file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/168891877.c | /*
* Copyright (c) 2020 Brian Callahan <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* planck -- text editor
*/
extern void *_syscall(void *n, void *a, void *b, void *c, void *d, void *e);
static void
_exit(int status)
{
_syscall((void *) 1, (void *) status, (void *) 0, (void *) 0, (void *) 0, (void *) 0);
}
static long
read(int d, void *buf, unsigned long nbytes)
{
return (long) _syscall((void *) 3, (void *) d, (void *) buf, (void *) nbytes, (void *) 0, (void *) 0);
}
static long
write(int d, const void *buf, unsigned long nbytes)
{
return (long) _syscall((void *) 4, (void *) d, (void *) buf, (void *) nbytes, (void *) 0, (void *) 0);
}
static long
open(const char *path, int flags, int mode)
{
return (long) _syscall((void *) 5, (void *) path, (void *) flags, (void *) mode, (void *) 0, (void *) 0);
}
static long
close(int d)
{
return (long) _syscall((void *) 6, (void *) d, (void *) 0, (void *) 0, (void *) 0, (void *) 0);
}
static unsigned long
strlen(const char *s)
{
char *t;
t = (char *) s;
while (*t != '\0')
t++;
return t - s;
}
static int
dgets(char *s, int size, int fd)
{
int i;
for (i = 0; i < size - 1; i++) {
if (read(fd, &s[i], 1) < 1)
return 0;
if (s[i] == '\n')
break;
}
s[i] = '\0';
return strlen(s);
}
static void
dputs(const char *s, int fd)
{
write(fd, s, strlen(s));
}
static void
dputi(int n, int fd)
{
char num[5];
int i = 0;
do {
num[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
for (i--; i >= 0; i--)
write(fd, &num[i], 1);
}
static int
dgeti(char *s, int size, int fd)
{
int i, n = 0;
for (i = 0; i < size - 1; i++) {
if (read(fd, &s[i], 1) < 1)
return 0;
if (s[i] == '\n')
break;
if (s[i] < '0' || s[i] > '9')
n = 1;
}
s[i] = '\0';
if (s[0] == '\0')
return 0;
if (n == 1)
return 1025;
n = 0;
for (i = 0; i < strlen(s); i++)
n = (n * 10) + (s[i] - '0');
return n;
}
int
main(int argc, char *argv[])
{
char linecol[1024][128];
char file[1024], line[128];
char buf[5], c;
int co = 0, fd, i, j, li = 0, save_name = 0;
if (argc > 2) {
dputs("usage: ", 2);
dputs(argv[0], 2);
dputs(" [file]\n", 2);
_exit(1);
}
for (i = 0; i < 1024; i++) {
for (j = 0; j < 128; j++)
linecol[i][j] = '\0';
}
if (argc == 2) {
for (i = 0; i < strlen(argv[1]); i++)
file[i] = argv[1][i];
file[i] = '\0';
save_name = 1;
if ((fd = open(file, 0x0000, 0)) < 3) {
dputs("planck: error: cannot open ", 2);
dputs(file, 2);
dputs("\n", 2);
goto begin;
}
while (read(fd, &c, 1) > 0) {
linecol[li][co] = c;
if (++co > 126) {
dputs("plank: error: line ", 2);
dputi(li, 2);
dputs(" is longer than 127 characters\n", 2);
}
if (c == '\n') {
if (++li > 1023) {
dputs("plank: error: ", 2);
dputs(argv[1], 2);
dputs(" is greater than 1024 lines\n", 2);
_exit(1);
}
co = 0;
}
}
if (close(fd) == -1) {
dputs("planck: error: could not close ", 2);
dputs(file, 2);
dputs("\n", 2);
_exit(1);
}
}
begin:
dputi(li, 1);
dputs("\n", 1);
get_command:
dputs("line: ", 1);
if ((li = dgeti(buf, sizeof(buf), 0)) > 1024) {
dputs("?\n", 1);
goto get_command;
}
dputs("command: ", 1);
(void) dgets(buf, sizeof(buf), 0);
switch (buf[0]) {
case 'd':
for (i = 0; i < 128; i++)
linecol[li - 1][i] = '\0';
for (i = li; i < 1024; i++) {
for (j = 0; j < 128; j++)
linecol[i - 1][j] = linecol[i][j];
}
for (i = 0; i < 128; i++)
linecol[1023][i] = '\0';
break;
case 'i':
if (li == 0) {
dputs("?\n", 1);
break;
}
--li;
if (linecol[li][0] != '\0' && linecol[li][0] != '\n') {
dputs(linecol[li], 1);
dputs("\n", 1);
}
if (dgets(line, sizeof(line) - 1, 0) == 0)
break;
for (i = 0; i < 128; i++)
linecol[li][i] = '\0';
for (i = 0; i < strlen(line); i++)
linecol[li][i] = line[i];
linecol[li][i] = '\n';
for (i = 0; linecol[i][0] != '\0'; i++)
;
if (i < li) {
for (j = 0; j < 128; j++)
linecol[i][j] = linecol[li][j];
for (j = 0; j < 128; j++)
linecol[li][j] = '\0';
}
break;
case 'n':
if (linecol[1023][0] != '\0') {
dputs("planck: error: cannot add line, already at limit\n", 2);
break;
}
for (i = 1022; i > li - 1; i--) {
if (linecol[i][0] != '\0') {
for (j = 0; j < 128; j++)
linecol[i + 1][j] = linecol[i][j];
for (j = 0; j < 128; j++)
linecol[i][j] = '\0';
}
}
linecol[li][0] = '\n';
break;
case 'p':
if (li == 0) {
for (i = 0; linecol[i][0] != '\0' ; i++) {
if (i < 999)
dputs(" ", 1);
if (i < 99)
dputs(" ", 1);
if (i < 9)
dputs(" ", 1);
dputi(i + 1, 1);
dputs(" ", 1);
dputs(linecol[i], 1);
}
} else if (linecol[li - 1][0] == '\0') {
dputs("?\n", 1);
} else {
dputs(linecol[li - 1], 1);
}
break;
case 'q':
goto done;
case 's':
if (save_name == 0) {
dputs("File: ", 1);
dgets(file, sizeof(file), 0);
save_name = 1;
}
if ((fd = open(file, 0x0001 | 0x0200, 000644)) == -1) {
dputs("planck: error: could not open ", 2);
dputs(file, 2);
dputs("\n", 2);
break;
}
for (li = 0; li < 1024; li++) {
if (linecol[li][0] == '\0')
break;
dputs(linecol[li], fd);
}
if (close(fd) == -1) {
dputs("planck: error: could not close ", 2);
dputs(file, 2);
dputs("\n", 2);
_exit(1);
}
break;
default:
dputs("?\n", 1);
}
goto get_command;
done:
return 0;
}
|
the_stack_data/1214034.c | #include <stdio.h>
#define MAXN 100005
char s[MAXN], t[MAXN];
int f[MAXN];
int main() {
printf("Input text: ");
scanf("%s", s);
printf("Input pattern: ");
scanf("%s", t);
f[0] = -1;
int i = 0, j = -1;
while (t[i]) {
while (~j && t[i] != t[j])
j = f[j];
f[++i] = ++j;
}
i = 0, j = 0;
while (s[i]) {
while (~j && s[i] != t[j])
j = f[j];
++i;
if (!t[++j]) {
printf("matched at %d\n", i - j);
}
}
}
|
the_stack_data/1054266.c | #include <stdio.h>
#include <math.h>
int main()
{
int x,y,X=1640/2,Y=1232/2;
printf("P5\n# CREATOR: 1640x1232.fine_crosshair_1200.c\n1640 1232\n255\n");
for(y=0; y<1232; ++y)
{
for(x=0; x<1640; ++x)
{
int r = sqrt((x-X)*(x-X)+(y-Y)*(y-Y));
printf("%c", (r==600 | (r<600 && (x==X || y==Y)))?0x00:0xFF);
}
}
return 0;
}
|
the_stack_data/150139893.c | /*
* Derived from:
* http://www.kernel.org/pub/linux/libs/klibc/
*/
/*
* lrand48.c
*/
#include <stdlib.h>
#include <stdint.h>
unsigned short __rand48_seed[3]; /* Common with mrand48.c, srand48.c */
long lrand48(void)
{
return (uint32_t)jrand48(__rand48_seed) >> 1;
}
int rand(void)
{
return (int)lrand48();
}
long random(void)
{
return lrand48();
}
|
the_stack_data/64977.c |
#include <stdio.h>
void scilab_rt_plot3d_i2d2i2i0i0s0i2_(int in00, int in01, int matrixin0[in00][in01],
int in10, int in11, double matrixin1[in10][in11],
int in20, int in21, int matrixin2[in20][in21],
int scalarin0,
int scalarin1,
char* scalarin2,
int in30, int in31, int matrixin3[in30][in31])
{
int i;
int j;
int val0 = 0;
double val1 = 0;
int val2 = 0;
int val3 = 0;
for (i = 0; i < in00; ++i) {
for (j = 0; j < in01; ++j) {
val0 += matrixin0[i][j];
}
}
printf("%d", val0);
for (i = 0; i < in10; ++i) {
for (j = 0; j < in11; ++j) {
val1 += matrixin1[i][j];
}
}
printf("%f", val1);
for (i = 0; i < in20; ++i) {
for (j = 0; j < in21; ++j) {
val2 += matrixin2[i][j];
}
}
printf("%d", val2);
printf("%d", scalarin0);
printf("%d", scalarin1);
printf("%s", scalarin2);
for (i = 0; i < in30; ++i) {
for (j = 0; j < in31; ++j) {
val3 += matrixin3[i][j];
}
}
printf("%d", val3);
}
|
the_stack_data/90765754.c | #include <stdio.h>
#include <string.h>
/* For all these problems, you may not use any
* string library functions; you may, however,
* define any helper functions that you may need */
/* Concatenates the src string to the end of the dest
* string, returns the dest string
*
* You can assume that src/dest are '\0' terminated,
* that dest hold enough space to store src+dest and
* src/dest do not overlap in memory */
char* strcat_m(char* dest, char* src) {
/* TODO: Implement this function */
return NULL;
}
/* Reverses a string and returns the a new string
* containing the reversed string
*
* You can assume that str is '\0' terminated */
char* strrev(char *str) {
/* TODO: Implement this function */
return NULL;
}
int main()
{
/* TODO: Implement test cases to check your implemenation
* You MAY use string library functions to test your code */
return 0;
}
|
the_stack_data/48575457.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
long unsigned qqai();
int p1_a_alloc_at_once = 16384;
unsigned long minimal_valid=0;
int real_ugly_way_to_keep_track_of_new_strings;
typedef struct alphax {
/* int star; */
char lc;
struct alphax *downp,*nextp,*fatherp;
long value;
} Anode;
Anode *alpha_add();
Anode * alpha_add_ver2();
Anode * allocate_rest_alpha();
Anode *afree=0;
Anode *first_access[256];
int anodes_allocations=0;
Anode *check_access[256];
void debug_call(int d) {
int x;
x=0;
printf("debug call \n");
x = d/x;
}
void check_me(x) int x; {
int i;
for (i=0;i<256;i++) {
if (first_access[i]!=check_access[i])
printf("++++++++ %d %d\n",i,x);
}
}
void p1_clear_anode(anode) Anode *anode;
{
(*anode).lc =0;
(*anode).downp =0;
(*anode).nextp =0;
(*anode).fatherp =0;
(*anode).value =99999999;
}
Anode *a1_get_node() {
Anode *temp;
int i;
if (afree) {
temp = afree;
afree = (Anode *) ((*afree).nextp);
p1_clear_anode(temp);
return temp;
}
temp = (Anode*) malloc(p1_a_alloc_at_once*sizeof(Anode));
if (!temp) {
printf("oopst!! run out of memory on anode allocations\n");
exit(3);
}
anodes_allocations++;
if ((anodes_allocations % 100) == 0)
printf("%% anode total allocated %luMeg\n",p1_a_alloc_at_once*anodes_allocations*sizeof(Anode)/(1024*1024));
for (i=1;i<p1_a_alloc_at_once;i++) {
(temp[i]).nextp = (Anode *) &(temp[i+1]);
}
afree = &(temp[1]);
(temp[p1_a_alloc_at_once-1]).nextp = 0;
p1_clear_anode(temp);
if (!minimal_valid) minimal_valid = (long unsigned) temp;
return temp;
}
int init_run = 0;
void alpha_init()
{
long unsigned i;
Anode *anode;
if (init_run) return;
init_run=1;
for (i=0;i<256;i++) {
anode = a1_get_node();
(*anode).lc = (char) i;
first_access[i]=anode;
/* check_access[i]=anode; */
}
i = qqai("aaa");
}
long unsigned qqai(str) char *str;
{
Anode *arun;
long unsigned j;
if (str[0]==0) return 0l;
arun = first_access[(unsigned)str[0]];
/* check_me(1); */
real_ugly_way_to_keep_track_of_new_strings=0;
j = (long unsigned) alpha_add(arun,&(str[1]));
/* j = (int) alpha_add_ver2(arun,&(str[1])); */
// printf("qqai %s %lx\n",str,j);
return j;
}
void cucu(ind) int ind;
{
printf("ilia error!! %d got qqia empty\n",ind);
}
char *alpha_ia1(ind,str) long unsigned ind; char *str;
{
int a,b,i=0;
Anode *run;
char tmp;
if (!ind) {str[0]=0; return str;}
run = (Anode *) ind;
while (run) {
str[i]= (*run).lc;
i++;
run = (Anode *) (*run).fatherp;
}
a = 0;
b = i-1;
str[i]=0;
while (b>a) {
tmp = str[b];
str[b]=str[a];
str[a]=tmp;
b--;
a++;
}
return str;
}
char alphas[64][50000];
int use_alpha=0;
char *qqia(long unsigned ind)
{
char *ch1;
/* int star; */
// printf("qqia %lx\n",ind);
use_alpha++;
if (use_alpha>63) use_alpha=0;
if (!ind) {
alphas[use_alpha][0]=0;
return alphas[use_alpha];
}
// if (ind<minimal_valid) {
// printf("warning!! ilia qqia got ind=0x%lx which is illegal min=0x%lu \n",ind,minimal_valid);
// minimal_valid = ind;
// debug_call(ind);
// }
/*
star = ( * (Anode *)ind).star;
if (star != 178) {
printf("error!! ilia qqia got ind=%d which was not starred\n",ind);
alphas[use_alpha][0]=0;
return alphas[use_alpha];
}
*/
if (!ind) {
alphas[use_alpha][0]=0;
return alphas[use_alpha];
}
ch1 = alpha_ia1(ind,alphas[use_alpha]);
if (!ch1[0]) {
cucu(ind);
}
return ch1;
}
Anode *alpha_add_ver2(arun,str) Anode *arun; char *str;
{
Anode * last;
Anode *hrun;
Anode *anode,*newdown,*down,*next,*prevnext;
int i;
if (str[0]==0) return (Anode *) arun;
hrun=arun;
for (i=0;str[i];i++) {
down = (Anode*)(*hrun).downp;
if (!down) {
last = allocate_rest_alpha(hrun,&(str[i]));
real_ugly_way_to_keep_track_of_new_strings=1;
return last;
} else {
if (str[i]<(*down).lc) {
last = allocate_rest_alpha(hrun,&(str[i]));
newdown = (Anode*)(*hrun).downp;
(*newdown).nextp = (Anode *)down;
real_ugly_way_to_keep_track_of_new_strings=1;
return last;
} else if (str[i]==(*down).lc) {
hrun=down;
} else {
prevnext = down;
next = (Anode*)(*down).nextp;
while (next && ( (*next).lc < str[i])) {
prevnext = next;
next = (Anode*)(*next).nextp;
}
if (!next) {
anode = a1_get_node();
(*anode).lc=str[i];
last = allocate_rest_alpha(anode,&(str[i+1]));
(*prevnext).nextp = (Anode *) anode;
(*anode).fatherp = (Anode *) hrun;
real_ugly_way_to_keep_track_of_new_strings=1;
return last;
} else if ((*next).lc == str[i]){
hrun = next;
} else {
anode = a1_get_node();
(*anode).lc=str[i];
last = allocate_rest_alpha(anode,&(str[i]));
(*anode).nextp=(Anode *) next;
(*anode).fatherp = (Anode *) hrun;
(*prevnext).nextp = (Anode *) anode;
real_ugly_way_to_keep_track_of_new_strings=1;
return last;
}
}
}
}
return (Anode *)hrun;
}
Anode * alpha_add(arun,str) Anode *arun; char *str;
{
Anode * last;
Anode *anode,*newdown,*down,*next,*prevnext;
if (str[0]==0) return (Anode *) arun;
down = (Anode*)(*arun).downp;
if (!down) {
last = allocate_rest_alpha(arun,str);
real_ugly_way_to_keep_track_of_new_strings=1;
return last;
} else {
if (str[0]<(*down).lc) {
last = allocate_rest_alpha(arun,str);
newdown = (Anode*)(*arun).downp;
(*newdown).nextp = (Anode *)down;
real_ugly_way_to_keep_track_of_new_strings=1;
return last;
} else if (str[0]==(*down).lc) {
return alpha_add(down,&(str[1]));
} else {
prevnext = down;
next = (Anode*)(*down).nextp;
while (next && ( (*next).lc < str[0])) {
prevnext = next;
next = (Anode*)(*next).nextp;
}
if (!next) {
anode = a1_get_node();
(*anode).lc=str[0];
last = allocate_rest_alpha(anode,&(str[1]));
(*prevnext).nextp = (Anode *) anode;
(*anode).fatherp = (Anode *) arun;
real_ugly_way_to_keep_track_of_new_strings=1;
} else if ((*next).lc == str[0]){
return alpha_add(next,&(str[1]));
} else {
anode = a1_get_node();
(*anode).lc=str[0];
last = allocate_rest_alpha(anode,&(str[1]));
(*anode).nextp=(Anode *) next;
(*anode).fatherp = (Anode *) arun;
(*prevnext).nextp = (Anode *) anode;
real_ugly_way_to_keep_track_of_new_strings=1;
}
return last;
}
}
}
Anode * allocate_rest_alpha(arun,str) Anode *arun; char *str;
{
Anode *anode;
if (str[0]==0) return (Anode *)arun;
anode = a1_get_node();
(*arun).downp = (Anode *) anode;
(*anode).fatherp = (Anode *) arun;
(*anode).lc = str[0];
return allocate_rest_alpha(anode,&(str[1]));
}
void qqsa(ind,val) long unsigned ind; long val;
{
Anode *x;
x = (Anode *)ind;
(*x).value = val;
}
long qqas(ind) long unsigned ind;
{
Anode *x;
x = (Anode *)ind;
return (*x).value;
}
int Index_ilia(s, t)
char *s, *t;
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++) {
for (j = i, k = 0; (s[j]!=0)&&(t[k] != '\0') &&(s[j] == t[k]); j++, k++);
if (t[k] == '\0')
return (i);
}
return (-1);
}
|
the_stack_data/231393494.c | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<linux/if_ether.h>
unsigned short int cksum(char buffer[], int size){ //校验函数
unsigned long sum = 0;
unsigned short int answer;
unsigned short int *temp;
temp = (short int *)buffer;
for( ; temp<buffer+size; temp+=1)
sum += *temp;
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = ~sum;
return answer;
}
int main(){
unsigned char buffer[1024];
int i;
// int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);//不知为啥,无法设置原始套接字在网络层抓IP数据报
int sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP)); //此处,利用原始套接字在数据链路层抓取MAC帧,去掉
if(sockfd < 0){ //14个字节的MAC帧首部即可
printf("create sock failed\n");
return -1;
}
int n = recvfrom(sockfd, buffer, 1024, 0, NULL, NULL); //接收MAC帧
printf("receive %d bytes\n", n);
for(i=14; i<n; i++){ //去掉MAC帧首部,直接输出IP数据报每个字节的数据
if((i-14) % 16 == 0)
printf("\n");
printf("%d ",buffer[i]);
}
printf("\n");
printf("ipcksum: %d\n", cksum(buffer+14, 20)); //此处再次校验时,应当输出0
return 0;
}
|
the_stack_data/811658.c | #include<stdio.h>
int main() {
float side, area;
printf("Enter the length of the side: ");
scanf("%f", &side);
area = side * side;
printf("Area of the square of length %.2f is %.2f.", side, area);
return 0;
}
|
the_stack_data/1135851.c | #include <sys/types.h>
#include <sys/timeb.h>
static struct timeb gorp = {
0L,
0,
5*60,
1
};
ftime(gorpp)
struct timeb *gorpp;
{
*gorpp = gorp;
return(0);
}
|
the_stack_data/104684.c | #include<stdio.h>
int main()
{
int num;
while(scanf("%d",&num)==1)
{
if(num==42)
{
break;
}
printf("%d\n",num);
}
return 0;
}
|
the_stack_data/680050.c | /*prog0510.c : Funções e Prodedimentos
*AUTOR: Luis Damas
*DATA: 14/12/2020
*/
#include <stdio.h>
int xToUpper(char ch)
{
if (ch >= 'a' && ch <= 'z')
return ch + 'A' - 'a';
else
return ch;
}
main()
{
char c;
while(1)
{
c=getchar();
putchar(xToUpper(c));
}
} |
the_stack_data/41362.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: [email protected], [email protected], [email protected],
[email protected], [email protected])
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
/*
Example use of firstprivate()
*/
#include <omp.h>
void foo(int *a,int n,int g)
{
int i;
#pragma omp parallel for private (i) firstprivate (n,g)
for (i = 0; i <= n - 1; i += 1) {
a[i] = a[i] + g;
}
}
int a[100];
int main()
{
int i;
int n = 100;
#pragma omp parallel for private (i)
for (i = 0; i <= n - 1; i += 1) {
a[i] = i;
}
foo(a,100,7);
for (i = 0; i <= n - 1; i += 1) {
printf("%d\n",a[i]);
}
return 0;
}
|
the_stack_data/66424.c | // BUG: Dentry still in use [unmount of vfat loop0]
// https://syzkaller.appspot.com/bug?id=304bc4c76f40a8a7113a
// status:0
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <linux/capability.h>
#include <linux/futex.h>
#include <linux/loop.h>
static unsigned long long procid;
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
static uint64_t current_time_ms(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
exit(1);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static void thread_start(void* (*fn)(void*), void* arg)
{
pthread_t th;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 128 << 10);
int i = 0;
for (; i < 100; i++) {
if (pthread_create(&th, &attr, fn, arg) == 0) {
pthread_attr_destroy(&attr);
return;
}
if (errno == EAGAIN) {
usleep(50);
continue;
}
break;
}
exit(1);
}
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (ev->state)
exit(1);
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
static int event_isset(event_t* ev)
{
return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE);
}
static int event_timedwait(event_t* ev, uint64_t timeout)
{
uint64_t start = current_time_ms();
uint64_t now = start;
for (;;) {
uint64_t remain = timeout - (now - start);
struct timespec ts;
ts.tv_sec = remain / 1000;
ts.tv_nsec = (remain % 1000) * 1000 * 1000;
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts);
if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
return 1;
now = current_time_ms();
if (now - start > timeout)
return 0;
}
}
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
struct fs_image_segment {
void* data;
uintptr_t size;
uintptr_t offset;
};
#define IMAGE_MAX_SEGMENTS 4096
#define IMAGE_MAX_SIZE (129 << 20)
#define sys_memfd_create 319
static unsigned long fs_image_segment_check(unsigned long size,
unsigned long nsegs,
struct fs_image_segment* segs)
{
if (nsegs > IMAGE_MAX_SEGMENTS)
nsegs = IMAGE_MAX_SEGMENTS;
for (size_t i = 0; i < nsegs; i++) {
if (segs[i].size > IMAGE_MAX_SIZE)
segs[i].size = IMAGE_MAX_SIZE;
segs[i].offset %= IMAGE_MAX_SIZE;
if (segs[i].offset > IMAGE_MAX_SIZE - segs[i].size)
segs[i].offset = IMAGE_MAX_SIZE - segs[i].size;
if (size < segs[i].offset + segs[i].offset)
size = segs[i].offset + segs[i].offset;
}
if (size > IMAGE_MAX_SIZE)
size = IMAGE_MAX_SIZE;
return size;
}
static int setup_loop_device(long unsigned size, long unsigned nsegs,
struct fs_image_segment* segs,
const char* loopname, int* memfd_p, int* loopfd_p)
{
int err = 0, loopfd = -1;
size = fs_image_segment_check(size, nsegs, segs);
int memfd = syscall(sys_memfd_create, "syzkaller", 0);
if (memfd == -1) {
err = errno;
goto error;
}
if (ftruncate(memfd, size)) {
err = errno;
goto error_close_memfd;
}
for (size_t i = 0; i < nsegs; i++) {
if (pwrite(memfd, segs[i].data, segs[i].size, segs[i].offset) < 0) {
}
}
loopfd = open(loopname, O_RDWR);
if (loopfd == -1) {
err = errno;
goto error_close_memfd;
}
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
if (errno != EBUSY) {
err = errno;
goto error_close_loop;
}
ioctl(loopfd, LOOP_CLR_FD, 0);
usleep(1000);
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
err = errno;
goto error_close_loop;
}
}
*memfd_p = memfd;
*loopfd_p = loopfd;
return 0;
error_close_loop:
close(loopfd);
error_close_memfd:
close(memfd);
error:
errno = err;
return -1;
}
static long syz_mount_image(volatile long fsarg, volatile long dir,
volatile unsigned long size,
volatile unsigned long nsegs,
volatile long segments, volatile long flags,
volatile long optsarg)
{
struct fs_image_segment* segs = (struct fs_image_segment*)segments;
int res = -1, err = 0, loopfd = -1, memfd = -1, need_loop_device = !!segs;
char* mount_opts = (char*)optsarg;
char* target = (char*)dir;
char* fs = (char*)fsarg;
char* source = NULL;
char loopname[64];
if (need_loop_device) {
memset(loopname, 0, sizeof(loopname));
snprintf(loopname, sizeof(loopname), "/dev/loop%llu", procid);
if (setup_loop_device(size, nsegs, segs, loopname, &memfd, &loopfd) == -1)
return -1;
source = loopname;
}
mkdir(target, 0777);
char opts[256];
memset(opts, 0, sizeof(opts));
if (strlen(mount_opts) > (sizeof(opts) - 32)) {
}
strncpy(opts, mount_opts, sizeof(opts) - 32);
if (strcmp(fs, "iso9660") == 0) {
flags |= MS_RDONLY;
} else if (strncmp(fs, "ext", 3) == 0) {
if (strstr(opts, "errors=panic") || strstr(opts, "errors=remount-ro") == 0)
strcat(opts, ",errors=continue");
} else if (strcmp(fs, "xfs") == 0) {
strcat(opts, ",nouuid");
}
res = mount(source, target, fs, flags, opts);
if (res == -1) {
err = errno;
goto error_clear_loop;
}
res = open(target, O_RDONLY | O_DIRECTORY);
if (res == -1) {
err = errno;
}
error_clear_loop:
if (need_loop_device) {
ioctl(loopfd, LOOP_CLR_FD, 0);
close(loopfd);
close(memfd);
}
errno = err;
return res;
}
static void setup_common()
{
if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) {
}
}
static void loop();
static void sandbox_common()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setsid();
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = (200 << 20);
setrlimit(RLIMIT_AS, &rlim);
rlim.rlim_cur = rlim.rlim_max = 32 << 20;
setrlimit(RLIMIT_MEMLOCK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 136 << 20;
setrlimit(RLIMIT_FSIZE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 1 << 20;
setrlimit(RLIMIT_STACK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 0;
setrlimit(RLIMIT_CORE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 256;
setrlimit(RLIMIT_NOFILE, &rlim);
if (unshare(CLONE_NEWNS)) {
}
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) {
}
if (unshare(CLONE_NEWIPC)) {
}
if (unshare(0x02000000)) {
}
if (unshare(CLONE_NEWUTS)) {
}
if (unshare(CLONE_SYSVSEM)) {
}
typedef struct {
const char* name;
const char* value;
} sysctl_t;
static const sysctl_t sysctls[] = {
{"/proc/sys/kernel/shmmax", "16777216"},
{"/proc/sys/kernel/shmall", "536870912"},
{"/proc/sys/kernel/shmmni", "1024"},
{"/proc/sys/kernel/msgmax", "8192"},
{"/proc/sys/kernel/msgmni", "1024"},
{"/proc/sys/kernel/msgmnb", "1024"},
{"/proc/sys/kernel/sem", "1024 1048576 500 1024"},
};
unsigned i;
for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++)
write_file(sysctls[i].name, sysctls[i].value);
}
static int wait_for_loop(int pid)
{
if (pid < 0)
exit(1);
int status = 0;
while (waitpid(-1, &status, __WALL) != pid) {
}
return WEXITSTATUS(status);
}
static void drop_caps(void)
{
struct __user_cap_header_struct cap_hdr = {};
struct __user_cap_data_struct cap_data[2] = {};
cap_hdr.version = _LINUX_CAPABILITY_VERSION_3;
cap_hdr.pid = getpid();
if (syscall(SYS_capget, &cap_hdr, &cap_data))
exit(1);
const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE);
cap_data[0].effective &= ~drop;
cap_data[0].permitted &= ~drop;
cap_data[0].inheritable &= ~drop;
if (syscall(SYS_capset, &cap_hdr, &cap_data))
exit(1);
}
static int do_sandbox_none(void)
{
if (unshare(CLONE_NEWPID)) {
}
int pid = fork();
if (pid != 0)
return wait_for_loop(pid);
setup_common();
sandbox_common();
drop_caps();
if (unshare(CLONE_NEWNET)) {
}
loop();
exit(1);
}
struct thread_t {
int created, call;
event_t ready, done;
};
static struct thread_t threads[16];
static void execute_call(int call);
static int running;
static void* thr(void* arg)
{
struct thread_t* th = (struct thread_t*)arg;
for (;;) {
event_wait(&th->ready);
event_reset(&th->ready);
execute_call(th->call);
__atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED);
event_set(&th->done);
}
return 0;
}
static void loop(void)
{
int i, call, thread;
int collide = 0;
again:
for (call = 0; call < 2; call++) {
for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0]));
thread++) {
struct thread_t* th = &threads[thread];
if (!th->created) {
th->created = 1;
event_init(&th->ready);
event_init(&th->done);
event_set(&th->done);
thread_start(thr, th);
}
if (!event_isset(&th->done))
continue;
event_reset(&th->done);
th->call = call;
__atomic_fetch_add(&running, 1, __ATOMIC_RELAXED);
event_set(&th->ready);
if (collide && (call % 2) == 0)
break;
event_timedwait(&th->done, 50 + (call == 1 ? 50 : 0));
break;
}
}
for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++)
sleep_ms(1);
if (!collide) {
collide = 1;
goto again;
}
}
void execute_call(int call)
{
switch (call) {
case 0:
memcpy((void*)0x200002c0, "./file0\000", 8);
memcpy((void*)0x20000000, "./file0\000", 8);
memcpy((void*)0x20000340, "incremental-fs\000", 15);
syscall(__NR_mount, 0x200002c0ul, 0x20000000ul, 0x20000340ul, 0ul, 0ul);
break;
case 1:
memcpy((void*)0x20000440, "vfat\000", 5);
memcpy((void*)0x20000100, "./file0\000", 8);
*(uint64_t*)0x20000300 = 0x20000000;
memcpy((void*)0x20000000,
"\xeb\x3c\x90\x6d\x6b\x66\x73\x2e\x66\x61\x74\x00\x02\x80\x01\x00"
"\x02\x40\x00\x00\x04\xf8\x01",
23);
*(uint64_t*)0x20000308 = 0x17;
*(uint64_t*)0x20000310 = 0;
*(uint64_t*)0x20000318 = 0;
*(uint64_t*)0x20000320 = 0;
*(uint64_t*)0x20000328 = 0x10e00;
*(uint8_t*)0x20000240 = 0;
syz_mount_image(0x20000440, 0x20000100, 0, 2, 0x20000300, 0, 0x20000240);
break;
}
}
int main(void)
{
syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
do_sandbox_none();
return 0;
}
|
the_stack_data/165764509.c | #include <stdio.h>
int main(void)
{
printf("Hi <string>!\n");
fprintf(stderr, "Ho, I'll fail miserably with exit code 33!\n");
return 33;
}
|
the_stack_data/168893524.c | #include <stdio.h>
int main()
{
int x;
x = 1;
while( x <= 10 )
{
printf("%d\n",x);
x++;
}
return(0);
}
|
the_stack_data/812883.c | /*
* Mesa 3-D graphics library
* Version: 4.0
*
* Copyright (C) 1999-2001 Brian Paul All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* Authors:
* David Bucciarelli
* Brian Paul
* Daryll Strauss
* Keith Whitwell
* Daniel Borca
* Hiroshi Morii
*/
/* fxsetup.c - 3Dfx VooDoo rendering mode setup functions */
#ifdef HAVE_CONFIG_H
#include "conf.h"
#endif
#if defined(FX)
#include "fxdrv.h"
#include "enums.h"
#include "tnl.h"
#include "tnl/t_context.h"
#include "swrast.h"
#include "texstore.h"
static void
fxTexValidate(GLcontext * ctx, struct gl_texture_object *tObj)
{
tfxTexInfo *ti = fxTMGetTexInfo(tObj);
GLint minl, maxl;
if (ti->validated) {
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxTexValidate(NOP)\n");
}
return;
}
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxTexValidate(%p (%d))\n", (void *)tObj, tObj->Name);
}
ti->tObj = tObj;
minl = ti->minLevel = tObj->BaseLevel;
maxl = ti->maxLevel = MIN2(tObj->MaxLevel, tObj->Image[0][0]->MaxLog2);
#if FX_RESCALE_BIG_TEXURES_HACK
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
/* [dBorca]
* Fake textures larger than HW supports:
* 1) we have mipmaps. Then we just push up to the first supported
* LOD. A possible drawback is that Mesa will ignore the skipped
* LODs on further texture handling.
* Will this interfere with GL_TEXTURE_[MIN|BASE]_LEVEL? How?
* 2) we don't have mipmaps. We need to rescale the big LOD in place.
* The above approach is somehow dumb! we might have rescaled
* once in TexImage2D to accomodate aspect ratio, and now we
* are rescaling again. The thing is, in TexImage2D we don't
* know whether we'll hit 1) or 2) by the time of validation.
*/
if ((tObj->MinFilter == GL_NEAREST) || (tObj->MinFilter == GL_LINEAR)) {
/* no mipmaps! */
struct gl_texture_image *texImage = tObj->Image[0][minl];
tfxMipMapLevel *mml = FX_MIPMAP_DATA(texImage);
GLint _w, _h, maxSize = 1 << fxMesa->textureMaxLod;
if ((mml->width > maxSize) || (mml->height > maxSize)) {
/* need to rescale */
GLint texelBytes = texImage->TexFormat->TexelBytes;
GLvoid *texImage_Data = texImage->Data;
_w = MIN2(texImage->Width, maxSize);
_h = MIN2(texImage->Height, maxSize);
if (TDFX_DEBUG & VERBOSE_TEXTURE) {
fprintf(stderr, "fxTexValidate: rescaling %d x %d -> %d x %d\n",
texImage->Width, texImage->Height, _w, _h);
}
/* we should leave these as is and... (!) */
texImage->Width = _w;
texImage->Height = _h;
fxTexGetInfo(_w, _h, NULL, NULL, NULL, NULL,
&(mml->wScale), &(mml->hScale));
_w *= mml->wScale;
_h *= mml->hScale;
texImage->Data = _mesa_malloc(_w * _h * texelBytes);
_mesa_rescale_teximage2d(texelBytes,
mml->width,
_w * texelBytes, /* dst stride */
mml->width, mml->height, /* src */
_w, _h, /* dst */
texImage_Data /*src*/, texImage->Data /*dst*/ );
_mesa_free(texImage_Data);
mml->width = _w;
mml->height = _h;
/* (!) ... and set mml->wScale = _w / texImage->Width */
}
} else {
/* mipmapping */
if (maxl - minl > fxMesa->textureMaxLod) {
/* skip a certain number of LODs */
minl += maxl - fxMesa->textureMaxLod;
if (TDFX_DEBUG & VERBOSE_TEXTURE) {
fprintf(stderr, "fxTexValidate: skipping %d LODs\n", minl - ti->minLevel);
}
ti->minLevel = tObj->BaseLevel = minl;
}
}
}
#endif
fxTexGetInfo(tObj->Image[0][minl]->Width, tObj->Image[0][minl]->Height,
&(FX_largeLodLog2(ti->info)), &(FX_aspectRatioLog2(ti->info)),
&(ti->sScale), &(ti->tScale),
NULL, NULL);
if ((tObj->MinFilter != GL_NEAREST) && (tObj->MinFilter != GL_LINEAR))
fxTexGetInfo(tObj->Image[0][maxl]->Width, tObj->Image[0][maxl]->Height,
&(FX_smallLodLog2(ti->info)), NULL,
NULL, NULL, NULL, NULL);
else
FX_smallLodLog2(ti->info) = FX_largeLodLog2(ti->info);
/* [dBorca] this is necessary because of fxDDCompressedTexImage2D */
if (ti->padded) {
struct gl_texture_image *texImage = tObj->Image[0][minl];
tfxMipMapLevel *mml = FX_MIPMAP_DATA(texImage);
if (mml->wScale != 1 || mml->hScale != 1) {
ti->sScale /= mml->wScale;
ti->tScale /= mml->hScale;
}
}
ti->baseLevelInternalFormat = tObj->Image[0][minl]->Format;
ti->validated = GL_TRUE;
ti->info.data = NULL;
}
static void
fxPrintUnitsMode(const char *msg, GLuint mode)
{
fprintf(stderr,
"%s: (0x%x) %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
msg,
mode,
(mode & FX_UM_E0_REPLACE) ? "E0_REPLACE, " : "",
(mode & FX_UM_E0_MODULATE) ? "E0_MODULATE, " : "",
(mode & FX_UM_E0_DECAL) ? "E0_DECAL, " : "",
(mode & FX_UM_E0_BLEND) ? "E0_BLEND, " : "",
(mode & FX_UM_E1_REPLACE) ? "E1_REPLACE, " : "",
(mode & FX_UM_E1_MODULATE) ? "E1_MODULATE, " : "",
(mode & FX_UM_E1_DECAL) ? "E1_DECAL, " : "",
(mode & FX_UM_E1_BLEND) ? "E1_BLEND, " : "",
(mode & FX_UM_E0_ALPHA) ? "E0_ALPHA, " : "",
(mode & FX_UM_E0_LUMINANCE) ? "E0_LUMINANCE, " : "",
(mode & FX_UM_E0_LUMINANCE_ALPHA) ? "E0_LUMINANCE_ALPHA, " : "",
(mode & FX_UM_E0_INTENSITY) ? "E0_INTENSITY, " : "",
(mode & FX_UM_E0_RGB) ? "E0_RGB, " : "",
(mode & FX_UM_E0_RGBA) ? "E0_RGBA, " : "",
(mode & FX_UM_E1_ALPHA) ? "E1_ALPHA, " : "",
(mode & FX_UM_E1_LUMINANCE) ? "E1_LUMINANCE, " : "",
(mode & FX_UM_E1_LUMINANCE_ALPHA) ? "E1_LUMINANCE_ALPHA, " : "",
(mode & FX_UM_E1_INTENSITY) ? "E1_INTENSITY, " : "",
(mode & FX_UM_E1_RGB) ? "E1_RGB, " : "",
(mode & FX_UM_E1_RGBA) ? "E1_RGBA, " : "",
(mode & FX_UM_COLOR_ITERATED) ? "COLOR_ITERATED, " : "",
(mode & FX_UM_COLOR_CONSTANT) ? "COLOR_CONSTANT, " : "",
(mode & FX_UM_ALPHA_ITERATED) ? "ALPHA_ITERATED, " : "",
(mode & FX_UM_ALPHA_CONSTANT) ? "ALPHA_CONSTANT, " : "");
}
static GLuint
fxGetTexSetConfiguration(GLcontext * ctx,
struct gl_texture_object *tObj0,
struct gl_texture_object *tObj1)
{
GLuint unitsmode = 0;
GLuint envmode = 0;
GLuint ifmt = 0;
if ((ctx->Light.ShadeModel == GL_SMOOTH) || 1 ||
(ctx->Point.SmoothFlag) ||
(ctx->Line.SmoothFlag) ||
(ctx->Polygon.SmoothFlag)) unitsmode |= FX_UM_ALPHA_ITERATED;
else
unitsmode |= FX_UM_ALPHA_CONSTANT;
if (ctx->Light.ShadeModel == GL_SMOOTH || 1)
unitsmode |= FX_UM_COLOR_ITERATED;
else
unitsmode |= FX_UM_COLOR_CONSTANT;
/*
OpenGL Feeds Texture 0 into Texture 1
Glide Feeds Texture 1 into Texture 0
*/
if (tObj0) {
tfxTexInfo *ti0 = fxTMGetTexInfo(tObj0);
switch (ti0->baseLevelInternalFormat) {
case GL_ALPHA:
ifmt |= FX_UM_E0_ALPHA;
break;
case GL_LUMINANCE:
ifmt |= FX_UM_E0_LUMINANCE;
break;
case GL_LUMINANCE_ALPHA:
ifmt |= FX_UM_E0_LUMINANCE_ALPHA;
break;
case GL_INTENSITY:
ifmt |= FX_UM_E0_INTENSITY;
break;
case GL_RGB:
ifmt |= FX_UM_E0_RGB;
break;
case GL_RGBA:
ifmt |= FX_UM_E0_RGBA;
break;
}
switch (ctx->Texture.Unit[0].EnvMode) {
case GL_DECAL:
envmode |= FX_UM_E0_DECAL;
break;
case GL_MODULATE:
envmode |= FX_UM_E0_MODULATE;
break;
case GL_REPLACE:
envmode |= FX_UM_E0_REPLACE;
break;
case GL_BLEND:
envmode |= FX_UM_E0_BLEND;
break;
case GL_ADD:
envmode |= FX_UM_E0_ADD;
break;
default:
/* do nothing */
break;
}
}
if (tObj1) {
tfxTexInfo *ti1 = fxTMGetTexInfo(tObj1);
switch (ti1->baseLevelInternalFormat) {
case GL_ALPHA:
ifmt |= FX_UM_E1_ALPHA;
break;
case GL_LUMINANCE:
ifmt |= FX_UM_E1_LUMINANCE;
break;
case GL_LUMINANCE_ALPHA:
ifmt |= FX_UM_E1_LUMINANCE_ALPHA;
break;
case GL_INTENSITY:
ifmt |= FX_UM_E1_INTENSITY;
break;
case GL_RGB:
ifmt |= FX_UM_E1_RGB;
break;
case GL_RGBA:
ifmt |= FX_UM_E1_RGBA;
break;
default:
/* do nothing */
break;
}
switch (ctx->Texture.Unit[1].EnvMode) {
case GL_DECAL:
envmode |= FX_UM_E1_DECAL;
break;
case GL_MODULATE:
envmode |= FX_UM_E1_MODULATE;
break;
case GL_REPLACE:
envmode |= FX_UM_E1_REPLACE;
break;
case GL_BLEND:
envmode |= FX_UM_E1_BLEND;
break;
case GL_ADD:
envmode |= FX_UM_E1_ADD;
break;
default:
/* do nothing */
break;
}
}
unitsmode |= (ifmt | envmode);
if (TDFX_DEBUG & (VERBOSE_DRIVER | VERBOSE_TEXTURE))
fxPrintUnitsMode("fxGetTexSetConfiguration", unitsmode);
return unitsmode;
}
/************************************************************************/
/************************* Rendering Mode SetUp *************************/
/************************************************************************/
/************************* Single Texture Set ***************************/
static void
fxSetupSingleTMU_NoLock(fxMesaContext fxMesa, struct gl_texture_object *tObj)
{
tfxTexInfo *ti = fxTMGetTexInfo(tObj);
int tmu;
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupSingleTMU_NoLock(%p (%d))\n", (void *)tObj, tObj->Name);
}
ti->lastTimeUsed = fxMesa->texBindNumber;
/* Make sure we're not loaded incorrectly */
if (ti->isInTM) {
if (ti->LODblend) {
if (ti->whichTMU != FX_TMU_SPLIT)
fxTMMoveOutTM(fxMesa, tObj);
}
else {
if (ti->whichTMU == FX_TMU_SPLIT)
fxTMMoveOutTM(fxMesa, tObj);
}
}
/* Make sure we're loaded correctly */
if (!ti->isInTM) {
if (ti->LODblend)
fxTMMoveInTM_NoLock(fxMesa, tObj, FX_TMU_SPLIT);
else {
if (fxMesa->haveTwoTMUs) {
if (fxTMCheckStartAddr(fxMesa, FX_TMU0, ti)) {
fxTMMoveInTM_NoLock(fxMesa, tObj, FX_TMU0);
}
else {
fxTMMoveInTM_NoLock(fxMesa, tObj, FX_TMU1);
}
}
else
fxTMMoveInTM_NoLock(fxMesa, tObj, FX_TMU0);
}
}
if (ti->LODblend && ti->whichTMU == FX_TMU_SPLIT) {
/* broadcast */
if ((ti->info.format == GR_TEXFMT_P_8)
&& (!fxMesa->haveGlobalPaletteTexture)) {
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupSingleTMU_NoLock: uploading texture palette\n");
}
grTexDownloadTable(ti->paltype, &(ti->palette));
}
grTexClampMode(GR_TMU0, ti->sClamp, ti->tClamp);
grTexClampMode(GR_TMU1, ti->sClamp, ti->tClamp);
grTexFilterMode(GR_TMU0, ti->minFilt, ti->maxFilt);
grTexFilterMode(GR_TMU1, ti->minFilt, ti->maxFilt);
grTexMipMapMode(GR_TMU0, ti->mmMode, ti->LODblend);
grTexMipMapMode(GR_TMU1, ti->mmMode, ti->LODblend);
grTexSource(GR_TMU0, ti->tm[FX_TMU0]->startAddr,
GR_MIPMAPLEVELMASK_ODD, &(ti->info));
grTexSource(GR_TMU1, ti->tm[FX_TMU1]->startAddr,
GR_MIPMAPLEVELMASK_EVEN, &(ti->info));
}
else {
if (ti->whichTMU == FX_TMU_BOTH)
tmu = FX_TMU0;
else
tmu = ti->whichTMU;
/* pointcast */
if ((ti->info.format == GR_TEXFMT_P_8)
&& (!fxMesa->haveGlobalPaletteTexture)) {
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupSingleTMU_NoLock: uploading texture palette\n");
}
fxMesa->Glide.grTexDownloadTableExt(tmu, ti->paltype, &(ti->palette));
}
/* KW: The alternative is to do the download to the other tmu. If
* we get to this point, I think it means we are thrashing the
* texture memory, so perhaps it's not a good idea.
*/
if (ti->LODblend && (TDFX_DEBUG & VERBOSE_DRIVER)) {
fprintf(stderr, "fxSetupSingleTMU_NoLock: not blending texture - only one tmu\n");
}
grTexClampMode(tmu, ti->sClamp, ti->tClamp);
grTexFilterMode(tmu, ti->minFilt, ti->maxFilt);
grTexMipMapMode(tmu, ti->mmMode, FXFALSE);
grTexSource(tmu, ti->tm[tmu]->startAddr, GR_MIPMAPLEVELMASK_BOTH, &(ti->info));
}
}
static void
fxSelectSingleTMUSrc_NoLock(fxMesaContext fxMesa, GLint tmu, FxBool LODblend)
{
struct tdfx_texcombine tex0, tex1;
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSelectSingleTMUSrc_NoLock(%d, %d)\n", tmu, LODblend);
}
tex0.InvertRGB = FXFALSE;
tex0.InvertAlpha = FXFALSE;
tex1.InvertRGB = FXFALSE;
tex1.InvertAlpha = FXFALSE;
if (LODblend) {
tex0.FunctionRGB = GR_COMBINE_FUNCTION_BLEND;
tex0.FactorRGB = GR_COMBINE_FACTOR_ONE_MINUS_LOD_FRACTION;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_BLEND;
tex0.FactorAlpha = GR_COMBINE_FACTOR_ONE_MINUS_LOD_FRACTION;
tex1.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
fxMesa->tmuSrc = FX_TMU_SPLIT;
}
else {
if (tmu != FX_TMU1) {
tex0.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex0.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex0.FactorAlpha = GR_COMBINE_FACTOR_NONE;
tex1.FunctionRGB = GR_COMBINE_FUNCTION_ZERO;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_ZERO;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
fxMesa->tmuSrc = FX_TMU0;
}
else {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
/* correct values to set TMU0 in passthrough mode */
tex0.FunctionRGB = GR_COMBINE_FUNCTION_BLEND;
tex0.FactorRGB = GR_COMBINE_FACTOR_ONE;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_BLEND;
tex0.FactorAlpha = GR_COMBINE_FACTOR_ONE;
fxMesa->tmuSrc = FX_TMU1;
}
}
grTexCombine(GR_TMU0,
tex0.FunctionRGB,
tex0.FactorRGB,
tex0.FunctionAlpha,
tex0.FactorAlpha,
tex0.InvertRGB,
tex0.InvertAlpha);
if (fxMesa->haveTwoTMUs) {
grTexCombine(GR_TMU1,
tex1.FunctionRGB,
tex1.FactorRGB,
tex1.FunctionAlpha,
tex1.FactorAlpha,
tex1.InvertRGB,
tex1.InvertAlpha);
}
}
static void
fxSetupTextureSingleTMU_NoLock(GLcontext * ctx, GLuint textureset)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
struct tdfx_combine alphaComb, colorComb;
GrCombineLocal_t localc, locala;
GLuint unitsmode;
GLint ifmt;
tfxTexInfo *ti;
struct gl_texture_object *tObj = ctx->Texture.Unit[textureset]._Current;
int tmu;
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupTextureSingleTMU_NoLock(%d)\n", textureset);
}
ti = fxTMGetTexInfo(tObj);
fxTexValidate(ctx, tObj);
fxSetupSingleTMU_NoLock(fxMesa, tObj);
if (ti->whichTMU == FX_TMU_BOTH)
tmu = FX_TMU0;
else
tmu = ti->whichTMU;
if (fxMesa->tmuSrc != tmu)
fxSelectSingleTMUSrc_NoLock(fxMesa, tmu, ti->LODblend);
if (textureset == 0 || !fxMesa->haveTwoTMUs)
unitsmode = fxGetTexSetConfiguration(ctx, tObj, NULL);
else
unitsmode = fxGetTexSetConfiguration(ctx, NULL, tObj);
/* if(fxMesa->lastUnitsMode==unitsmode) */
/* return; */
fxMesa->lastUnitsMode = unitsmode;
fxMesa->stw_hint_state = 0;
FX_grHints_NoLock(GR_HINT_STWHINT, 0);
ifmt = ti->baseLevelInternalFormat;
if (unitsmode & FX_UM_ALPHA_ITERATED)
locala = GR_COMBINE_LOCAL_ITERATED;
else
locala = GR_COMBINE_LOCAL_CONSTANT;
if (unitsmode & FX_UM_COLOR_ITERATED)
localc = GR_COMBINE_LOCAL_ITERATED;
else
localc = GR_COMBINE_LOCAL_CONSTANT;
if (TDFX_DEBUG & (VERBOSE_DRIVER | VERBOSE_TEXTURE))
fprintf(stderr, "fxSetupTextureSingleTMU_NoLock: envmode is %s\n",
_mesa_lookup_enum_by_nr(ctx->Texture.Unit[textureset].EnvMode));
alphaComb.Local = locala;
alphaComb.Invert = FXFALSE;
colorComb.Local = localc;
colorComb.Invert = FXFALSE;
switch (ctx->Texture.Unit[textureset].EnvMode) {
case GL_DECAL:
alphaComb.Function = GR_COMBINE_FUNCTION_LOCAL;
alphaComb.Factor = GR_COMBINE_FACTOR_NONE;
alphaComb.Other = GR_COMBINE_OTHER_NONE;
colorComb.Function = GR_COMBINE_FUNCTION_BLEND;
colorComb.Factor = GR_COMBINE_FACTOR_TEXTURE_ALPHA;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
break;
case GL_MODULATE:
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
alphaComb.Factor = GR_COMBINE_FACTOR_LOCAL;
alphaComb.Other = GR_COMBINE_OTHER_TEXTURE;
if (ifmt == GL_ALPHA) {
colorComb.Function = GR_COMBINE_FUNCTION_LOCAL;
colorComb.Factor = GR_COMBINE_FACTOR_NONE;
colorComb.Other = GR_COMBINE_OTHER_NONE;
} else {
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
colorComb.Factor = GR_COMBINE_FACTOR_LOCAL;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
}
break;
case GL_BLEND:
if (ifmt == GL_LUMINANCE || ifmt == GL_RGB) {
/* Av = Af */
alphaComb.Function = GR_COMBINE_FUNCTION_LOCAL;
alphaComb.Factor = GR_COMBINE_FACTOR_NONE;
alphaComb.Other = GR_COMBINE_OTHER_NONE;
}
else if (ifmt == GL_INTENSITY) {
/* Av = Af * (1 - It) + Ac * It */
alphaComb.Function = GR_COMBINE_FUNCTION_BLEND;
alphaComb.Factor = GR_COMBINE_FACTOR_TEXTURE_ALPHA;
alphaComb.Other = GR_COMBINE_OTHER_CONSTANT;
}
else {
/* Av = Af * At */
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
alphaComb.Factor = GR_COMBINE_FACTOR_LOCAL;
alphaComb.Other = GR_COMBINE_OTHER_TEXTURE;
}
if (ifmt == GL_ALPHA) {
colorComb.Function = GR_COMBINE_FUNCTION_LOCAL;
colorComb.Factor = GR_COMBINE_FACTOR_NONE;
colorComb.Other = GR_COMBINE_OTHER_NONE;
} else {
if (fxMesa->type >= GR_SSTTYPE_Voodoo2) {
colorComb.Function = GR_COMBINE_FUNCTION_BLEND;
colorComb.Factor = GR_COMBINE_FACTOR_TEXTURE_RGB;
colorComb.Other = GR_COMBINE_OTHER_CONSTANT;
} else if (ifmt == GL_INTENSITY) {
/* just a hack: RGB == ALPHA */
colorComb.Function = GR_COMBINE_FUNCTION_BLEND;
colorComb.Factor = GR_COMBINE_FACTOR_TEXTURE_ALPHA;
colorComb.Other = GR_COMBINE_OTHER_CONSTANT;
} else {
/* Only Voodoo^2 can GL_BLEND (GR_COMBINE_FACTOR_TEXTURE_RGB)
* These settings assume that the TexEnv color is black and
* incoming fragment color is white.
*/
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
colorComb.Factor = GR_COMBINE_FACTOR_ONE;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
colorComb.Invert = FXTRUE;
_mesa_problem(NULL, "can't GL_BLEND with SST1");
}
}
grConstantColorValue(
(((GLuint)(ctx->Texture.Unit[textureset].EnvColor[0] * 255.0f)) ) |
(((GLuint)(ctx->Texture.Unit[textureset].EnvColor[1] * 255.0f)) << 8) |
(((GLuint)(ctx->Texture.Unit[textureset].EnvColor[2] * 255.0f)) << 16) |
(((GLuint)(ctx->Texture.Unit[textureset].EnvColor[3] * 255.0f)) << 24));
break;
case GL_REPLACE:
if ((ifmt == GL_RGB) || (ifmt == GL_LUMINANCE)) {
alphaComb.Function = GR_COMBINE_FUNCTION_LOCAL;
alphaComb.Factor = GR_COMBINE_FACTOR_NONE;
alphaComb.Other = GR_COMBINE_OTHER_NONE;
} else {
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
alphaComb.Factor = GR_COMBINE_FACTOR_ONE;
alphaComb.Other = GR_COMBINE_OTHER_TEXTURE;
}
if (ifmt == GL_ALPHA) {
colorComb.Function = GR_COMBINE_FUNCTION_LOCAL;
colorComb.Factor = GR_COMBINE_FACTOR_NONE;
colorComb.Other = GR_COMBINE_OTHER_NONE;
} else {
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
colorComb.Factor = GR_COMBINE_FACTOR_ONE;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
}
break;
case GL_ADD:
if (ifmt == GL_ALPHA ||
ifmt == GL_LUMINANCE_ALPHA ||
ifmt == GL_RGBA) {
/* product of texel and fragment alpha */
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
alphaComb.Factor = GR_COMBINE_FACTOR_LOCAL;
alphaComb.Other = GR_COMBINE_OTHER_TEXTURE;
}
else if (ifmt == GL_LUMINANCE || ifmt == GL_RGB) {
/* fragment alpha is unchanged */
alphaComb.Function = GR_COMBINE_FUNCTION_LOCAL;
alphaComb.Factor = GR_COMBINE_FACTOR_NONE;
alphaComb.Other = GR_COMBINE_OTHER_NONE;
}
else {
/* sum of texel and fragment alpha */
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER_ADD_LOCAL;
alphaComb.Factor = GR_COMBINE_FACTOR_ONE;
alphaComb.Other = GR_COMBINE_OTHER_TEXTURE;
}
if (ifmt == GL_ALPHA) {
/* rgb unchanged */
colorComb.Function = GR_COMBINE_FUNCTION_LOCAL;
colorComb.Factor = GR_COMBINE_FACTOR_NONE;
colorComb.Other = GR_COMBINE_OTHER_NONE;
}
else {
/* sum of texel and fragment rgb */
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER_ADD_LOCAL;
colorComb.Factor = GR_COMBINE_FACTOR_ONE;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
}
break;
default:
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupTextureSingleTMU_NoLock: %x Texture.EnvMode not yet supported\n",
ctx->Texture.Unit[textureset].EnvMode);
}
return;
}
grAlphaCombine(alphaComb.Function,
alphaComb.Factor,
alphaComb.Local,
alphaComb.Other,
alphaComb.Invert);
grColorCombine(colorComb.Function,
colorComb.Factor,
colorComb.Local,
colorComb.Other,
colorComb.Invert);
}
#if 00
static void
fxSetupTextureSingleTMU(GLcontext * ctx, GLuint textureset)
{
BEGIN_BOARD_LOCK();
fxSetupTextureSingleTMU_NoLock(ctx, textureset);
END_BOARD_LOCK();
}
#endif
/************************* Double Texture Set ***************************/
static void
fxSetupDoubleTMU_NoLock(fxMesaContext fxMesa,
struct gl_texture_object *tObj0,
struct gl_texture_object *tObj1)
{
#define T0_NOT_IN_TMU 0x01
#define T1_NOT_IN_TMU 0x02
#define T0_IN_TMU0 0x04
#define T1_IN_TMU0 0x08
#define T0_IN_TMU1 0x10
#define T1_IN_TMU1 0x20
tfxTexInfo *ti0 = fxTMGetTexInfo(tObj0);
tfxTexInfo *ti1 = fxTMGetTexInfo(tObj1);
GLuint tstate = 0;
int tmu0 = 0, tmu1 = 1;
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupDoubleTMU_NoLock(...)\n");
}
/* We shouldn't need to do this. There is something wrong with
mutlitexturing when the TMUs are swapped. So, we're forcing
them to always be loaded correctly. !!! */
if (ti0->whichTMU == FX_TMU1)
fxTMMoveOutTM_NoLock(fxMesa, tObj0);
if (ti1->whichTMU == FX_TMU0)
fxTMMoveOutTM_NoLock(fxMesa, tObj1);
if (ti0->isInTM) {
switch (ti0->whichTMU) {
case FX_TMU0:
tstate |= T0_IN_TMU0;
break;
case FX_TMU1:
tstate |= T0_IN_TMU1;
break;
case FX_TMU_BOTH:
tstate |= T0_IN_TMU0 | T0_IN_TMU1;
break;
case FX_TMU_SPLIT:
tstate |= T0_NOT_IN_TMU;
break;
}
}
else
tstate |= T0_NOT_IN_TMU;
if (ti1->isInTM) {
switch (ti1->whichTMU) {
case FX_TMU0:
tstate |= T1_IN_TMU0;
break;
case FX_TMU1:
tstate |= T1_IN_TMU1;
break;
case FX_TMU_BOTH:
tstate |= T1_IN_TMU0 | T1_IN_TMU1;
break;
case FX_TMU_SPLIT:
tstate |= T1_NOT_IN_TMU;
break;
}
}
else
tstate |= T1_NOT_IN_TMU;
ti0->lastTimeUsed = fxMesa->texBindNumber;
ti1->lastTimeUsed = fxMesa->texBindNumber;
/* Move texture maps into TMUs */
if (!(((tstate & T0_IN_TMU0) && (tstate & T1_IN_TMU1)) ||
((tstate & T0_IN_TMU1) && (tstate & T1_IN_TMU0)))) {
if (tObj0 == tObj1)
fxTMMoveInTM_NoLock(fxMesa, tObj1, FX_TMU_BOTH);
else {
/* Find the minimal way to correct the situation */
if ((tstate & T0_IN_TMU0) || (tstate & T1_IN_TMU1)) {
/* We have one in the standard order, setup the other */
if (tstate & T0_IN_TMU0) { /* T0 is in TMU0, put T1 in TMU1 */
fxTMMoveInTM_NoLock(fxMesa, tObj1, FX_TMU1);
}
else {
fxTMMoveInTM_NoLock(fxMesa, tObj0, FX_TMU0);
}
/* tmu0 and tmu1 are setup */
}
else if ((tstate & T0_IN_TMU1) || (tstate & T1_IN_TMU0)) {
/* we have one in the reverse order, setup the other */
if (tstate & T1_IN_TMU0) { /* T1 is in TMU0, put T0 in TMU1 */
fxTMMoveInTM_NoLock(fxMesa, tObj0, FX_TMU1);
}
else {
fxTMMoveInTM_NoLock(fxMesa, tObj1, FX_TMU0);
}
tmu0 = 1;
tmu1 = 0;
}
else { /* Nothing is loaded */
fxTMMoveInTM_NoLock(fxMesa, tObj0, FX_TMU0);
fxTMMoveInTM_NoLock(fxMesa, tObj1, FX_TMU1);
/* tmu0 and tmu1 are setup */
}
}
}
/* [dBorca] Hack alert:
* we put these in reverse order, so that if we can't
* do _REAL_ pointcast, the TMU0 table gets broadcasted
*/
if (!fxMesa->haveGlobalPaletteTexture) {
/* pointcast */
if (ti1->info.format == GR_TEXFMT_P_8) {
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupDoubleTMU_NoLock: uploading texture palette for TMU1\n");
}
fxMesa->Glide.grTexDownloadTableExt(ti1->whichTMU, ti1->paltype, &(ti1->palette));
}
if (ti0->info.format == GR_TEXFMT_P_8) {
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupDoubleTMU_NoLock: uploading texture palette for TMU0\n");
}
fxMesa->Glide.grTexDownloadTableExt(ti0->whichTMU, ti0->paltype, &(ti0->palette));
}
}
grTexSource(tmu0, ti0->tm[tmu0]->startAddr,
GR_MIPMAPLEVELMASK_BOTH, &(ti0->info));
grTexClampMode(tmu0, ti0->sClamp, ti0->tClamp);
grTexFilterMode(tmu0, ti0->minFilt, ti0->maxFilt);
grTexMipMapMode(tmu0, ti0->mmMode, FXFALSE);
grTexSource(tmu1, ti1->tm[tmu1]->startAddr,
GR_MIPMAPLEVELMASK_BOTH, &(ti1->info));
grTexClampMode(tmu1, ti1->sClamp, ti1->tClamp);
grTexFilterMode(tmu1, ti1->minFilt, ti1->maxFilt);
grTexMipMapMode(tmu1, ti1->mmMode, FXFALSE);
#undef T0_NOT_IN_TMU
#undef T1_NOT_IN_TMU
#undef T0_IN_TMU0
#undef T1_IN_TMU0
#undef T0_IN_TMU1
#undef T1_IN_TMU1
}
static void
fxSetupTextureDoubleTMU_NoLock(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
struct tdfx_combine alphaComb, colorComb;
struct tdfx_texcombine tex0, tex1;
GrCombineLocal_t localc, locala;
tfxTexInfo *ti0, *ti1;
struct gl_texture_object *tObj0 = ctx->Texture.Unit[1]._Current;
struct gl_texture_object *tObj1 = ctx->Texture.Unit[0]._Current;
GLuint envmode, ifmt, unitsmode;
int tmu0 = 0, tmu1 = 1;
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupTextureDoubleTMU_NoLock(...)\n");
}
ti0 = fxTMGetTexInfo(tObj0);
fxTexValidate(ctx, tObj0);
ti1 = fxTMGetTexInfo(tObj1);
fxTexValidate(ctx, tObj1);
fxSetupDoubleTMU_NoLock(fxMesa, tObj0, tObj1);
unitsmode = fxGetTexSetConfiguration(ctx, tObj0, tObj1);
/* if(fxMesa->lastUnitsMode==unitsmode) */
/* return; */
fxMesa->lastUnitsMode = unitsmode;
fxMesa->stw_hint_state |= GR_STWHINT_ST_DIFF_TMU1;
FX_grHints_NoLock(GR_HINT_STWHINT, fxMesa->stw_hint_state);
envmode = unitsmode & FX_UM_E_ENVMODE;
ifmt = unitsmode & FX_UM_E_IFMT;
if (unitsmode & FX_UM_ALPHA_ITERATED)
locala = GR_COMBINE_LOCAL_ITERATED;
else
locala = GR_COMBINE_LOCAL_CONSTANT;
if (unitsmode & FX_UM_COLOR_ITERATED)
localc = GR_COMBINE_LOCAL_ITERATED;
else
localc = GR_COMBINE_LOCAL_CONSTANT;
if (TDFX_DEBUG & (VERBOSE_DRIVER | VERBOSE_TEXTURE))
fprintf(stderr, "fxSetupTextureDoubleTMU_NoLock: envmode is %s/%s\n",
_mesa_lookup_enum_by_nr(ctx->Texture.Unit[0].EnvMode),
_mesa_lookup_enum_by_nr(ctx->Texture.Unit[1].EnvMode));
if ((ti0->whichTMU == FX_TMU1) || (ti1->whichTMU == FX_TMU0)) {
tmu0 = 1;
tmu1 = 0;
}
fxMesa->tmuSrc = FX_TMU_BOTH;
tex0.InvertRGB = FXFALSE;
tex0.InvertAlpha = FXFALSE;
tex1.InvertRGB = FXFALSE;
tex1.InvertAlpha = FXFALSE;
alphaComb.Local = locala;
alphaComb.Invert = FXFALSE;
colorComb.Local = localc;
colorComb.Invert = FXFALSE;
switch (envmode) {
case (FX_UM_E0_MODULATE | FX_UM_E1_MODULATE):
{
GLboolean isalpha[FX_NUM_TMU];
isalpha[tmu0] = (ti0->baseLevelInternalFormat == GL_ALPHA);
isalpha[tmu1] = (ti1->baseLevelInternalFormat == GL_ALPHA);
if (isalpha[FX_TMU1]) {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_ZERO;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
tex1.InvertRGB = FXTRUE;
} else {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
}
if (isalpha[FX_TMU0]) {
tex0.FunctionRGB = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorRGB = GR_COMBINE_FACTOR_ONE;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorAlpha = GR_COMBINE_FACTOR_LOCAL;
} else {
tex0.FunctionRGB = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorRGB = GR_COMBINE_FACTOR_LOCAL;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorAlpha = GR_COMBINE_FACTOR_LOCAL;
}
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
colorComb.Factor = GR_COMBINE_FACTOR_LOCAL;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
alphaComb.Factor = GR_COMBINE_FACTOR_LOCAL;
alphaComb.Other = GR_COMBINE_OTHER_TEXTURE;
break;
}
case (FX_UM_E0_REPLACE | FX_UM_E1_BLEND): /* Only for GLQuake */
if (tmu0 == FX_TMU1) {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
tex1.InvertRGB = FXTRUE;
tex0.FunctionRGB = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorRGB = GR_COMBINE_FACTOR_LOCAL;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorAlpha = GR_COMBINE_FACTOR_LOCAL;
}
else {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
tex0.FunctionRGB = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorRGB = GR_COMBINE_FACTOR_ONE_MINUS_LOCAL;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorAlpha = GR_COMBINE_FACTOR_ONE_MINUS_LOCAL;
}
alphaComb.Function = GR_COMBINE_FUNCTION_LOCAL;
alphaComb.Factor = GR_COMBINE_FACTOR_NONE;
alphaComb.Other = GR_COMBINE_OTHER_NONE;
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
colorComb.Factor = GR_COMBINE_FACTOR_ONE;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
break;
case (FX_UM_E0_REPLACE | FX_UM_E1_MODULATE): /* Quake 2 and 3 */
if (tmu1 == FX_TMU1) {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_ZERO;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
tex1.InvertAlpha = FXTRUE;
tex0.FunctionRGB = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorRGB = GR_COMBINE_FACTOR_LOCAL;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorAlpha = GR_COMBINE_FACTOR_LOCAL;
}
else {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
tex0.FunctionRGB = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorRGB = GR_COMBINE_FACTOR_LOCAL;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_BLEND_OTHER;
tex0.FactorAlpha = GR_COMBINE_FACTOR_ONE;
}
if (ti0->baseLevelInternalFormat == GL_RGB) {
alphaComb.Function = GR_COMBINE_FUNCTION_LOCAL;
alphaComb.Factor = GR_COMBINE_FACTOR_NONE;
alphaComb.Other = GR_COMBINE_OTHER_NONE;
} else {
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
alphaComb.Factor = GR_COMBINE_FACTOR_ONE;
alphaComb.Other = GR_COMBINE_OTHER_NONE;
}
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
colorComb.Factor = GR_COMBINE_FACTOR_ONE;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
break;
case (FX_UM_E0_MODULATE | FX_UM_E1_ADD): /* Quake 3 Sky */
{
GLboolean isalpha[FX_NUM_TMU];
isalpha[tmu0] = (ti0->baseLevelInternalFormat == GL_ALPHA);
isalpha[tmu1] = (ti1->baseLevelInternalFormat == GL_ALPHA);
if (isalpha[FX_TMU1]) {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_ZERO;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
tex1.InvertRGB = FXTRUE;
} else {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
}
if (isalpha[FX_TMU0]) {
tex0.FunctionRGB = GR_COMBINE_FUNCTION_SCALE_OTHER;
tex0.FactorRGB = GR_COMBINE_FACTOR_ONE;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_SCALE_OTHER_ADD_LOCAL;
tex0.FactorAlpha = GR_COMBINE_FACTOR_ONE;
} else {
tex0.FunctionRGB = GR_COMBINE_FUNCTION_SCALE_OTHER_ADD_LOCAL;
tex0.FactorRGB = GR_COMBINE_FACTOR_ONE;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_SCALE_OTHER_ADD_LOCAL;
tex0.FactorAlpha = GR_COMBINE_FACTOR_ONE;
}
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
colorComb.Factor = GR_COMBINE_FACTOR_LOCAL;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
alphaComb.Factor = GR_COMBINE_FACTOR_LOCAL;
alphaComb.Other = GR_COMBINE_OTHER_TEXTURE;
break;
}
case (FX_UM_E0_REPLACE | FX_UM_E1_ADD): /* Vulpine Sky */
{
GLboolean isalpha[FX_NUM_TMU];
isalpha[tmu0] = (ti0->baseLevelInternalFormat == GL_ALPHA);
isalpha[tmu1] = (ti1->baseLevelInternalFormat == GL_ALPHA);
if (isalpha[FX_TMU1]) {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_ZERO;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
tex1.InvertRGB = FXTRUE;
} else {
tex1.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
}
if (isalpha[FX_TMU0]) {
tex0.FunctionRGB = GR_COMBINE_FUNCTION_SCALE_OTHER;
tex0.FactorRGB = GR_COMBINE_FACTOR_ONE;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_SCALE_OTHER_ADD_LOCAL;
tex0.FactorAlpha = GR_COMBINE_FACTOR_ONE;
} else {
tex0.FunctionRGB = GR_COMBINE_FUNCTION_SCALE_OTHER_ADD_LOCAL;
tex0.FactorRGB = GR_COMBINE_FACTOR_ONE;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_SCALE_OTHER_ADD_LOCAL;
tex0.FactorAlpha = GR_COMBINE_FACTOR_ONE;
}
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
colorComb.Factor = GR_COMBINE_FACTOR_ONE;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
alphaComb.Factor = GR_COMBINE_FACTOR_ONE;
alphaComb.Other = GR_COMBINE_OTHER_TEXTURE;
break;
}
case (FX_UM_E0_MODULATE | FX_UM_E1_REPLACE): /* Homeworld2 */
{
tex1.FunctionRGB = GR_COMBINE_FUNCTION_ZERO;
tex1.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex1.FunctionAlpha = GR_COMBINE_FUNCTION_ZERO;
tex1.FactorAlpha = GR_COMBINE_FACTOR_NONE;
tex0.FunctionRGB = GR_COMBINE_FUNCTION_LOCAL;
tex0.FactorRGB = GR_COMBINE_FACTOR_NONE;
tex0.FunctionAlpha = GR_COMBINE_FUNCTION_LOCAL;
tex0.FactorAlpha = GR_COMBINE_FACTOR_NONE;
if (ifmt & (FX_UM_E0_RGB | FX_UM_E0_LUMINANCE)) {
alphaComb.Function = GR_COMBINE_FUNCTION_LOCAL;
alphaComb.Factor = GR_COMBINE_FACTOR_NONE;
alphaComb.Other = GR_COMBINE_OTHER_NONE;
} else {
alphaComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
alphaComb.Factor = GR_COMBINE_FACTOR_ONE;
alphaComb.Other = GR_COMBINE_OTHER_TEXTURE;
}
if (ifmt & FX_UM_E0_ALPHA) {
colorComb.Function = GR_COMBINE_FUNCTION_LOCAL;
colorComb.Factor = GR_COMBINE_FACTOR_NONE;
colorComb.Other = GR_COMBINE_OTHER_NONE;
} else {
colorComb.Function = GR_COMBINE_FUNCTION_SCALE_OTHER;
colorComb.Factor = GR_COMBINE_FACTOR_ONE;
colorComb.Other = GR_COMBINE_OTHER_TEXTURE;
}
break;
}
default:
fprintf(stderr, "fxSetupTextureDoubleTMU_NoLock: Unexpected dual texture mode encountered\n");
return;
}
grAlphaCombine(alphaComb.Function,
alphaComb.Factor,
alphaComb.Local,
alphaComb.Other,
alphaComb.Invert);
grColorCombine(colorComb.Function,
colorComb.Factor,
colorComb.Local,
colorComb.Other,
colorComb.Invert);
grTexCombine(GR_TMU0,
tex0.FunctionRGB,
tex0.FactorRGB,
tex0.FunctionAlpha,
tex0.FactorAlpha,
tex0.InvertRGB,
tex0.InvertAlpha);
grTexCombine(GR_TMU1,
tex1.FunctionRGB,
tex1.FactorRGB,
tex1.FunctionAlpha,
tex1.FactorAlpha,
tex1.InvertRGB,
tex1.InvertAlpha);
}
/************************* No Texture ***************************/
static void
fxSetupTextureNone_NoLock(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
GrCombineLocal_t localc, locala;
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupTextureNone_NoLock(...)\n");
}
if ((ctx->Light.ShadeModel == GL_SMOOTH) || 1 ||
(ctx->Point.SmoothFlag) ||
(ctx->Line.SmoothFlag) ||
(ctx->Polygon.SmoothFlag)) locala = GR_COMBINE_LOCAL_ITERATED;
else
locala = GR_COMBINE_LOCAL_CONSTANT;
if (ctx->Light.ShadeModel == GL_SMOOTH || 1)
localc = GR_COMBINE_LOCAL_ITERATED;
else
localc = GR_COMBINE_LOCAL_CONSTANT;
grAlphaCombine(GR_COMBINE_FUNCTION_LOCAL,
GR_COMBINE_FACTOR_NONE,
locala,
GR_COMBINE_OTHER_NONE,
FXFALSE);
grColorCombine(GR_COMBINE_FUNCTION_LOCAL,
GR_COMBINE_FACTOR_NONE,
localc,
GR_COMBINE_OTHER_NONE,
FXFALSE);
fxMesa->lastUnitsMode = FX_UM_NONE;
}
#include "fxsetup.h"
/************************************************************************/
/************************** Texture Mode SetUp **************************/
/************************************************************************/
static void
fxSetupTexture_NoLock(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "fxSetupTexture_NoLock(...)\n");
}
if (fxMesa->HaveCmbExt) {
/* Texture Combine, Color Combine and Alpha Combine. */
if ((ctx->Texture.Unit[0]._ReallyEnabled & (TEXTURE_1D_BIT|TEXTURE_2D_BIT)) &&
(ctx->Texture.Unit[1]._ReallyEnabled & (TEXTURE_1D_BIT|TEXTURE_2D_BIT)) &&
fxMesa->haveTwoTMUs) {
fxSetupTextureDoubleTMUNapalm_NoLock(ctx);
}
else if (ctx->Texture.Unit[0]._ReallyEnabled & (TEXTURE_1D_BIT|TEXTURE_2D_BIT)) {
fxSetupTextureSingleTMUNapalm_NoLock(ctx, 0);
}
else if (ctx->Texture.Unit[1]._ReallyEnabled & (TEXTURE_1D_BIT|TEXTURE_2D_BIT)) {
fxSetupTextureSingleTMUNapalm_NoLock(ctx, 1);
}
else {
fxSetupTextureNoneNapalm_NoLock(ctx);
}
} else {
/* Texture Combine, Color Combine and Alpha Combine. */
if ((ctx->Texture.Unit[0]._ReallyEnabled & (TEXTURE_1D_BIT|TEXTURE_2D_BIT)) &&
(ctx->Texture.Unit[1]._ReallyEnabled & (TEXTURE_1D_BIT|TEXTURE_2D_BIT)) &&
fxMesa->haveTwoTMUs) {
fxSetupTextureDoubleTMU_NoLock(ctx);
}
else if (ctx->Texture.Unit[0]._ReallyEnabled & (TEXTURE_1D_BIT|TEXTURE_2D_BIT)) {
fxSetupTextureSingleTMU_NoLock(ctx, 0);
}
else if (ctx->Texture.Unit[1]._ReallyEnabled & (TEXTURE_1D_BIT|TEXTURE_2D_BIT)) {
fxSetupTextureSingleTMU_NoLock(ctx, 1);
}
else {
fxSetupTextureNone_NoLock(ctx);
}
}
}
void
fxSetupTexture(GLcontext * ctx)
{
BEGIN_BOARD_LOCK();
fxSetupTexture_NoLock(ctx);
END_BOARD_LOCK();
}
/************************************************************************/
/**************************** Blend SetUp *******************************/
/************************************************************************/
void
fxDDBlendFuncSeparate(GLcontext * ctx, GLenum sfactor, GLenum dfactor, GLenum asfactor, GLenum adfactor)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
GLboolean isNapalm = (fxMesa->type >= GR_SSTTYPE_Voodoo4);
GLboolean have32bpp = (fxMesa->colDepth == 32);
GLboolean haveAlpha = fxMesa->haveHwAlpha;
GrAlphaBlendFnc_t sfact, dfact, asfact, adfact;
/*
* 15/16 BPP alpha channel alpha blending modes
* 0x0 AZERO Zero
* 0x4 AONE One
*
* 32 BPP alpha channel alpha blending modes
* 0x0 AZERO Zero
* 0x1 ASRC_ALPHA Source alpha
* 0x3 ADST_ALPHA Destination alpha
* 0x4 AONE One
* 0x5 AOMSRC_ALPHA 1 - Source alpha
* 0x7 AOMDST_ALPHA 1 - Destination alpha
*
* If we don't have HW alpha buffer:
* DST_ALPHA == 1
* ONE_MINUS_DST_ALPHA == 0
* Unsupported modes are:
* 1 if used as src blending factor
* 0 if used as dst blending factor
*/
switch (sfactor) {
case GL_ZERO:
sfact = GR_BLEND_ZERO;
break;
case GL_ONE:
sfact = GR_BLEND_ONE;
break;
case GL_DST_COLOR:
sfact = GR_BLEND_DST_COLOR;
break;
case GL_ONE_MINUS_DST_COLOR:
sfact = GR_BLEND_ONE_MINUS_DST_COLOR;
break;
case GL_SRC_ALPHA:
sfact = GR_BLEND_SRC_ALPHA;
break;
case GL_ONE_MINUS_SRC_ALPHA:
sfact = GR_BLEND_ONE_MINUS_SRC_ALPHA;
break;
case GL_DST_ALPHA:
sfact = haveAlpha ? GR_BLEND_DST_ALPHA : GR_BLEND_ONE/*bad*/;
break;
case GL_ONE_MINUS_DST_ALPHA:
sfact = haveAlpha ? GR_BLEND_ONE_MINUS_DST_ALPHA : GR_BLEND_ZERO/*bad*/;
break;
case GL_SRC_ALPHA_SATURATE:
sfact = GR_BLEND_ALPHA_SATURATE;
break;
case GL_SRC_COLOR:
if (isNapalm) {
sfact = GR_BLEND_SAME_COLOR_EXT;
break;
}
case GL_ONE_MINUS_SRC_COLOR:
if (isNapalm) {
sfact = GR_BLEND_ONE_MINUS_SAME_COLOR_EXT;
break;
}
default:
sfact = GR_BLEND_ONE;
break;
}
switch (asfactor) {
case GL_ZERO:
asfact = GR_BLEND_ZERO;
break;
case GL_ONE:
asfact = GR_BLEND_ONE;
break;
case GL_SRC_COLOR:
case GL_SRC_ALPHA:
asfact = have32bpp ? GR_BLEND_SRC_ALPHA : GR_BLEND_ONE/*bad*/;
break;
case GL_ONE_MINUS_SRC_COLOR:
case GL_ONE_MINUS_SRC_ALPHA:
asfact = have32bpp ? GR_BLEND_ONE_MINUS_SRC_ALPHA : GR_BLEND_ONE/*bad*/;
break;
case GL_DST_COLOR:
case GL_DST_ALPHA:
asfact = (have32bpp && haveAlpha) ? GR_BLEND_DST_ALPHA : GR_BLEND_ONE/*bad*/;
break;
case GL_ONE_MINUS_DST_COLOR:
case GL_ONE_MINUS_DST_ALPHA:
asfact = (have32bpp && haveAlpha) ? GR_BLEND_ONE_MINUS_DST_ALPHA : GR_BLEND_ZERO/*bad*/;
break;
case GL_SRC_ALPHA_SATURATE:
asfact = GR_BLEND_ONE;
break;
default:
asfact = GR_BLEND_ONE;
break;
}
switch (dfactor) {
case GL_ZERO:
dfact = GR_BLEND_ZERO;
break;
case GL_ONE:
dfact = GR_BLEND_ONE;
break;
case GL_SRC_COLOR:
dfact = GR_BLEND_SRC_COLOR;
break;
case GL_ONE_MINUS_SRC_COLOR:
dfact = GR_BLEND_ONE_MINUS_SRC_COLOR;
break;
case GL_SRC_ALPHA:
dfact = GR_BLEND_SRC_ALPHA;
break;
case GL_ONE_MINUS_SRC_ALPHA:
dfact = GR_BLEND_ONE_MINUS_SRC_ALPHA;
break;
case GL_DST_ALPHA:
dfact = haveAlpha ? GR_BLEND_DST_ALPHA : GR_BLEND_ONE/*bad*/;
break;
case GL_ONE_MINUS_DST_ALPHA:
dfact = haveAlpha ? GR_BLEND_ONE_MINUS_DST_ALPHA : GR_BLEND_ZERO/*bad*/;
break;
case GL_DST_COLOR:
if (isNapalm) {
dfact = GR_BLEND_SAME_COLOR_EXT;
break;
}
case GL_ONE_MINUS_DST_COLOR:
if (isNapalm) {
dfact = GR_BLEND_ONE_MINUS_SAME_COLOR_EXT;
break;
}
default:
dfact = GR_BLEND_ZERO;
break;
}
switch (adfactor) {
case GL_ZERO:
adfact = GR_BLEND_ZERO;
break;
case GL_ONE:
adfact = GR_BLEND_ONE;
break;
case GL_SRC_COLOR:
case GL_SRC_ALPHA:
adfact = have32bpp ? GR_BLEND_SRC_ALPHA : GR_BLEND_ZERO/*bad*/;
break;
case GL_ONE_MINUS_SRC_COLOR:
case GL_ONE_MINUS_SRC_ALPHA:
adfact = have32bpp ? GR_BLEND_ONE_MINUS_SRC_ALPHA : GR_BLEND_ZERO/*bad*/;
break;
case GL_DST_COLOR:
case GL_DST_ALPHA:
adfact = (have32bpp && haveAlpha) ? GR_BLEND_DST_ALPHA : GR_BLEND_ONE/*bad*/;
break;
case GL_ONE_MINUS_DST_COLOR:
case GL_ONE_MINUS_DST_ALPHA:
adfact = (have32bpp && haveAlpha) ? GR_BLEND_ONE_MINUS_DST_ALPHA : GR_BLEND_ZERO/*bad*/;
break;
default:
adfact = GR_BLEND_ZERO;
break;
}
if ((sfact != us->blendSrcFuncRGB) || (asfact != us->blendSrcFuncAlpha)) {
us->blendSrcFuncRGB = sfact;
us->blendSrcFuncAlpha = asfact;
fxMesa->new_state |= FX_NEW_BLEND;
}
if ((dfact != us->blendDstFuncRGB) || (adfact != us->blendDstFuncAlpha)) {
us->blendDstFuncRGB = dfact;
us->blendDstFuncAlpha = adfact;
fxMesa->new_state |= FX_NEW_BLEND;
}
}
void
fxDDBlendEquationSeparate(GLcontext * ctx, GLenum modeRGB, GLenum modeA)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
GrAlphaBlendOp_t q;
switch (modeRGB) {
case GL_FUNC_ADD:
q = GR_BLEND_OP_ADD;
break;
case GL_FUNC_SUBTRACT:
q = GR_BLEND_OP_SUB;
break;
case GL_FUNC_REVERSE_SUBTRACT:
q = GR_BLEND_OP_REVSUB;
break;
default:
q = us->blendEqRGB;
}
if (q != us->blendEqRGB) {
us->blendEqRGB = q;
fxMesa->new_state |= FX_NEW_BLEND;
}
switch (modeA) {
case GL_FUNC_ADD:
q = GR_BLEND_OP_ADD;
break;
case GL_FUNC_SUBTRACT:
q = GR_BLEND_OP_SUB;
break;
case GL_FUNC_REVERSE_SUBTRACT:
q = GR_BLEND_OP_REVSUB;
break;
default:
q = us->blendEqAlpha;
}
if (q != us->blendEqAlpha) {
us->blendEqAlpha = q;
fxMesa->new_state |= FX_NEW_BLEND;
}
}
void
fxSetupBlend(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (fxMesa->HavePixExt) {
if (us->blendEnabled) {
fxMesa->Glide.grAlphaBlendFunctionExt(us->blendSrcFuncRGB, us->blendDstFuncRGB,
us->blendEqRGB,
us->blendSrcFuncAlpha, us->blendDstFuncAlpha,
us->blendEqAlpha);
} else {
fxMesa->Glide.grAlphaBlendFunctionExt(GR_BLEND_ONE, GR_BLEND_ZERO,
GR_BLEND_OP_ADD,
GR_BLEND_ONE, GR_BLEND_ZERO,
GR_BLEND_OP_ADD);
}
} else {
if (us->blendEnabled) {
grAlphaBlendFunction(us->blendSrcFuncRGB, us->blendDstFuncRGB,
us->blendSrcFuncAlpha, us->blendDstFuncAlpha);
} else {
grAlphaBlendFunction(GR_BLEND_ONE, GR_BLEND_ZERO,
GR_BLEND_ONE, GR_BLEND_ZERO);
}
}
}
/************************************************************************/
/************************** Alpha Test SetUp ****************************/
/************************************************************************/
void
fxDDAlphaFunc(GLcontext * ctx, GLenum func, GLfloat ref)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (
(us->alphaTestFunc != func)
||
(us->alphaTestRefValue != ref)
) {
us->alphaTestFunc = func;
us->alphaTestRefValue = ref;
fxMesa->new_state |= FX_NEW_ALPHA;
}
}
static void
fxSetupAlphaTest(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (us->alphaTestEnabled) {
GrAlpha_t ref = (GLint) (us->alphaTestRefValue * 255.0);
grAlphaTestFunction(us->alphaTestFunc - GL_NEVER + GR_CMP_NEVER);
grAlphaTestReferenceValue(ref);
}
else
grAlphaTestFunction(GR_CMP_ALWAYS);
}
/************************************************************************/
/************************** Depth Test SetUp ****************************/
/************************************************************************/
void
fxDDDepthFunc(GLcontext * ctx, GLenum func)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (us->depthTestFunc != func) {
us->depthTestFunc = func;
fxMesa->new_state |= FX_NEW_DEPTH;
}
}
void
fxDDDepthMask(GLcontext * ctx, GLboolean flag)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (flag != us->depthMask) {
us->depthMask = flag;
fxMesa->new_state |= FX_NEW_DEPTH;
}
}
void
fxSetupDepthTest(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (us->depthTestEnabled) {
grDepthBufferFunction(us->depthTestFunc - GL_NEVER + GR_CMP_NEVER);
grDepthMask(us->depthMask);
}
else {
grDepthBufferFunction(GR_CMP_ALWAYS);
grDepthMask(FXFALSE);
}
}
/************************************************************************/
/************************** Stencil SetUp *******************************/
/************************************************************************/
static GrStencil_t convertGLStencilOp( GLenum op )
{
switch ( op ) {
case GL_KEEP:
return GR_STENCILOP_KEEP;
case GL_ZERO:
return GR_STENCILOP_ZERO;
case GL_REPLACE:
return GR_STENCILOP_REPLACE;
case GL_INCR:
return GR_STENCILOP_INCR_CLAMP;
case GL_DECR:
return GR_STENCILOP_DECR_CLAMP;
case GL_INVERT:
return GR_STENCILOP_INVERT;
case GL_INCR_WRAP_EXT:
return GR_STENCILOP_INCR_WRAP;
case GL_DECR_WRAP_EXT:
return GR_STENCILOP_DECR_WRAP;
default:
_mesa_problem( NULL, "bad stencil op in convertGLStencilOp" );
}
return GR_STENCILOP_KEEP; /* never get, silence compiler warning */
}
void
fxDDStencilFunc (GLcontext *ctx, GLenum func, GLint ref, GLuint mask)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (ctx->Stencil.ActiveFace) {
return;
}
if (
(us->stencilFunction != func)
||
(us->stencilRefValue != ref)
||
(us->stencilValueMask != mask)
) {
us->stencilFunction = func;
us->stencilRefValue = ref;
us->stencilValueMask = mask;
fxMesa->new_state |= FX_NEW_STENCIL;
}
}
void
fxDDStencilMask (GLcontext *ctx, GLuint mask)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (ctx->Stencil.ActiveFace) {
return;
}
if (us->stencilWriteMask != mask) {
us->stencilWriteMask = mask;
fxMesa->new_state |= FX_NEW_STENCIL;
}
}
void
fxDDStencilOp (GLcontext *ctx, GLenum sfail, GLenum zfail, GLenum zpass)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (ctx->Stencil.ActiveFace) {
return;
}
if (
(us->stencilFailFunc != sfail)
||
(us->stencilZFailFunc != zfail)
||
(us->stencilZPassFunc != zpass)
) {
us->stencilFailFunc = sfail;
us->stencilZFailFunc = zfail;
us->stencilZPassFunc = zpass;
fxMesa->new_state |= FX_NEW_STENCIL;
}
}
void
fxSetupStencil (GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (us->stencilEnabled) {
GrCmpFnc_t stencilFailFunc = GR_STENCILOP_KEEP;
GrCmpFnc_t stencilZFailFunc = GR_STENCILOP_KEEP;
GrCmpFnc_t stencilZPassFunc = GR_STENCILOP_KEEP;
if (!fxMesa->multipass) {
stencilFailFunc = convertGLStencilOp(us->stencilFailFunc);
stencilZFailFunc = convertGLStencilOp(us->stencilZFailFunc);
stencilZPassFunc = convertGLStencilOp(us->stencilZPassFunc);
}
grEnable(GR_STENCIL_MODE_EXT);
fxMesa->Glide.grStencilOpExt(stencilFailFunc,
stencilZFailFunc,
stencilZPassFunc);
fxMesa->Glide.grStencilFuncExt(us->stencilFunction - GL_NEVER + GR_CMP_NEVER,
us->stencilRefValue,
us->stencilValueMask);
fxMesa->Glide.grStencilMaskExt(us->stencilWriteMask);
} else {
grDisable(GR_STENCIL_MODE_EXT);
}
}
void
fxSetupStencilFace (GLcontext * ctx, GLint face)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (us->stencilEnabled) {
GrCmpFnc_t stencilFailFunc = GR_STENCILOP_KEEP;
GrCmpFnc_t stencilZFailFunc = GR_STENCILOP_KEEP;
GrCmpFnc_t stencilZPassFunc = GR_STENCILOP_KEEP;
if (!fxMesa->multipass) {
stencilFailFunc = convertGLStencilOp(ctx->Stencil.FailFunc[face]);
stencilZFailFunc = convertGLStencilOp(ctx->Stencil.ZFailFunc[face]);
stencilZPassFunc = convertGLStencilOp(ctx->Stencil.ZPassFunc[face]);
}
grEnable(GR_STENCIL_MODE_EXT);
fxMesa->Glide.grStencilOpExt(stencilFailFunc,
stencilZFailFunc,
stencilZPassFunc);
fxMesa->Glide.grStencilFuncExt(ctx->Stencil.Function[face] - GL_NEVER + GR_CMP_NEVER,
ctx->Stencil.Ref[face],
ctx->Stencil.ValueMask[face]);
fxMesa->Glide.grStencilMaskExt(ctx->Stencil.WriteMask[face]);
} else {
grDisable(GR_STENCIL_MODE_EXT);
}
}
/************************************************************************/
/**************************** Color Mask SetUp **************************/
/************************************************************************/
void
fxDDColorMask(GLcontext * ctx,
GLboolean r, GLboolean g, GLboolean b, GLboolean a)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
fxMesa->new_state |= FX_NEW_COLOR_MASK;
(void) r;
(void) g;
(void) b;
(void) a;
}
void
fxSetupColorMask(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
if (fxMesa->colDepth == 32) {
/* 32bpp mode */
fxMesa->Glide.grColorMaskExt(ctx->Color.ColorMask[RCOMP],
ctx->Color.ColorMask[GCOMP],
ctx->Color.ColorMask[BCOMP],
ctx->Color.ColorMask[ACOMP] && fxMesa->haveHwAlpha);
}
else {
/* 15/16 bpp mode */
grColorMask(ctx->Color.ColorMask[RCOMP] |
ctx->Color.ColorMask[GCOMP] |
ctx->Color.ColorMask[BCOMP],
ctx->Color.ColorMask[ACOMP] && fxMesa->haveHwAlpha);
}
}
/************************************************************************/
/**************************** Fog Mode SetUp ****************************/
/************************************************************************/
/*
* This is called during state update in order to update the Glide fog state.
*/
static void
fxSetupFog(GLcontext * ctx)
{
if (ctx->Fog.Enabled /*&& ctx->FogMode==FOG_FRAGMENT */ ) {
fxMesaContext fxMesa = FX_CONTEXT(ctx);
/* update fog color */
GLubyte col[4];
col[0] = (unsigned int) (255 * ctx->Fog.Color[0]);
col[1] = (unsigned int) (255 * ctx->Fog.Color[1]);
col[2] = (unsigned int) (255 * ctx->Fog.Color[2]);
col[3] = (unsigned int) (255 * ctx->Fog.Color[3]);
grFogColorValue(FXCOLOR4(col));
if (fxMesa->fogTableMode != ctx->Fog.Mode ||
fxMesa->fogDensity != ctx->Fog.Density ||
fxMesa->fogStart != ctx->Fog.Start ||
fxMesa->fogEnd != ctx->Fog.End) {
/* reload the fog table */
switch (ctx->Fog.Mode) {
case GL_LINEAR:
guFogGenerateLinear(fxMesa->fogTable, ctx->Fog.Start,
ctx->Fog.End);
if (fxMesa->fogTable[0] > 63) {
/* [dBorca] Hack alert:
* As per Glide3 Programming Guide:
* The difference between consecutive fog values
* must be less than 64.
*/
fxMesa->fogTable[0] = 63;
}
break;
case GL_EXP:
guFogGenerateExp(fxMesa->fogTable, ctx->Fog.Density);
break;
case GL_EXP2:
guFogGenerateExp2(fxMesa->fogTable, ctx->Fog.Density);
break;
default:
;
}
fxMesa->fogTableMode = ctx->Fog.Mode;
fxMesa->fogDensity = ctx->Fog.Density;
fxMesa->fogStart = ctx->Fog.Start;
fxMesa->fogEnd = ctx->Fog.End;
}
grFogTable(fxMesa->fogTable);
if (ctx->Fog.FogCoordinateSource == GL_FOG_COORDINATE_EXT) {
grVertexLayout(GR_PARAM_FOG_EXT, GR_VERTEX_FOG_OFFSET << 2,
GR_PARAM_ENABLE);
grFogMode(GR_FOG_WITH_TABLE_ON_FOGCOORD_EXT);
} else {
grVertexLayout(GR_PARAM_FOG_EXT, GR_VERTEX_FOG_OFFSET << 2,
GR_PARAM_DISABLE);
grFogMode(GR_FOG_WITH_TABLE_ON_Q);
}
}
else {
grFogMode(GR_FOG_DISABLE);
}
}
void
fxDDFogfv(GLcontext * ctx, GLenum pname, const GLfloat * params)
{
FX_CONTEXT(ctx)->new_state |= FX_NEW_FOG;
switch (pname) {
case GL_FOG_COORDINATE_SOURCE_EXT: {
GLenum p = (GLenum)*params;
if (p == GL_FOG_COORDINATE_EXT) {
_swrast_allow_vertex_fog(ctx, GL_TRUE);
_swrast_allow_pixel_fog(ctx, GL_FALSE);
_tnl_allow_vertex_fog( ctx, GL_TRUE);
_tnl_allow_pixel_fog( ctx, GL_FALSE);
} else {
_swrast_allow_vertex_fog(ctx, GL_FALSE);
_swrast_allow_pixel_fog(ctx, GL_TRUE);
_tnl_allow_vertex_fog( ctx, GL_FALSE);
_tnl_allow_pixel_fog( ctx, GL_TRUE);
}
break;
}
default:
;
}
}
/************************************************************************/
/************************** Scissor Test SetUp **************************/
/************************************************************************/
/* This routine is used in managing the lock state, and therefore can't lock */
void
fxSetScissorValues(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
int xmin, xmax;
int ymin, ymax;
if (ctx->Scissor.Enabled) {
xmin = ctx->Scissor.X;
xmax = ctx->Scissor.X + ctx->Scissor.Width;
ymin = ctx->Scissor.Y;
ymax = ctx->Scissor.Y + ctx->Scissor.Height;
if (xmin < 0)
xmin = 0;
if (xmax > fxMesa->width)
xmax = fxMesa->width;
if (ymin < fxMesa->screen_height - fxMesa->height)
ymin = fxMesa->screen_height - fxMesa->height;
if (ymax > fxMesa->screen_height - 0)
ymax = fxMesa->screen_height - 0;
}
else {
xmin = 0;
ymin = 0;
xmax = fxMesa->width;
ymax = fxMesa->height;
}
fxMesa->clipMinX = xmin;
fxMesa->clipMinY = ymin;
fxMesa->clipMaxX = xmax;
fxMesa->clipMaxY = ymax;
grClipWindow(xmin, ymin, xmax, ymax);
}
void
fxSetupScissor(GLcontext * ctx)
{
BEGIN_BOARD_LOCK();
fxSetScissorValues(ctx);
END_BOARD_LOCK();
}
void
fxDDScissor(GLcontext * ctx, GLint x, GLint y, GLsizei w, GLsizei h)
{
FX_CONTEXT(ctx)->new_state |= FX_NEW_SCISSOR;
}
/************************************************************************/
/*************************** Cull mode setup ****************************/
/************************************************************************/
void
fxDDCullFace(GLcontext * ctx, GLenum mode)
{
(void) mode;
FX_CONTEXT(ctx)->new_state |= FX_NEW_CULL;
}
void
fxDDFrontFace(GLcontext * ctx, GLenum mode)
{
(void) mode;
FX_CONTEXT(ctx)->new_state |= FX_NEW_CULL;
}
void
fxSetupCull(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
GrCullMode_t mode = GR_CULL_DISABLE;
if (ctx->Polygon.CullFlag && (fxMesa->raster_primitive == GL_TRIANGLES)) {
switch (ctx->Polygon.CullFaceMode) {
case GL_BACK:
if (ctx->Polygon.FrontFace == GL_CCW)
mode = GR_CULL_NEGATIVE;
else
mode = GR_CULL_POSITIVE;
break;
case GL_FRONT:
if (ctx->Polygon.FrontFace == GL_CCW)
mode = GR_CULL_POSITIVE;
else
mode = GR_CULL_NEGATIVE;
break;
case GL_FRONT_AND_BACK:
/* Handled as a fallback on triangles in tdfx_tris.c */
return;
default:
ASSERT(0);
break;
}
}
if (fxMesa->cullMode != mode) {
fxMesa->cullMode = mode;
grCullMode(mode);
}
}
/************************************************************************/
/****************************** DD Enable ******************************/
/************************************************************************/
void
fxDDEnable(GLcontext * ctx, GLenum cap, GLboolean state)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
tfxUnitsState *us = &fxMesa->unitsState;
if (TDFX_DEBUG & VERBOSE_DRIVER) {
fprintf(stderr, "%s(%s)\n", state ? "fxDDEnable" : "fxDDDisable",
_mesa_lookup_enum_by_nr(cap));
}
switch (cap) {
case GL_ALPHA_TEST:
if (state != us->alphaTestEnabled) {
us->alphaTestEnabled = state;
fxMesa->new_state |= FX_NEW_ALPHA;
}
break;
case GL_BLEND:
if (state != us->blendEnabled) {
us->blendEnabled = state;
fxMesa->new_state |= FX_NEW_BLEND;
}
break;
case GL_DEPTH_TEST:
if (state != us->depthTestEnabled) {
us->depthTestEnabled = state;
fxMesa->new_state |= FX_NEW_DEPTH;
}
break;
case GL_STENCIL_TEST:
if (fxMesa->haveHwStencil && state != us->stencilEnabled) {
us->stencilEnabled = state;
fxMesa->new_state |= FX_NEW_STENCIL;
}
break;
case GL_DITHER:
if (state) {
grDitherMode(GR_DITHER_4x4);
}
else {
grDitherMode(GR_DITHER_DISABLE);
}
break;
case GL_SCISSOR_TEST:
fxMesa->new_state |= FX_NEW_SCISSOR;
break;
case GL_SHARED_TEXTURE_PALETTE_EXT:
fxDDTexUseGlbPalette(ctx, state);
break;
case GL_FOG:
fxMesa->new_state |= FX_NEW_FOG;
break;
case GL_CULL_FACE:
fxMesa->new_state |= FX_NEW_CULL;
break;
case GL_LINE_SMOOTH:
case GL_LINE_STIPPLE:
case GL_POINT_SMOOTH:
case GL_POLYGON_SMOOTH:
case GL_TEXTURE_1D:
case GL_TEXTURE_2D:
fxMesa->new_state |= FX_NEW_TEXTURING;
break;
default:
; /* XXX no-op? */
}
}
/************************************************************************/
/************************** Changes to units state **********************/
/************************************************************************/
/* All units setup is handled under texture setup.
*/
void
fxDDShadeModel(GLcontext * ctx, GLenum mode)
{
FX_CONTEXT(ctx)->new_state |= FX_NEW_TEXTURING;
}
/************************************************************************/
/****************************** Units SetUp *****************************/
/************************************************************************/
static void
fx_print_state_flags(const char *msg, GLuint flags)
{
fprintf(stderr,
"%s: (0x%x) %s%s%s%s%s%s%s%s\n",
msg,
flags,
(flags & FX_NEW_TEXTURING) ? "texture, " : "",
(flags & FX_NEW_BLEND) ? "blend, " : "",
(flags & FX_NEW_ALPHA) ? "alpha, " : "",
(flags & FX_NEW_FOG) ? "fog, " : "",
(flags & FX_NEW_SCISSOR) ? "scissor, " : "",
(flags & FX_NEW_COLOR_MASK) ? "colormask, " : "",
(flags & FX_NEW_CULL) ? "cull, " : "",
(flags & FX_NEW_STENCIL) ? "stencil, " : "");
}
void
fxSetupFXUnits(GLcontext * ctx)
{
fxMesaContext fxMesa = FX_CONTEXT(ctx);
GLuint newstate = fxMesa->new_state;
if (TDFX_DEBUG & VERBOSE_DRIVER)
fx_print_state_flags("fxSetupFXUnits", newstate);
if (newstate) {
if (newstate & FX_NEW_TEXTURING)
fxSetupTexture(ctx);
if (newstate & FX_NEW_BLEND)
fxSetupBlend(ctx);
if (newstate & FX_NEW_ALPHA)
fxSetupAlphaTest(ctx);
if (newstate & FX_NEW_DEPTH)
fxSetupDepthTest(ctx);
if (newstate & FX_NEW_STENCIL)
fxSetupStencil(ctx);
if (newstate & FX_NEW_FOG)
fxSetupFog(ctx);
if (newstate & FX_NEW_SCISSOR)
fxSetupScissor(ctx);
if (newstate & FX_NEW_COLOR_MASK)
fxSetupColorMask(ctx);
if (newstate & FX_NEW_CULL)
fxSetupCull(ctx);
fxMesa->new_state = 0;
}
}
#else
/*
* Need this to provide at least one external definition.
*/
extern int gl_fx_dummy_function_setup(void);
int
gl_fx_dummy_function_setup(void)
{
return 0;
}
#endif /* FX */
|
the_stack_data/407002.c | /* spoof_syslog.c
*
* This program sends a spoofed syslog message. You have to be root to run it.
* Source and target IP addresses, message text, facility and priority are
* supplied by the user.
*
* The code compiles and works under Linux. Any Unix that has
* SOCK_RAW/IPPROTO_RAW should be no problem (you may need to use BSD-style
* struct ip though). It could use a few improvements, like checking for possible
* ICMP Port Unreachable errors in case the remote machine doesn't run syslogd
* with remote reception turned on.
*
* The idea behind this program is a proof of a concept, nothing more. It
* comes as is, no warranty.
*
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <netdb.h>
#include <syslog.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <netinet/ip.h>
#define IPVERSION 4
/* This is the stuff that actually gets sent. Feel free to change it */
#define MESSAGE_FAC LOG_LOCAL7
// #define MESSAGE_PRI LOG_INFO
// char message[] = {"logreplay[4489]: connection from [email protected]\n"};
struct raw_pkt_hdr {
struct iphdr ip; /* This is Linux-style iphdr.
Use BSD-style struct ip if you want */
struct udphdr udp;
};
struct raw_pkt_hdr* pkt;
void die(char *);
unsigned long int get_ip_addr(char*);
unsigned short checksum(unsigned short*,char);
/* Added by Ethan */
#define NUM_CMD_ARGS 5 /* Take 5 args from command line */
/* I'm guessing about these paramters. Rename them to make more sense. */
char *log_message;
int priority;
/* End Added by Ethan */
int main(int argc,char** argv){
struct sockaddr_in sa;
int sock,packet_len;
char usage[] = {"\
Spoof a syslog message to appear from a specified source\n\
usage: spoof src_hostname dst_hostname \"message\" severity[integer]\n\
Example: ./spoof 1.1.1.1 127.0.0.1 \"Log_Replay[7306]: %LINK-3-UPDOWN: Interface FastEthernet1/0/19, changed state to up\" 3 \n"};
char on = 1;
if(argc != NUM_CMD_ARGS)
die(usage);
log_message = argv[3];
priority = atoi(argv[4]);
/* EDB: Remove this if you don't want the run-time arg info printed out: */
printf("Running using args:\n\tIP1: %s\n\tIP2: %s\n\tMessage: %s\n\tSeverity: %i\n", argv[1], argv[2], log_message, priority);
if( (sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0){
perror("socket");
exit(1);
}
sa.sin_addr.s_addr = get_ip_addr(argv[2]);
sa.sin_family = AF_INET;
packet_len = sizeof(struct raw_pkt_hdr)+strlen(log_message)+5;
pkt = calloc((size_t)1,(size_t)packet_len);
pkt->ip.version = IPVERSION;
pkt->ip.ihl = sizeof(struct iphdr) >> 2;
pkt->ip.tos = 0;
pkt->ip.tot_len = htons(packet_len);
pkt->ip.id = htons(getpid() & 0xFFFF);
pkt->ip.frag_off = 0;
pkt->ip.ttl = 0x40;
pkt->ip.protocol = IPPROTO_UDP;
pkt->ip.check = 0;
pkt->ip.saddr = get_ip_addr(argv[1]);
pkt->ip.daddr = sa.sin_addr.s_addr;
pkt->ip.check = checksum((unsigned short*)pkt,sizeof(struct iphdr));
pkt->udp.source = htons(514);
pkt->udp.dest = htons(514);
pkt->udp.len = htons(packet_len - sizeof(struct iphdr));
pkt->udp.check = 0; /* If you feel like screwing around with pseudo-headers
and stuff, you may of course calculate UDP checksum
as well. I chose to leave it zero, it's usually OK */
sprintf((char*)pkt+sizeof(struct raw_pkt_hdr),"<%d>%s",
(int)(MESSAGE_FAC | priority),log_message);
if (setsockopt(sock,IPPROTO_IP,IP_HDRINCL,(char *)&on,sizeof(on)) < 0) {
perror("setsockopt: IP_HDRINCL");
exit(1);
}
if(sendto(sock,pkt,packet_len,0,(struct sockaddr*)&sa,sizeof(sa)) < 0){
perror("sendto");
exit(1);
}
exit(0);
}
void die(char* str){
fprintf(stderr,"%s\n",str);
exit(1);
}
unsigned long int get_ip_addr(char* str){
struct hostent *hostp;
unsigned long int addr;
if( (addr = inet_addr(str)) == -1){
if( (hostp = gethostbyname(str)))
return *(unsigned long int*)(hostp->h_addr);
else {
fprintf(stderr,"unknown host %s\n",str);
}
}
return addr;
}
unsigned short checksum(unsigned short* addr,char len){
/* This is a simplified version that expects even number of bytes */
register long sum = 0;
while(len > 1){
sum += *addr++;
len -= 2;
}
while (sum>>16) sum = (sum & 0xffff) + (sum >> 16);
return ~sum;
}
|
the_stack_data/29920.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* init.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vtarasiu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/05 16:57:26 by vtarasiu #+# #+# */
/* Updated: 2019/06/05 16:57:26 by vtarasiu ### ########.fr */
/* */
/* ************************************************************************** */
|
the_stack_data/86162.c | #include <stdio.h>
#include <assert.h>
/**
* Declaración de auxiliares para el ejercicio
*/
/**
* Enumeración auxiliar para el ejercicio.
*
* Enumeracion con los resultados posibles de una prueba, para ser
* más claros con los resultados esperados
*/
enum TestResult
{
FAILED = 0,
PASSED = 1
};
enum TestResult testStringLengthIs(char string[], unsigned int expectedLength);
/**
* INSTRUCCIONES:
* 1. Sin usar las funciones de la librería string.h, implementa una función
* que cuente la cantidad de caracteres dentro de un string terminado en
* nulo, y la regrese como su longitud.
*
* 2. Asegúrate que al ejecutarse tu programa todos los casos de prueba pasan exitosamente.
* El programa debe mostrar solamente el mensaje: Ejercicio terminado con éxito.
*/
/**
* Calcula la longitud del string terminado en nulo especificado y la regresa.
*/
unsigned int stringLength(char string[])
{
/* Implementa aquí tu función */
return 42;
}
int main()
{
assert(testStringLengthIs("Nanuk!", 6) == PASSED);
assert(testStringLengthIs("hola que tal", 12) == PASSED);
assert(testStringLengthIs("\n\n\n", 3) == PASSED);
assert(testStringLengthIs("", 0) == PASSED);
assert(testStringLengthIs("\0", 0) == PASSED);
printf("OK! Funcion implementada correctamente\n");
}
/**
* IMPLEMENTACION DE FUNCIONES DE PRUEBA
*/
/**
* Función auxiliar para el ejercicio.
*
* Prueba la funcion stringLength con el string especificado y comapara
* el resultado con la longitud esperada que se indique.
*
* Regresa el resultado de la prueba
*/
enum TestResult testStringLengthIs(char string[], unsigned int expectedLength)
{
unsigned int got = stringLength(string);
if (got != expectedLength)
{
printf("FAIL:\n stringLength( %s ): expected %i but got %i instead\n", string, expectedLength, got);
return FAILED;
}
return PASSED;
}
|
the_stack_data/32948962.c | struct S
{
_Static_assert(1, "in struct");
int x;
} asd;
_Static_assert(1, "global scope");
int main()
{
_Static_assert(1, "in function");
}
|
the_stack_data/165765681.c | /* Not needed anymore. */
|
the_stack_data/118913.c | /* Example code for Think OS.
Copyright 2014 Allen Downey
License: GNU GPLv3
*/
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
int *foo() {
int i;
int array[SIZE];
printf("%p\n", array);
for (i=0; i<SIZE; i++) {
array[i] = 42;
}
return array;
}
void bar() {
int i;
int array[SIZE];
//printf("%p\n", array);
for (i=0; i<SIZE; i++) {
array[i] = i;
}
}
int main()
{
int i;
int *array = foo();
bar();
for (i=0; i<SIZE; i++) {
printf("%d\n", array[i]);
}
return 0;
}
/*
### Stack allocated data
1. Read `stack.c`, which should be in this directory. What is it
intended to do? What would the output be if the program worked as
expected?
The program inteds to make an array of size 5 filled with the number 42
in each element of the array. It then intends to print the array and change the
values to be 1 2 3 4 5.
Finally it is supposed to print the array.
2. You get a warning in the function "foo"
warning: function returns address of local variable [-Wreturn-local-addr]
return array;
This function returns the address of a local variable. Local variables are
created in the stack and destroyed when the program goes out of scope. This
function returns a pointer to an invalid memory location.
3. When running the code I got a segmentation fault. This means I am trying to
access data I don't have access to.
4. When commenting out the print statements in foo() and bar() I still get a
seg fault. I remove the seg fault by commenting out the final print statement in
main(), rintf("%d\n", array[i]); This is because we are trying to access array.
Array was created in foo and then destroyed so the pointer doesn't point to a
valid place in memory. A way to fix this would be to pass a variable that can
exist between the scopes of these funcitons or not point to stack allocated data.
*/
|
the_stack_data/3262639.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//#include "tools.h"
void vecacc(int n, float* src1, float* src2, float* result)
{
int i;
#pragma vector aligned
#pragma ivdep
for(i=0;i<n;i++)
result[i]=src1[i]*src2[i];
}
int main(int argc, char **argv)
{
int n;
float *src1, *src2, *result;
n = atoi(argv[1]);
#define xmalloc(p) \
do { \
if (posix_memalign((void **) &p, 32, n * sizeof(float))) \
return 3; \
} while(0);
#define vmalloc(p)\
do {\
p=(float*)malloc(n*sizeof(float));\
} while(0)
xmalloc(src1);
xmalloc(src2);
xmalloc(result);
init_data_file(argv[2]);
init_data_float(src1, n);
init_data_float(src2, n);
close_data_file();
vecacc(n, src1, src2, result);
print_array_float("result", result, n);
free(src1);
free(src2);
free(result);
return 0;
}
|
the_stack_data/6329.c |
/*
PowerTerm(R) for HP Performance Software for Windows XP/2003/2008/7/2008 R2/8/2012
Version: 10.2.0
Copyright (C) 1994-2014 Ericom(R) Software
*/
vuser_end()
{
return 0;
}
|
the_stack_data/79568.c | /**********************************************************************************/
/* MIT License */
/* */
/* Copyright (c) 2020 Joel Svensson */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining a copy */
/* of this software and associated documentation files (the "Software"), to deal */
/* in the Software without restriction, including without limitation the rights */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */
/* copies of the Software, and to permit persons to whom the Software is */
/* furnished to do so, subject to the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be included in all */
/* copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */
/* SOFTWARE. */
/**********************************************************************************/
#include <stdio.h>
#include <stdint.h>
typedef enum {
nothing,
one_reg_any_imm12,
one_reg_any_registerlist,
two_regs_any_imm12,
two_regs_any_imm12_sf,
two_regs_any_imm5_sf,
two_regs_any_imm5_shift,
two_regs_any_imm5_shift_sf,
three_regs_any,
three_regs_any_sf,
three_regs_any_imm5_shift_sf,
cond_branch,
branch
} thumb32_opcode_format;
typedef struct {
char *name;
uint32_t opcode;
thumb32_opcode_format format;
} thumb32_opcode;
const thumb32_opcode opcodes[] =
{ {"m0_dsb" , 0b11110011101111111000111101001111, nothing},
{"m0_dmb" , 0b11110011101111111000111101011111, nothing},
{"m0_isb" , 0b11110011101111111000111101101111, nothing},
{"m0_bl" , 0b11110000000000001100000000000000, branch},
{"m3_adc_imm" , 0b11110001010000000000000000000000, two_regs_any_imm12_sf},
{"m3_adc_any" , 0b11101011010000000000000000000000, three_regs_any_imm5_shift_sf},
{"m3_add_const" , 0b11110001000000000000000000000000, two_regs_any_imm12_sf},
{"m3_add_imm" , 0b11110010000000000000000000000000, two_regs_any_imm12},
{"m3_add_any" , 0b11101011000000000000000000000000, three_regs_any_imm5_shift_sf},
{"m3_add_sp_imm" , 0b11101011000011010000000000000000, two_regs_any_imm5_shift_sf},
{"m3_add_pc_imm" , 0b11110010000011110000000000000000, one_reg_any_imm12},
{"m3_sub_pc_imm" , 0b11110010101011110000000000000000, one_reg_any_imm12},
{"m3_and_imm" , 0b11110000000000000000000000000000, two_regs_any_imm12_sf},
{"m3_and_any" , 0b11101010000000000000000000000000, three_regs_any_imm5_shift_sf},
{"m3_asr_imm" , 0b11101010010011110000000000100000, two_regs_any_imm5_sf},
{"m3_asr_any" , 0b11111010010000001111000000000000, three_regs_any_sf},
{"m3_beq" , 0b11110000000000001000000000000000, cond_branch},
{"m3_bne" , 0b11110000010000001000000000000000, cond_branch},
{"m3_bcs" , 0b11110000100000001000000000000000, cond_branch},
{"m3_bcc" , 0b11110000110000001000000000000000, cond_branch},
{"m3_bmi" , 0b11110001000000001000000000000000, cond_branch},
{"m3_bpl" , 0b11110001010000001000000000000000, cond_branch},
{"m3_bvs" , 0b11110001100000001000000000000000, cond_branch},
{"m3_bvc" , 0b11110001110000001000000000000000, cond_branch},
{"m3_bhi" , 0b11110010000000001000000000000000, cond_branch},
{"m3_bls" , 0b11110010010000001000000000000000, cond_branch},
{"m3_bge" , 0b11110010100000001000000000000000, cond_branch},
{"m3_blt" , 0b11110010110000001000000000000000, cond_branch},
{"m3_bgt" , 0b11110011000000001000000000000000, cond_branch},
{"m3_ble" , 0b11110011010000001000000000000000, cond_branch},
{"m3_bal" , 0b11110011110000001000000000000000, cond_branch},
{"m3_b" , 0b11110000000000001001000000000000, branch},
{"m3_bic_imm" , 0b11110000001000000000000000000000, two_regs_any_imm12_sf},
{"m3_bic_any" , 0b11101000100000000000000000000000, three_regs_any_imm5_shift_sf},
{"m3_clrex" , 0b11110011101111111000111100101111, nothing},
{"m3_clz" , 0b11111010101100001111000010000000, three_regs_any},
{"m3_cmn_imm" , 0b11110001000100000000111100000000, one_reg_any_imm12},
{"m3_cmn_any" , 0b11101011000100000000111100000000, two_regs_any_imm5_shift},
{"m3_cmp_imm" , 0b11110001101100000000111100000000, one_reg_any_imm12},
{"m3_cmp_any" , 0b11101011101100000000111100000000, two_regs_any_imm5_shift},
{"m3_csdb" , 0b11110011101011111000000000010100, nothing},
{"m3_eor_imm" , 0b11110000100000000000000000000000, two_regs_any_imm12_sf},
{"m3_eor_any" , 0b11101010100000000000000000000000, three_regs_any_imm5_shift_sf},
{"m3_ldm" , 0b11101000100100000000000000000000, one_reg_any_registerlist},
{"m3_ldmw" , 0b11101000101100000000000000000000, one_reg_any_registerlist},
{"m3_ldmdb" , 0b11101001000100000000000000000000, one_reg_any_registerlist},
{"m3_ldmdbw" , 0b11101001001100000000000000000000, one_reg_any_registerlist},
{"m3_ldr_imm" , 0b11111000110100000000000000000000, two_regs_any_imm12},
{NULL, 0, 0}};
/* left out for now,
DBG
LDC, LDC2
*/
void print_extern_decl(thumb32_opcode op) {
switch(op.format) {
case nothing:
printf("extern thumb_opcode_t %s(void);\n", op.name);
break;
case one_reg_any_imm12:
printf("extern thumb_opcode_t %s(reg_t rd, uint16_t imm12);\n", op.name);
break;
case one_reg_any_registerlist:
printf("extern thumb_opcode_t %s(reg_t rn, uint16_t rl);\n", op.name);
break;
case two_regs_any_imm12:
printf("extern thumb_opcode_t %s(reg_t rd, reg_t rn, uint16_t imm12);\n", op.name);
break;
case two_regs_any_imm12_sf:
printf("extern thumb_opcode_t %s(reg_t rd, reg_t rn, uint16_t imm12, bool sf);\n", op.name);
break;
case two_regs_any_imm5_sf:
printf("extern thumb_opcode_t %s(reg_t rd, reg_t rn, uint8_t imm5, bool sf);\n", op.name);
break;
case two_regs_any_imm5_shift:
printf("extern thumb_opcode_t %s(reg_t rd, reg_t rn, uint8_t imm5, imm_shift_t shift);\n", op.name);
break;
case two_regs_any_imm5_shift_sf:
printf("extern thumb_opcode_t %s(reg_t rd, reg_t rn, uint8_t imm5, imm_shift_t shift, bool sf);\n", op.name);
break;
case three_regs_any:
printf("extern thumb_opcode_t %s(reg_t rd, reg_t rn, reg_t rm);\n", op.name);
break;
case three_regs_any_sf:
printf("extern thumb_opcode_t %s(reg_t rd, reg_t rn, reg_t rm, bool sf);\n", op.name);
break;
case three_regs_any_imm5_shift_sf:
printf("extern thumb_opcode_t %s(reg_t rd, reg_t rn, reg_t rm, uint8_t imm5, imm_shift_t shift, bool sf);\n", op.name);
break;
case cond_branch:
printf("extern thumb_opcode_t %s(int32_t offset);\n", op.name);
break;
case branch:
printf("extern thumb_opcode_t %s(int32_t offset);\n", op.name);
break;
default:
printf("Error - unknown\n");
break;
}
}
void print_opcode(thumb32_opcode op) {
switch(op.format) {
case nothing:
printf("thumb_opcode_t %s(void) {\n", op.name);
printf(" return thumb32_opcode(%u);\n", op.opcode);
printf("}\n\n");
break;
case one_reg_any_imm12:
printf("thumb_opcode_t %s(reg_t rd,uint16_t imm12) {\n", op.name);
printf(" return thumb32_opcode_one_reg_any_imm12(%u, rd, imm12);\n", op.opcode);
printf("}\n\n");
break;
case one_reg_any_registerlist:
printf("thumb_opcode_t %s(reg_t rn, uint16_t rl) {\n", op.name);
printf(" return thump32_opcode_one_reg_any_registerlist(%u, rn, rl);\n", op.opcode);
printf("}\n\n");
break;
case two_regs_any_imm12:
printf("thumb_opcode_t %s(reg_t rd, reg_t rn, uint16_t imm12) {\n", op.name);
printf(" return thumb32_opcode_two_regs_any_imm12(%u, rd, rn, imm12);\n", op.opcode);
printf("}\n\n");
break;
case two_regs_any_imm12_sf:
printf("thumb_opcode_t %s(reg_t rd, reg_t rn, uint16_t imm12, bool sf) {\n", op.name);
printf(" return thumb32_opcode_two_regs_any_imm12_sf(%u, rd, rn, imm12, sf);\n", op.opcode);
printf("}\n\n");
break;
case two_regs_any_imm5_sf:
printf("thumb_opcode_t %s(reg_t rd, reg_t rn, uint8_t imm5, bool sf) {\n", op.name);
printf(" return thumb32_opcode_two_regs_any_imm5_sf(%u, rd, rn, imm5, sf);\n", op.opcode);
printf("}\n\n");
break;
case two_regs_any_imm5_shift:
printf("thumb_opcode_t %s(reg_t rd, reg_t rn, uint8_t imm5, imm_shift_t shift) {\n", op.name);
printf(" return thumb32_opcode_two_regs_any_imm5_shift(%u, rd, rn, imm5, shift);\n", op.opcode);
printf("}\n\n");
break;
case two_regs_any_imm5_shift_sf:
printf("thumb_opcode_t %s(reg_t rd, reg_t rn, uint8_t imm5, imm_shift_t shift, bool sf) {\n", op.name);
printf(" return thumb32_opcode_two_regs_any_imm5_shift_sf(%u, rd, rn, imm5, shift, sf);\n", op.opcode);
printf("}\n\n");
break;
case three_regs_any:
printf("thumb_opcode_t %s(reg_t rd, reg_t rn, reg_t rm) {\n", op.name);
printf(" return thumb32_opcode_three_regs_any(%u, rd, rn, rm); \n", op.opcode);
printf("}\n\n");
break;
case three_regs_any_sf:
printf("thumb_opcode_t %s(reg_t rd, reg_t rn, reg_t rm, bool sf) {\n", op.name);
printf(" return thumb32_opcode_three_regs_any_sf(%u, rd, rn, rm, sf); \n", op.opcode);
printf("}\n\n");
break;
case three_regs_any_imm5_shift_sf:
printf("thumb_opcode_t %s(reg_t rd, reg_t rn, reg_t rm, uint8_t imm5, imm_shift_t shift, bool sf) {\n", op.name);
printf(" return thumb32_opcode_three_regs_any_imm5_shift_sf(%u, rd, rn, rm, imm5, shift, sf); \n", op.opcode);
printf("}\n\n");
break;
case cond_branch:
printf("thumb_opcode_t %s(int32_t offset) {\n", op.name);
printf(" return thumb32_opcode_cond_branch(%u, offset); \n", op.opcode);
printf("}\n\n");
break;
case branch:
printf("thumb_opcode_t %s(int32_t offset) {\n", op.name);
printf(" return thumb32_opcode_branch(%u, offset); \n", op.opcode);
printf("}\n\n");
break;
default:
printf("Error - unknown (%s)", op.name);
break;
}
}
void unique_ops() {
int i = 0;
while (opcodes[i].name) {
int j = i+1;
while (opcodes[j].name) {
if (i != j && opcodes[i].opcode == opcodes[j].opcode) {
printf("WARNING!\n");
printf("opcodes at indices %d and %d are the same\n", i, j);
printf("%d: %s : %u \n", i, opcodes[i].name, opcodes[i].opcode);
printf("%d: %s : %u \n", j, opcodes[j].name, opcodes[j].opcode);
printf("\n");
}
j++;
}
i++;
}
}
int main(int argc, char **argv) {
int i = 0;
unique_ops();
i = 0;
while (opcodes[i].name) {
print_extern_decl(opcodes[i++]);
}
printf("\n\n\n");
i = 0;
while (opcodes[i].name) {
print_opcode(opcodes[i++]);
}
return 0;
}
|
the_stack_data/154829634.c | /********************************************************************************
* tools/nxstyle.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you 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.
*
********************************************************************************/
/********************************************************************************
* Included Files
********************************************************************************/
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <limits.h>
#include <unistd.h>
#include <libgen.h>
/********************************************************************************
* Pre-processor Definitions
********************************************************************************/
#define NXSTYLE_VERSION "0.01"
#define LINE_SIZE 512
#define RANGE_NUMBER 4096
#define DEFAULT_WIDTH 78
#define FIRST_SECTION INCLUDED_FILES
#define LAST_SECTION PUBLIC_FUNCTION_PROTOTYPES
#define FATAL(m, l, o) message(FATAL, (m), (l), (o))
#define FATALFL(m, s) message(FATAL, (m), -1, -1)
#define WARN(m, l, o) message(WARN, (m), (l), (o))
#define ERROR(m, l, o) message(ERROR, (m), (l), (o))
#define ERRORFL(m, s) message(ERROR, (m), -1, -1)
#define INFO(m, l, o) message(INFO, (m), (l), (o))
#define INFOFL(m, s) message(INFO, (m), -1, -1)
/********************************************************************************
* Private types
********************************************************************************/
enum class_e
{
INFO,
WARN,
ERROR,
FATAL
};
const char *class_text[] =
{
"info",
"warning",
"error",
"fatal"
};
enum file_e
{
UNKNOWN = 0x00,
C_HEADER = 0x01,
C_SOURCE = 0x02
};
enum section_s
{
NO_SECTION = 0,
INCLUDED_FILES,
PRE_PROCESSOR_DEFINITIONS,
PUBLIC_TYPES,
PRIVATE_TYPES,
PRIVATE_DATA,
PUBLIC_DATA,
PRIVATE_FUNCTIONS,
PRIVATE_FUNCTION_PROTOTYPES,
INLINE_FUNCTIONS,
PUBLIC_FUNCTIONS,
PUBLIC_FUNCTION_PROTOTYPES
};
enum pptype_e
{
PPLINE_NONE = 0,
PPLINE_DEFINE,
PPLINE_IF,
PPLINE_ELIF,
PPLINE_ELSE,
PPLINE_ENDIF,
PPLINE_OTHER
};
struct file_section_s
{
const char *name; /* File section name */
uint8_t ftype; /* File type where section found */
};
/********************************************************************************
* Private data
********************************************************************************/
static enum file_e g_file_type = UNKNOWN;
static enum section_s g_section = NO_SECTION;
static int g_maxline = DEFAULT_WIDTH;
static int g_status = 0;
static int g_verbose = 2;
static int g_rangenumber = 0;
static int g_rangestart[RANGE_NUMBER];
static int g_rangecount[RANGE_NUMBER];
static char g_file_name[PATH_MAX];
static const struct file_section_s g_section_info[] =
{
{
" *\n", /* Index: NO_SECTION */
C_SOURCE | C_HEADER
},
{
" * Included Files\n", /* Index: INCLUDED_FILES */
C_SOURCE | C_HEADER
},
{
" * Pre-processor Definitions\n", /* Index: PRE_PROCESSOR_DEFINITIONS */
C_SOURCE | C_HEADER
},
{
" * Public Types\n", /* Index: PUBLIC_TYPES */
C_HEADER
},
{
" * Private Types\n", /* Index: PRIVATE_TYPES */
C_SOURCE
},
{
" * Private Data\n", /* Index: PRIVATE_DATA */
C_SOURCE
},
{
" * Public Data\n", /* Index: PUBLIC_DATA */
C_SOURCE | C_HEADER
},
{
" * Private Functions\n", /* Index: PRIVATE_FUNCTIONS */
C_SOURCE
},
{
" * Private Function Prototypes\n", /* Index: PRIVATE_FUNCTION_PROTOTYPES */
C_SOURCE
},
{
" * Inline Functions\n", /* Index: INLINE_FUNCTIONS */
C_SOURCE | C_HEADER
},
{
" * Public Functions\n", /* Index: PUBLIC_FUNCTIONS */
C_SOURCE
},
{
" * Public Function Prototypes\n", /* Index: PUBLIC_FUNCTION_PROTOTYPES */
C_SOURCE | C_HEADER
}
};
static const char *g_white_prefix[] =
{
"Elf", /* Ref: include/elf.h, include/elf32.h, include/elf64.h */
"PRId", /* Ref: inttypes.h */
"PRIi", /* Ref: inttypes.h */
"PRIo", /* Ref: inttypes.h */
"PRIu", /* Ref: inttypes.h */
"PRIx", /* Ref: inttypes.h */
"SCNd", /* Ref: inttypes.h */
"SCNi", /* Ref: inttypes.h */
"SCNo", /* Ref: inttypes.h */
"SCNu", /* Ref: inttypes.h */
"SCNx", /* Ref: inttypes.h */
"SYS_", /* Ref: include/sys/syscall.h */
"STUB_", /* Ref: syscall/syscall_lookup.h, syscall/sycall_stublookup.c */
"b8", /* Ref: include/fixedmath.h */
"b16", /* Ref: include/fixedmath.h */
"b32", /* Ref: include/fixedmath.h */
"ub8", /* Ref: include/fixedmath.h */
"ub16", /* Ref: include/fixedmath.h */
"ub32", /* Ref: include/fixedmath.h */
"ASCII_", /* Ref: include/nuttx/ascii.h */
"XK_", /* Ref: include/input/X11_keysymdef.h */
NULL
};
static const char *g_white_list[] =
{
/* Ref: gnu_unwind_find_exidx.c */
"__EIT_entry",
/* Ref: gnu_unwind_find_exidx.c */
"__gnu_Unwind_Find_exidx",
/* Ref: stdlib.h */
"_Exit",
/* Ref: stdatomic.h */
"_Atomic",
/* Ref: unwind-arm-common.h */
"_Unwind",
/* Ref:
* https://pubs.opengroup.org/onlinepubs/9699919799/functions/tempnam.html
*/
"P_tmpdir",
/* Ref:
* https://pubs.opengroup.org/onlinepubs/9699919799/functions/tempnam.html
*/
"L_tmpnam",
/* Ref:
* nuttx/compiler.h
*/
"_Far",
"_Erom",
/* Ref:
* arch/sim/src/sim/up_wpcap.c
*/
"Address",
"Description",
"FirstUnicastAddress",
"GetAdaptersAddresses",
"GetProcAddress",
"LoadLibrary",
"lpSockaddr",
"Next",
"PhysicalAddressLength",
"PhysicalAddress",
"WideCharToMultiByte",
/* Ref:
* fs/nfs/rpc.h
* fs/nfs/nfs_proto.h
* fs/nfs/nfs_mount.h
* fs/nfs/nfs_vfsops.c
*/
"CREATE3args",
"CREATE3resok",
"LOOKUP3args",
"LOOKUP3filename",
"LOOKUP3resok",
"WRITE3args",
"WRITE3resok",
"READ3args",
"READ3resok",
"REMOVE3args",
"REMOVE3resok",
"RENAME3args",
"RENAME3resok",
"MKDIR3args",
"MKDIR3resok",
"RMDIR3args",
"RMDIR3resok",
"READDIR3args",
"READDIR3resok",
"SETATTR3args",
"SETATTR3resok",
"FS3args",
"SIZEOF_rpc_reply_read",
"SIZEOF_rpc_call_write",
"SIZEOF_rpc_reply_readdir",
"SIZEOF_nfsmount",
/* Ref:
* mm/kasan/kasan.c
*/
"__asan_loadN",
"__asan_storeN",
"__asan_loadN_noabort",
"__asan_storeN_noabort",
NULL
};
/********************************************************************************
* Private Functions
********************************************************************************/
/********************************************************************************
* Name: show_usage
*
* Description:
*
********************************************************************************/
static void show_usage(char *progname, int exitcode, char *what)
{
fprintf(stderr, "%s version %s\n\n", basename(progname), NXSTYLE_VERSION);
if (what)
{
fprintf(stderr, "%s\n", what);
}
fprintf(stderr, "Usage: %s [-m <excess>] [-v <level>] "
"[-r <start,count>] <filename>\n",
basename(progname));
fprintf(stderr, " %s -h this help\n", basename(progname));
fprintf(stderr, " %s -v <level> where level is\n",
basename(progname));
fprintf(stderr, " 0 - no output\n");
fprintf(stderr, " 1 - PASS/FAIL\n");
fprintf(stderr, " 2 - output each line (default)\n");
exit(exitcode);
}
/********************************************************************************
* Name: skip
*
* Description:
*
********************************************************************************/
static int skip(int lineno)
{
int i;
for (i = 0; i < g_rangenumber; i++)
{
if (lineno >= g_rangestart[i] && lineno < g_rangestart[i] +
g_rangecount[i])
{
return 0;
}
}
return g_rangenumber != 0;
}
/********************************************************************************
* Name: message
*
* Description:
*
********************************************************************************/
static int message(enum class_e class, const char *text, int lineno, int ndx)
{
FILE *out = stdout;
if (skip(lineno))
{
return g_status;
}
if (class > INFO)
{
out = stderr;
g_status |= 1;
}
if (g_verbose == 2)
{
if (lineno == -1 && ndx == -1)
{
fprintf(out, "%s: %s: %s\n", g_file_name, class_text[class], text);
}
else
{
fprintf(out, "%s:%d:%d: %s: %s\n", g_file_name, lineno, ndx,
class_text[class], text);
}
}
return g_status;
}
/********************************************************************************
* Name: check_spaces_left
*
* Description:
*
********************************************************************************/
static void check_spaces_left(char *line, int lineno, int ndx)
{
/* Unary operator should generally be preceded by a space but make also
* follow a left parenthesis at the beginning of a parenthetical list or
* expression or follow a right parentheses in the case of a cast.
*/
if (ndx-- > 0 && line[ndx] != ' ' && line[ndx] != '(' && line[ndx] != ')')
{
ERROR("Operator/assignment must be preceded with whitespace",
lineno, ndx);
}
}
/********************************************************************************
* Name: check_spaces_leftright
*
* Description:
*
********************************************************************************/
static void check_spaces_leftright(char *line, int lineno, int ndx1, int ndx2)
{
if (ndx1 > 0 && line[ndx1 - 1] != ' ')
{
ERROR("Operator/assignment must be preceded with whitespace",
lineno, ndx1);
}
if (line[ndx2 + 1] != '\0' && line[ndx2 + 1] != '\n' && line[ndx2 + 1] != ' ')
{
ERROR("Operator/assignment must be followed with whitespace",
lineno, ndx2);
}
}
/********************************************************************************
* Name: check_nospaces_leftright
*
* Description:
* Check if there are whitespaces on the left of right. If there is, report
* an error.
*
********************************************************************************/
static void check_nospaces_leftright(char *line, int lineno, int ndx1, int ndx2)
{
if (ndx1 > 0 && line[ndx1 - 1] == ' ')
{
ERROR("There should be no spaces before the operator/assignment",
lineno, ndx1);
}
if (line[ndx2 + 1] == ' ')
{
ERROR("There should be no spaces after the operator/assignment",
lineno, ndx2);
}
}
/********************************************************************************
* Name: check_operand_leftright
*
* Description:
* Check if the operator is next to an operand. If not, report the error.
*
********************************************************************************/
static void check_operand_leftright(char *line, int lineno, int ndx1, int ndx2)
{
/* The cases below includes("xx" represents the operator):
* " xx " | " xx(end)" | " xx;" | " xx\n" | " xx)" | " xx]" - (ndx1 > 0)
* "(xx " | "(xx(end)" | "(xx;" | "(xx\n" | "(xx)" | "(xx]" - (ndx1 > 0)
* "[xx " | "[xx(end)" | "[xx;" | "[xx\n" | "[xx)" | "[xx]" - (ndx1 > 0)
* "xx " | "xx(end)" | "xx;" | "xx\n" | "xx)" | "xx]" - (ndx1 = 0)
* In these cases, the operators must be not next any operands, thus errors
* are reported.
*/
if (ndx1 > 0 && (line[ndx1 - 1] == ' ' || line[ndx1 - 1] == '(' ||
line[ndx1 - 1] == '[') &&
(line[ndx2 + 1] == ' ' || line[ndx2 + 1] == '\0' ||
line[ndx2 + 1] == ';' || line[ndx2 + 1] == '\n' ||
line[ndx2 + 1] == ')' || line[ndx2 + 1] == ']'))
{
ERROR("Operator must be next to an operand", lineno, ndx2);
}
}
/********************************************************************************
* Name: block_comment_width
*
* Description:
* Get the width of a block comment
*
********************************************************************************/
static int block_comment_width(char *line)
{
int b;
int e;
int n;
/* Skip over any leading whitespace on the line */
for (b = 0; isspace(line[b]); b++)
{
}
/* Skip over any trailing whitespace at the end of the line */
for (e = strlen(line) - 1; e >= 0 && isspace(line[e]); e--)
{
}
/* Number of characters on the line */
n = e - b + 1;
if (n < 4)
{
return 0;
}
/* The first line of a block comment starts with "[slash]***" and ends with
* "***"
*/
if (strncmp(&line[b], "/***", 4) == 0 &&
strncmp(&line[e - 2], "***", 3) == 0)
{
/* Return the the length of the line up to the final '*' */
return e + 1;
}
/* The last line of a block begins with whitespace then "***" and ends
* with "***[slash]"
*/
if (strncmp(&line[b], "***", 3) == 0 &&
strncmp(&line[e - 3], "***/", 4) == 0)
{
/* Return the the length of the line up to the final '*' */
return e;
}
/* But there is also a special single line comment that begins with "[slash]* "
* and ends with "***[slash]"
*/
if (strncmp(&line[b], "/*", 2) == 0 &&
strncmp(&line[e - 3], "***/", 4) == 0)
{
/* Return the the length of the line up to the final '*' */
return e;
}
/* Return zero if the line is not the first or last line of a block
* comment.
*/
return 0;
}
/********************************************************************************
* Name: get_line_width
*
* Description:
* Get the maximum line width by examining the width of the block comments.
*
********************************************************************************/
static int get_line_width(FILE *instream)
{
char line[LINE_SIZE]; /* The current line being examined */
int max = 0;
int min = INT_MAX;
int lineno = 0;
int lineno_max = 0;
int lineno_min = 0;
int len;
while (fgets(line, LINE_SIZE, instream))
{
lineno++;
len = block_comment_width(line);
if (len > 0)
{
if (len > max)
{
max = len;
lineno_max = lineno;
}
if (len < min)
{
min = len;
lineno_min = lineno;
}
}
}
if (max < min)
{
ERRORFL("No block comments found", g_file_name);
return DEFAULT_WIDTH;
}
else if (max != min)
{
ERROR("Block comments have different lengths", lineno_max, max);
ERROR("Block comments have different lengths", lineno_min, min);
return DEFAULT_WIDTH;
}
return min;
}
/********************************************************************************
* Name: check_section_header
*
* Description:
* Check if the current line holds a section header
*
********************************************************************************/
static bool check_section_header(const char *line, int lineno)
{
int i;
/* Search g_section_info[] to find a matching section header line */
for (i = FIRST_SECTION; i <= LAST_SECTION; i++)
{
if (strcmp(line, g_section_info[i].name) == 0)
{
g_section = (enum section_s)i;
/* Verify that this section is appropriate for this file type */
if ((g_file_type & g_section_info[i].ftype) == 0)
{
ERROR("Invalid section for this file type", lineno, 3);
}
return true;
}
}
return false;
}
/********************************************************************************
* Name: white_prefix
*
* Description:
* Return true if the identifier string begins with a white-listed prefix
*
********************************************************************************/
static bool white_list(const char *ident, int lineno)
{
const char **pptr;
const char *str;
for (pptr = g_white_prefix;
(str = *pptr) != NULL;
pptr++)
{
if (strncmp(ident, str, strlen(str)) == 0)
{
return true;
}
}
for (pptr = g_white_list;
(str = *pptr) != NULL;
pptr++)
{
size_t len = strlen(str);
if (strncmp(ident, str, len) == 0 &&
isalnum(ident[len]) == 0)
{
return true;
}
}
return false;
}
/********************************************************************************
* Public Functions
********************************************************************************/
int main(int argc, char **argv, char **envp)
{
FILE *instream; /* File input stream */
char line[LINE_SIZE]; /* The current line being examined */
char buffer[100]; /* Localy format error strings */
char *lptr; /* Temporary pointer into line[] */
char *ext; /* Temporary file extension */
bool btabs; /* True: TAB characters found on the line */
bool bcrs; /* True: Carriage return found on the line */
bool bfunctions; /* True: In private or public functions */
bool bstatm; /* True: This line is beginning of a statement */
bool bfor; /* True: This line is beginning of a 'for' statement */
bool bswitch; /* True: Within a switch statement */
bool bstring; /* True: Within a string */
bool bquote; /* True: Backslash quoted character next */
bool bblank; /* Used to verify block comment terminator */
bool bexternc; /* True: Within 'extern "C"' */
enum pptype_e ppline; /* > 0: The next line the continuation of a
* pre-processor command */
int rhcomment; /* Indentation of Comment to the right of code
* (-1 -> don't check position) */
int prevrhcmt; /* Indentation of previous Comment to the right
* of code (-1 -> don't check position) */
int lineno; /* Current line number */
int indent; /* Indentation level */
int ncomment; /* Comment nesting level on this line */
int prevncomment; /* Comment nesting level on the previous line */
int bnest; /* Brace nesting level on this line */
int prevbnest; /* Brace nesting level on the previous line */
int dnest; /* Data declaration nesting level on this line */
int prevdnest; /* Data declaration nesting level on the previous line */
int pnest; /* Parenthesis nesting level on this line */
int ppifnest; /* #if nesting level on this line */
int inasm; /* > 0: Within #ifdef __ASSEMBLY__ */
int comment_lineno; /* Line on which the last comment was closed */
int blank_lineno; /* Line number of the last blank line */
int noblank_lineno; /* A blank line is not needed after this line */
int lbrace_lineno; /* Line number of last left brace */
int rbrace_lineno; /* Last line containing a right brace */
int externc_lineno; /* Last line where 'extern "C"' declared */
int linelen; /* Length of the line */
int excess;
int n;
int i;
int c;
excess = 0;
while ((c = getopt(argc, argv, ":hv:gm:r:")) != -1)
{
switch (c)
{
case 'm':
excess = atoi(optarg);
if (excess < 1)
{
show_usage(argv[0], 1, "Bad value for <excess>.");
excess = 0;
}
break;
case 'v':
g_verbose = atoi(optarg);
if (g_verbose < 0 || g_verbose > 2)
{
show_usage(argv[0], 1, "Bad value for <level>.");
}
break;
case 'r':
g_rangestart[g_rangenumber] = atoi(strtok(optarg, ","));
g_rangecount[g_rangenumber++] = atoi(strtok(NULL, ","));
break;
case 'h':
show_usage(argv[0], 0, NULL);
break;
case ':':
show_usage(argv[0], 1, "Missing argument.");
break;
case '?':
show_usage(argv[0], 1, "Unrecognized option.");
break;
default:
show_usage(argv[0], 0, NULL);
break;
}
}
if (optind < argc - 1 || argv[optind] == NULL)
{
show_usage(argv[0], 1, "No file name given.");
}
/* Resolve the absolute path for the input file */
if (realpath(argv[optind], g_file_name) == NULL)
{
FATALFL("Failed to resolve absolute path.", g_file_name);
return 1;
}
/* Are we parsing a header file? */
ext = strrchr(g_file_name, '.');
if (ext == 0)
{
}
else if (strcmp(ext, ".h") == 0)
{
g_file_type = C_HEADER;
}
else if (strcmp(ext, ".c") == 0)
{
g_file_type = C_SOURCE;
}
if (g_file_type == UNKNOWN)
{
return 0;
}
instream = fopen(g_file_name, "r");
if (!instream)
{
FATALFL("Failed to open", g_file_name);
return 1;
}
/* Determine the line width */
g_maxline = get_line_width(instream) + excess;
rewind(instream);
btabs = false; /* True: TAB characters found on the line */
bcrs = false; /* True: Carriage return found on the line */
bfunctions = false; /* True: In private or public functions */
bswitch = false; /* True: Within a switch statement */
bstring = false; /* True: Within a string */
bexternc = false; /* True: Within 'extern "C"' */
ppline = PPLINE_NONE; /* > 0: The next line the continuation of a
* pre-processor command */
rhcomment = 0; /* Indentation of Comment to the right of code
* (-1 -> don't check position) */
prevrhcmt = 0; /* Indentation of previous Comment to the right
* of code (-1 -> don't check position) */
lineno = 0; /* Current line number */
ncomment = 0; /* Comment nesting level on this line */
bnest = 0; /* Brace nesting level on this line */
dnest = 0; /* Data declaration nesting level on this line */
pnest = 0; /* Parenthesis nesting level on this line */
ppifnest = 0; /* #if nesting level on this line */
inasm = 0; /* > 0: Within #ifdef __ASSEMBLY__ */
comment_lineno = -1; /* Line on which the last comment was closed */
blank_lineno = -1; /* Line number of the last blank line */
noblank_lineno = -1; /* A blank line is not needed after this line */
lbrace_lineno = -1; /* Line number of last left brace */
rbrace_lineno = -1; /* Last line containing a right brace */
externc_lineno = -1; /* Last line where 'extern "C"' declared */
/* Process each line in the input stream */
while (fgets(line, LINE_SIZE, instream))
{
lineno++;
indent = 0;
prevbnest = bnest; /* Brace nesting level on the previous line */
prevdnest = dnest; /* Data declaration nesting level on the
* previous line */
prevncomment = ncomment; /* Comment nesting level on the previous line */
bstatm = false; /* True: This line is beginning of a
* statement */
bfor = false; /* REVISIT: Implies for() is all on one line */
/* If we are not in a comment, then this certainly is not a right-hand
* comment.
*/
prevrhcmt = rhcomment;
if (ncomment <= 0)
{
rhcomment = 0;
}
/* Check for a blank line */
for (n = 0; line[n] != '\n' && isspace((int)line[n]); n++)
{
}
if (line[n] == '\n')
{
if (n > 0)
{
ERROR("Blank line contains whitespace", lineno, 1);
}
if (lineno == 1)
{
ERROR("File begins with a blank line", 1, 1);
}
else if (lineno == blank_lineno + 1)
{
ERROR("Too many blank lines", lineno, 1);
}
else if (lineno == lbrace_lineno + 1)
{
ERROR("Blank line follows left brace", lineno, 1);
}
blank_lineno = lineno;
continue;
}
else /* This line is non-blank */
{
/* Check for a missing blank line after a comment */
if (lineno == comment_lineno + 1)
{
/* No blank line should be present if the current line contains
* a right brace, a pre-processor line, the start of another
* comment.
*
* REVISIT: Generates a false alarm if the current line is also
* a comment. Generally it is acceptable for one comment to
* follow another with no space separation.
*
* REVISIT: prevrhcmt is tested to case the preceding line
* contained comments to the right of the code. In such cases,
* the comments are normally aligned and do not follow normal
* indentation rules. However, this code will generate a false
* alarm if the comments are aligned to the right BUT the
* preceding line has no comment.
*/
if (line[n] != '}' && line[n] != '#' && prevrhcmt == 0)
{
ERROR("Missing blank line after comment", comment_lineno,
1);
}
}
/* Files must begin with a comment (the file header).
* REVISIT: Logically, this belongs in the STEP 2 operations
* below.
*/
if (lineno == 1 && (line[n] != '/' || line[n + 1] != '*'))
{
ERROR("Missing file header comment block", lineno, 1);
}
if (lineno == 2)
{
if (line[n] == '*' && line[n + 1] == '\n')
{
ERROR("Missing relative file path in file header", lineno,
n);
}
else if (isspace(line[n + 2]))
{
ERROR("Too many whitespaces before relative file path",
lineno, n);
}
else
{
const char *apps_dir = "apps/";
const size_t apps_len = strlen(apps_dir);
size_t offset;
#ifdef TOPDIR
/* TOPDIR macro contains the absolute path to the "nuttx"
* root directory. It should have been defined via Makefile
* and it is required to accurately evaluate the relative
* path contained in the file header. Otherwise, skip this
* verification.
*/
char *basedir = strstr(g_file_name, TOPDIR);
if (basedir != NULL)
{
/* Add 1 to the offset for the slash character */
offset = strlen(TOPDIR) + 1;
/* Duplicate the line from the beginning of the
* relative file path, removing the '\n' at the end of
* the string.
*/
char *line_dup = strndup(&line[n + 2],
strlen(&line[n + 2]) - 1);
if (strcmp(line_dup, basedir + offset) != 0)
{
ERROR("Relative file path does not match actual file",
lineno, n);
}
free(line_dup);
}
else if (strncmp(&line[n + 2], apps_dir, apps_len) != 0)
{
/* g_file_name neither belongs to "nuttx" repository
* nor begins with the root dir of the other
* repository (e.g. "apps/")
*/
ERROR("Path relative to repository other than \"nuttx\" "
"must begin with the root directory", lineno, n);
}
else
{
#endif
offset = 0;
if (strncmp(&line[n + 2], apps_dir, apps_len) == 0)
{
/* Input file belongs to the "apps" repository */
/* Calculate the offset to the first directory
* after the "apps/" folder.
*/
offset += apps_len;
}
/* Duplicate the line from the beginning of the
* relative file path, removing the '\n' at the end of
* the string.
*/
char *line_dup = strndup(&line[n + 2],
strlen(&line[n + 2]) - 1);
ssize_t base =
strlen(g_file_name) - strlen(&line_dup[offset]);
if (base < 0 ||
(base != 0 && g_file_name[base - 1] != '/') ||
strcmp(&g_file_name[base], &line_dup[offset]) != 0)
{
ERROR("Relative file path does not match actual file",
lineno, n);
}
free(line_dup);
#ifdef TOPDIR
}
#endif
}
}
/* Check for a blank line following a right brace */
if (bfunctions && lineno == rbrace_lineno + 1)
{
/* Check if this line contains a right brace. A right brace
* must be followed by 'else', 'while', 'break', a blank line,
* another right brace, or a pre-processor directive like #endif
*/
if (dnest == 0 &&
strchr(line, '}') == NULL && line[n] != '#' &&
strncmp(&line[n], "else", 4) != 0 &&
strncmp(&line[n], "while", 5) != 0 &&
strncmp(&line[n], "break", 5) != 0)
{
ERROR("Right brace must be followed by a blank line",
rbrace_lineno, n + 1);
}
/* If the right brace is followed by a pre-processor command
* like #endif (but not #else or #elif), then set the right
* brace line number to the line number of the pre-processor
* command (it then must be followed by a blank line)
*/
if (line[n] == '#')
{
int ii;
for (ii = n + 1; line[ii] != '\0' && isspace(line[ii]); ii++)
{
}
if (strncmp(&line[ii], "else", 4) != 0 &&
strncmp(&line[ii], "elif", 4) != 0)
{
rbrace_lineno = lineno;
}
}
}
}
/* STEP 1: Find the indentation level and the start of real stuff on
* the line.
*/
for (n = 0; line[n] != '\n' && isspace((int)line[n]); n++)
{
switch (line[n])
{
case ' ':
{
indent++;
}
break;
case '\t':
{
if (!btabs)
{
ERROR("TABs found. First detected", lineno, n);
btabs = true;
}
indent = (indent + 4) & ~3;
}
break;
case '\r':
{
if (!bcrs)
{
ERROR("Carriage returns found. "
"First detected", lineno, n);
bcrs = true;
}
}
break;
default:
{
snprintf(buffer, sizeof(buffer),
"Unexpected white space character %02x found",
line[n]);
ERROR(buffer, lineno, n);
}
break;
}
}
/* STEP 2: Detect some certain start of line conditions */
/* Skip over pre-processor lines (or continuations of pre-processor
* lines as indicated by ppline)
*/
if (line[indent] == '#' || ppline != PPLINE_NONE)
{
int len;
int ii;
/* Suppress error for comment following conditional compilation */
noblank_lineno = lineno;
/* Check pre-processor commands if this is not a continuation
* line.
*/
ii = indent + 1;
if (ppline == PPLINE_NONE)
{
/* Skip to the pre-processor command following the '#' */
while (line[ii] != '\0' && isspace(line[ii]))
{
ii++;
}
if (line[ii] != '\0')
{
/* Make sure that pre-processor definitions are all in
* the pre-processor definitions section.
*/
ppline = PPLINE_OTHER;
if (strncmp(&line[ii], "define", 6) == 0)
{
ppline = PPLINE_DEFINE;
if (g_section != PRE_PROCESSOR_DEFINITIONS)
{
/* A complication is the header files always have
* the idempotence guard definitions before the
* "Pre-processor Definitions section".
*/
if (g_section == NO_SECTION &&
g_file_type != C_HEADER)
{
/* Only a warning because there is some usage
* of define outside the Pre-processor
* Definitions section which is justifiable.
* Should be manually checked.
*/
WARN("#define outside of 'Pre-processor "
"Definitions' section",
lineno, ii);
}
}
}
/* Make sure that files are included only in the Included
* Files section.
*/
else if (strncmp(&line[ii], "include", 7) == 0)
{
if (g_section != INCLUDED_FILES)
{
/* Only a warning because there is some usage of
* include outside the Included Files section
* which may be is justifiable. Should be
* manually checked.
*/
WARN("#include outside of 'Included Files' "
"section",
lineno, ii);
}
}
else if (strncmp(&line[ii], "if", 2) == 0)
{
ppifnest++;
ppline = PPLINE_IF;
ii += 2;
}
else if (strncmp(&line[ii], "elif", 4) == 0)
{
if (ppifnest == inasm)
{
inasm = 0;
}
ppline = PPLINE_ELIF;
ii += 4;
}
else if (strncmp(&line[ii], "else", 4) == 0)
{
if (ppifnest == inasm)
{
inasm = 0;
}
ppline = PPLINE_ELSE;
}
else if (strncmp(&line[ii], "endif", 4) == 0)
{
if (ppifnest == inasm)
{
inasm = 0;
}
ppifnest--;
ppline = PPLINE_ENDIF;
}
}
}
if (ppline == PPLINE_IF || ppline == PPLINE_ELIF)
{
int bdef = 0;
if (strncmp(&line[ii], "def", 3) == 0)
{
bdef = 1;
ii += 3;
}
else
{
while (line[ii] != '\0' && isspace(line[ii]))
{
ii++;
}
if (strncmp(&line[ii], "defined", 7) == 0)
{
bdef = 1;
ii += 7;
}
}
if (bdef)
{
while (line[ii] != '\0' &&
(isspace(line[ii]) || line[ii] == '('))
{
ii++;
}
if (strncmp(&line[ii], "__ASSEMBLY__", 12) == 0)
{
inasm = ppifnest;
}
}
}
/* Check if the next line will be a continuation of the pre-
* processor command.
*/
len = strlen(&line[indent]) + indent - 1;
if (line[len] == '\n')
{
len--;
}
/* Propagate rhcomment over preprocessor lines Issue #120 */
if (prevrhcmt != 0)
{
/* Don't check position */
rhcomment = -1;
}
lptr = strstr(line, "/*");
if (lptr != NULL)
{
n = lptr - &line[0];
if (line[n + 2] == '\n')
{
ERROR("C comment opening on separate line", lineno, n);
}
else if (!isspace((int)line[n + 2]) && line[n + 2] != '*')
{
ERROR("Missing space after opening C comment", lineno, n);
}
if (strstr(lptr, "*/") == NULL)
{
/* Increment the count of nested comments */
ncomment++;
}
if (ppline == PPLINE_DEFINE)
{
rhcomment = n;
if (prevrhcmt > 0 && n != prevrhcmt)
{
rhcomment = prevrhcmt;
WARN("Wrong column position of comment right of code",
lineno, n);
}
}
else
{
/* Signal rhcomment, but ignore position */
rhcomment = -1;
if (ncomment > 0 &&
(ppline == PPLINE_IF ||
ppline == PPLINE_ELSE ||
ppline == PPLINE_ELIF))
{
/* in #if... and #el... */
ERROR("No multiline comment right of code allowed here",
lineno, n);
}
}
}
if (line[len] != '\\' || ncomment > 0)
{
ppline = PPLINE_NONE;
}
continue;
}
/* Check for a single line comment */
linelen = strlen(line);
if (linelen >= 5) /* Minimum is slash, star, star, slash, newline */
{
lptr = strstr(line, "*/");
if (line[indent] == '/' && line[indent + 1] == '*' &&
lptr - line == linelen - 3)
{
/* If preceding comments were to the right of code, then we can
* assume that there is a columnar alignment of columns that do
* no follow the usual alignment. So the rhcomment flag
* should propagate.
*/
rhcomment = prevrhcmt;
/* Check if there should be a blank line before the comment */
if (lineno > 1 &&
comment_lineno != lineno - 1 &&
blank_lineno != lineno - 1 &&
noblank_lineno != lineno - 1 &&
rhcomment == 0)
{
/* TODO: This generates a false alarm if preceded
* by a label.
*/
ERROR("Missing blank line before comment found", lineno, 1);
}
/* 'comment_lineno 'holds the line number of the last closing
* comment. It is used only to verify that the comment is
* followed by a blank line.
*/
comment_lineno = lineno;
}
}
/* Check for the comment block indicating the beginning of a new file
* section.
*/
if (check_section_header(line, lineno))
{
if (g_section == PRIVATE_FUNCTIONS || g_section == PUBLIC_FUNCTIONS)
{
bfunctions = true; /* Latched */
}
}
/* Check for some kind of declaration.
* REVISIT: The following logic fails for any non-standard types.
* REVISIT: Terminator after keyword might not be a space. Might be
* a newline, for example. struct and unions are often unnamed, for
* example.
*/
else if (inasm == 0)
{
if (strncmp(&line[indent], "auto ", 5) == 0 ||
strncmp(&line[indent], "bool ", 5) == 0 ||
strncmp(&line[indent], "char ", 5) == 0 ||
strncmp(&line[indent], "CODE ", 5) == 0 ||
strncmp(&line[indent], "const ", 6) == 0 ||
strncmp(&line[indent], "double ", 7) == 0 ||
strncmp(&line[indent], "struct ", 7) == 0 ||
strncmp(&line[indent], "struct\n", 7) == 0 || /* May be unnamed */
strncmp(&line[indent], "enum ", 5) == 0 ||
strncmp(&line[indent], "extern ", 7) == 0 ||
strncmp(&line[indent], "EXTERN ", 7) == 0 ||
strncmp(&line[indent], "FAR ", 4) == 0 ||
strncmp(&line[indent], "float ", 6) == 0 ||
strncmp(&line[indent], "int ", 4) == 0 ||
strncmp(&line[indent], "int16_t ", 8) == 0 ||
strncmp(&line[indent], "int32_t ", 8) == 0 ||
strncmp(&line[indent], "long ", 5) == 0 ||
strncmp(&line[indent], "off_t ", 6) == 0 ||
strncmp(&line[indent], "register ", 9) == 0 ||
strncmp(&line[indent], "short ", 6) == 0 ||
strncmp(&line[indent], "signed ", 7) == 0 ||
strncmp(&line[indent], "size_t ", 7) == 0 ||
strncmp(&line[indent], "ssize_t ", 8) == 0 ||
strncmp(&line[indent], "static ", 7) == 0 ||
strncmp(&line[indent], "time_t ", 7) == 0 ||
strncmp(&line[indent], "typedef ", 8) == 0 ||
strncmp(&line[indent], "uint8_t ", 8) == 0 ||
strncmp(&line[indent], "uint16_t ", 9) == 0 ||
strncmp(&line[indent], "uint32_t ", 9) == 0 ||
strncmp(&line[indent], "union ", 6) == 0 ||
strncmp(&line[indent], "union\n", 6) == 0 || /* May be unnamed */
strncmp(&line[indent], "unsigned ", 9) == 0 ||
strncmp(&line[indent], "void ", 5) == 0 ||
strncmp(&line[indent], "volatile ", 9) == 0)
{
/* Check if this is extern "C"; We don't typically indent
* following this.
*/
if (strncmp(&line[indent], "extern \"C\"", 10) == 0)
{
externc_lineno = lineno;
}
/* bfunctions: True: Processing private or public functions.
* bnest: Brace nesting level on this line
* dnest: Data declaration nesting level on this line
*/
/* REVISIT: Also picks up function return types */
/* REVISIT: Logic problem for nested data/function declarations */
if ((!bfunctions || bnest > 0) && dnest == 0)
{
dnest = 1;
}
/* Check for multiple definitions of variables on the line.
* Ignores declarations within parentheses which are probably
* formal parameters.
*/
if (pnest == 0)
{
int tmppnest;
/* Note, we have not yet parsed each character on the line so
* a comma have have been be preceded by '(' on the same line.
* We will have parse up to any comma to see if that is the
* case.
*/
for (i = indent, tmppnest = 0;
line[i] != '\n' && line[i] != '\0';
i++)
{
if (tmppnest == 0 && line[i] == ',')
{
ERROR("Multiple data definitions", lineno, i + 1);
break;
}
else if (line[i] == '(')
{
tmppnest++;
}
else if (line[i] == ')')
{
if (tmppnest < 1)
{
/* We should catch this later */
break;
}
tmppnest--;
}
else if (line[i] == ';')
{
/* Break out if the semicolon terminates the
* declaration is found. Avoids processing any
* righthand comments in most cases.
*/
break;
}
}
}
}
/* Check for a keyword indicating the beginning of a statement.
* REVISIT: This, obviously, will not detect statements that do not
* begin with a C keyword (such as assignment statements).
*/
else if (strncmp(&line[indent], "break ", 6) == 0 ||
strncmp(&line[indent], "case ", 5) == 0 ||
#if 0 /* Part of switch */
strncmp(&line[indent], "case ", 5) == 0 ||
#endif
strncmp(&line[indent], "continue ", 9) == 0 ||
#if 0 /* Part of switch */
strncmp(&line[indent], "default ", 8) == 0 ||
#endif
strncmp(&line[indent], "do ", 3) == 0 ||
strncmp(&line[indent], "else ", 5) == 0 ||
strncmp(&line[indent], "goto ", 5) == 0 ||
strncmp(&line[indent], "if ", 3) == 0 ||
strncmp(&line[indent], "return ", 7) == 0 ||
#if 0 /* Doesn't follow pattern */
strncmp(&line[indent], "switch ", 7) == 0 ||
#endif
strncmp(&line[indent], "while ", 6) == 0)
{
bstatm = true;
}
/* Spacing works a little differently for and switch statements */
else if (strncmp(&line[indent], "for ", 4) == 0)
{
bfor = true;
bstatm = true;
}
else if (strncmp(&line[indent], "switch ", 7) == 0)
{
bswitch = true;
}
/* Also check for C keywords with missing white space */
else if (strncmp(&line[indent], "do(", 3) == 0 ||
strncmp(&line[indent], "if(", 3) == 0 ||
strncmp(&line[indent], "while(", 6) == 0)
{
ERROR("Missing whitespace after keyword", lineno, n);
bstatm = true;
}
else if (strncmp(&line[indent], "for(", 4) == 0)
{
ERROR("Missing whitespace after keyword", lineno, n);
bfor = true;
bstatm = true;
}
else if (strncmp(&line[indent], "switch(", 7) == 0)
{
ERROR("Missing whitespace after keyword", lineno, n);
bswitch = true;
}
}
/* STEP 3: Parse each character on the line */
bquote = false; /* True: Backslash quoted character next */
bblank = true; /* Used to verify block comment terminator */
for (; line[n] != '\n' && line[n] != '\0'; n++)
{
/* Report any use of non-standard white space characters */
if (isspace(line[n]))
{
if (line[n] == '\t')
{
if (!btabs)
{
ERROR("TABs found. First detected", lineno, n);
btabs = true;
}
}
else if (line[n] == '\r')
{
if (!bcrs)
{
ERROR("Carriage returns found. "
"First detected", lineno, n);
bcrs = true;
}
}
else if (line[n] != ' ')
{
snprintf(buffer, sizeof(buffer),
"Unexpected white space character %02x found",
line[n]);
ERROR(buffer, lineno, n);
}
}
/* Skip over identifiers */
if (ncomment == 0 && !bstring && (line[n] == '_' || isalpha(line[n])))
{
bool have_upper = false;
bool have_lower = false;
int ident_index = n;
/* Parse over the identifier. Check if it contains mixed upper-
* and lower-case characters.
*/
do
{
have_upper |= isupper(line[n]);
/* The coding standard provides for some exceptions of lower
* case characters in pre-processor strings:
*
* IPv[4|6] as an IP version number
* ICMPv6 as an ICMP version number
* IGMPv2 as an IGMP version number
* [0-9]p[0-9] as a decimal point
* d[0-9] as a divisor
* Hz for frequencies (including KHz, MHz, etc.)
*/
if (!have_lower && islower(line[n]))
{
switch (line[n])
{
/* A sequence containing 'v' may occur at the
* beginning of the identifier.
*/
case 'v':
if (n > 1 &&
line[n - 2] == 'I' &&
line[n - 1] == 'P' &&
(line[n + 1] == '4' ||
line[n + 1] == '6'))
{
}
else if (n > 3 &&
line[n - 4] == 'I' &&
line[n - 3] == 'C' &&
line[n - 2] == 'M' &&
line[n - 1] == 'P' &&
line[n + 1] == '6')
{
}
else if (n > 3 &&
line[n - 4] == 'I' &&
line[n - 3] == 'G' &&
line[n - 2] == 'M' &&
line[n - 1] == 'P' &&
line[n + 1] == '2')
{
}
else
{
have_lower = true;
}
break;
/* Sequences containing 'p', 'd', or 'z' must have
* been preceded by upper case characters.
*/
case 'p':
if (!have_upper || n < 1 ||
!isdigit(line[n - 1]) ||
!isdigit(line[n + 1]))
{
have_lower = true;
}
break;
case 'd':
if (!have_upper || !isdigit(line[n + 1]))
{
have_lower = true;
}
break;
case 'z':
if (!have_upper || n < 1 ||
line[n - 1] != 'H')
{
have_lower = true;
}
break;
break;
default:
have_lower = true;
break;
}
}
n++;
}
while (line[n] == '_' || isalnum(line[n]));
/* Check for mixed upper and lower case */
if (have_upper && have_lower)
{
/* Ignore symbols that begin with white-listed prefixes */
if (white_list(&line[ident_index], lineno))
{
/* No error */
}
/* Special case hex constants. These will look like
* identifiers starting with 'x' or 'X' but preceded
* with '0'
*/
else if (ident_index < 1 ||
(line[ident_index] != 'x' &&
line[ident_index] != 'X') ||
line[ident_index - 1] != '0')
{
ERROR("Mixed case identifier found",
lineno, ident_index);
}
else if (have_upper)
{
ERROR("Upper case hex constant found",
lineno, ident_index);
}
}
/* Check if the identifier is the last thing on the line */
if (line[n] == '\n' || line[n] == '\0')
{
break;
}
}
/* Handle comments */
if (line[n] == '/' && !bstring)
{
/* Check for start of a C comment */
if (line[n + 1] == '*')
{
if (line[n + 2] == '\n')
{
ERROR("C comment opening on separate line", lineno, n);
}
else if (!isspace((int)line[n + 2]) && line[n + 2] != '*')
{
ERROR("Missing space after opening C comment", lineno, n);
}
/* Increment the count of nested comments */
ncomment++;
/* If there is anything to the left of the left brace, then
* this must be a comment to the right of code.
* Also if preceding comments were to the right of code, then
* we can assume that there is a columnar alignment of columns
* that do no follow the usual alignment. So the rhcomment
* flag should propagate.
*/
if (prevrhcmt == 0)
{
if (n != indent)
{
rhcomment = n;
}
}
else
{
rhcomment = n;
if (prevrhcmt > 0 && n != prevrhcmt)
{
rhcomment = prevrhcmt;
if (n != indent)
{
WARN("Wrong column position of "
"comment right of code", lineno, n);
}
else
{
ERROR("Wrong column position or missing "
"blank line before comment", lineno, n);
}
}
}
n++;
continue;
}
/* Check for end of a C comment */
else if (n > 0 && line[n - 1] == '*')
{
if (n < 2)
{
ERROR("Closing C comment not indented", lineno, n);
}
else if (!isspace((int)line[n - 2]) && line[n - 2] != '*')
{
ERROR("Missing space before closing C comment", lineno,
n);
}
/* Check for block comments that are not on a separate line.
* This would be the case if we are we are within a comment
* that did not start on this line and the current line is
* not blank up to the point where the comment was closed.
*/
if (prevncomment > 0 && !bblank && rhcomment == 0)
{
ERROR("Block comment terminator must be on a "
"separate line", lineno, n);
}
#if 0
/* REVISIT: Generates false alarms when portions of an
* expression are commented out within the expression.
*/
if (line[n + 1] != '\n')
{
ERROR("Garbage on line after C comment", lineno, n);
}
#endif
/* Handle nested comments */
if (ncomment > 0)
{
/* Remember the line number of the line containing the
* closing of the outermost comment.
*/
if (--ncomment == 0)
{
/* 'comment_lineno 'holds the line number of the
* last closing comment. It is used only to
* verify that the comment is followed by a blank
* line.
*/
comment_lineno = lineno;
/* Note that rhcomment must persist to support a
* later test for comment alignment. We will fix
* that at the top of the loop when ncomment == 0.
*/
}
}
else
{
/* Note that rhcomment must persist to support a later
* test for comment alignment. We will will fix that
* at the top of the loop when ncomment == 0.
*/
ncomment = 0;
ERROR("Closing without opening comment", lineno, n);
}
n++;
continue;
}
/* Check for C++ style comments */
else if (line[n + 1] == '/')
{
/* Check for URI schemes, e.g. "http://" or "https://" */
if ((ncomment == 0) &&
(n == 0 || strncmp(&line[n - 1], "://", 3) != 0))
{
ERROR("C++ style comment", lineno, n);
n++;
continue;
}
}
}
/* Check if the line is blank so far. This is only used to
* to verify the the closing of a block comment is on a separate
* line. So we also need to treat '*' as a 'blank'.
*/
if (!isblank(line[n]) && line[n] != '*')
{
bblank = false;
}
/* Check for a string... ignore if we are in the middle of a
* comment.
*/
if (ncomment == 0)
{
/* Backslash quoted character */
if (line[n] == '\\')
{
bquote = true;
n++;
}
/* Check for quoted characters: \" in string */
if (line[n] == '"' && !bquote)
{
bstring = !bstring;
}
bquote = false;
}
/* The rest of the line is only examined of we are not in a comment,
* in a string or in assembly.
*
* REVISIT: Should still check for whitespace at the end of the
* line.
*/
if (ncomment == 0 && !bstring && inasm == 0)
{
switch (line[n])
{
/* Handle logic nested with curly braces */
case '{':
{
if (n > indent)
{
/* REVISIT: dnest is always > 0 here if bfunctions ==
* false.
*/
if (dnest == 0 || !bfunctions || lineno == rbrace_lineno)
{
ERROR("Left bracket not on separate line", lineno,
n);
}
}
else if (line[n + 1] != '\n')
{
if (dnest == 0)
{
ERROR("Garbage follows left bracket", lineno, n);
}
}
bnest++;
if (dnest > 0)
{
dnest++;
}
/* Check if we are within 'extern "C"', we don't
* normally indent in that case because the 'extern "C"'
* is conditioned on __cplusplus.
*/
if (lineno == externc_lineno ||
lineno - 1 == externc_lineno)
{
bexternc = true;
}
/* Suppress error for comment following a left brace */
noblank_lineno = lineno;
lbrace_lineno = lineno;
}
break;
case '}':
{
/* Decrement the brace nesting level */
if (bnest < 1)
{
ERROR("Unmatched right brace", lineno, n);
}
else
{
bnest--;
if (bnest < 1)
{
bnest = 0;
bswitch = false;
}
}
/* Decrement the declaration nesting level */
if (dnest < 3)
{
dnest = 0;
bexternc = false;
}
else
{
dnest--;
}
/* The right brace should be on a separate line */
if (n > indent)
{
if (dnest == 0)
{
ERROR("Right bracket not on separate line",
lineno, n);
}
}
/* Check for garbage following the left brace */
if (line[n + 1] != '\n' &&
line[n + 1] != ',' &&
line[n + 1] != ';')
{
int sndx = n + 1;
bool whitespace = false;
/* Skip over spaces */
while (line[sndx] == ' ')
{
sndx++;
}
/* One possibility is that the right bracket is
* followed by an identifier then a semi-colon.
* Comma is possible to but would be a case of
* multiple declaration of multiple instances.
*/
if (line[sndx] == '_' || isalpha(line[sndx]))
{
int endx = sndx;
/* Skip to the end of the identifier. Checking
* for mixed case identifiers will be done
* elsewhere.
*/
while (line[endx] == '_' ||
isalnum(line[endx]))
{
endx++;
}
/* Skip over spaces */
while (line[endx] == ' ')
{
whitespace = true;
endx++;
}
/* Handle according to what comes after the
* identifier.
*/
if (strncmp(&line[sndx], "while", 5) == 0)
{
ERROR("'while' must be on a separate line",
lineno, sndx);
}
else if (line[endx] == ',')
{
ERROR("Multiple data definitions on line",
lineno, endx);
}
else if (line[endx] == ';')
{
if (whitespace)
{
ERROR("Space precedes semi-colon",
lineno, endx);
}
}
else if (line[endx] == '=')
{
/* There's a struct initialization following */
check_spaces_leftright(line, lineno, endx, endx);
dnest = 1;
}
else
{
ERROR("Garbage follows right bracket",
lineno, n);
}
}
else
{
ERROR("Garbage follows right bracket", lineno, n);
}
}
/* The right brace should not be preceded with a a blank
* line.
*/
if (lineno == blank_lineno + 1)
{
ERROR("Blank line precedes right brace at line",
lineno, 1);
}
rbrace_lineno = lineno;
}
break;
/* Handle logic with parentheses */
case '(':
{
/* Increase the parenthetical nesting level */
pnest++;
/* Check for inappropriate space around parentheses */
if (line[n + 1] == ' ') /* && !bfor */
{
ERROR("Space follows left parenthesis", lineno, n);
}
}
break;
case ')':
{
/* Decrease the parenthetical nesting level */
if (pnest < 1)
{
ERROR("Unmatched right parentheses", lineno, n);
pnest = 0;
}
else
{
pnest--;
}
/* Allow ')' as first thing on the line (n == indent)
* Allow "for (xx; xx; )" (bfor == true)
*/
if (n > 0 && n != indent && line[n - 1] == ' ' && !bfor)
{
ERROR("Space precedes right parenthesis", lineno, n);
}
}
break;
/* Check for inappropriate space around square brackets */
case '[':
{
if (line[n + 1] == ' ')
{
ERROR("Space follows left bracket", lineno, n);
}
}
break;
case ']':
{
if (n > 0 && line[n - 1] == ' ')
{
ERROR("Space precedes right bracket", lineno, n);
}
}
break;
/* Semi-colon may terminate a declaration */
case ';':
{
if (!isspace((int)line[n + 1]))
{
ERROR("Missing whitespace after semicolon", lineno, n);
}
/* Semicolon terminates a declaration/definition if there
* was no left curly brace (i.e., dnest is only 1).
*/
if (dnest == 1)
{
dnest = 0;
}
}
break;
/* Semi-colon may terminate a declaration */
case ',':
{
if (!isspace((int)line[n + 1]))
{
ERROR("Missing whitespace after comma", lineno, n);
}
}
break;
/* Skip over character constants */
case '\'':
{
int endndx = n + 2;
if (line[n + 1] != '\n' && line[n + 1] != '\0')
{
if (line[n + 1] == '\\')
{
for (;
line[endndx] != '\n' &&
line[endndx] != '\0' &&
line[endndx] != '\'';
endndx++);
}
n = endndx;
}
}
break;
/* Check for space around various operators */
case '-':
/* -> */
if (line[n + 1] == '>')
{
/* -> must have no whitespaces on its left or right */
check_nospaces_leftright(line, lineno, n, n + 1);
n++;
}
/* -- */
else if (line[n + 1] == '-')
{
/* "--" should be next to its operand. If there are
* whitespaces or non-operand characters on both left
* and right (e.g. "a -- ", “a[i --]”, "(-- i)"),
* there's an error.
*/
check_operand_leftright(line, lineno, n, n + 1);
n++;
}
/* -= */
else if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
/* Scientific notation with a negative exponent (eg. 10e-10)
* REVISIT: This fails for cases where the variable name
* ends with 'e' preceded by a digit:
* a = abc1e-10;
* a = ABC1E-10;
*/
else if ((line[n - 1] == 'e' || line[n - 1] == 'E') &&
isdigit(line[n + 1]) && isdigit(line[n - 2]))
{
n++;
}
else
{
/* '-' may function as a unary operator and snuggle
* on the left.
*/
check_spaces_left(line, lineno, n);
}
break;
case '+':
/* ++ */
if (line[n + 1] == '+')
{
/* "++" should be next to its operand. If there are
* whitespaces or non-operand characters on both left
* and right (e.g. "a ++ ", “a[i ++]”, "(++ i)"),
* there's an error.
*/
check_operand_leftright(line, lineno, n, n + 1);
n++;
}
/* += */
else if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
/* '+' may function as a unary operator and snuggle
* on the left.
*/
check_spaces_left(line, lineno, n);
}
break;
case '&':
/* &<variable> OR &(<expression>) */
if (isalpha((int)line[n + 1]) || line[n + 1] == '_' ||
line[n + 1] == '(')
{
}
/* &&, &= */
else if (line[n + 1] == '=' || line[n + 1] == '&')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '/':
/* C comment terminator */
if (line[n - 1] == '*')
{
n++;
}
/* C++-style comment */
else if (line[n + 1] == '/')
{
/* Check for "http://" or "https://" */
if ((n < 5 || strncmp(&line[n - 5], "http://", 7) != 0) &&
(n < 6 || strncmp(&line[n - 6], "https://", 8) != 0))
{
ERROR("C++ style comment on at %d:%d\n",
lineno, n);
}
n++;
}
/* /= */
else if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
/* Division operator */
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '*':
/* *\/, ** */
if (line[n] == '*' &&
(line[n + 1] == '/' ||
line[n + 1] == '*'))
{
n++;
break;
}
/* *<variable>, *(<expression>) */
else if (isalpha((int)line[n + 1]) ||
line[n + 1] == '_' ||
line[n + 1] == '(')
{
break;
}
/* (<type> *) */
else if (line[n + 1] == ')')
{
/* REVISIT: This gives false alarms on syntax like *--ptr */
if (line[n - 1] != ' ' && line[n - 1] != '(')
{
ERROR("Operator/assignment must be preceded "
"with whitespace", lineno, n);
}
break;
}
/* *= */
else if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
/* A single '*' may be an binary operator, but
* it could also be a unary operator when used to deference
* a pointer.
*/
check_spaces_left(line, lineno, n);
}
break;
case '%':
/* %= */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '<':
/* <=, <<, <<= */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else if (line[n + 1] == '<')
{
if (line[n + 2] == '=')
{
check_spaces_leftright(line, lineno, n, n + 2);
n += 2;
}
else
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '>':
/* >=, >>, >>= */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else if (line[n + 1] == '>')
{
if (line[n + 2] == '=')
{
check_spaces_leftright(line, lineno, n, n + 2);
n += 2;
}
else
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '|':
/* |=, || */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else if (line[n + 1] == '|')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '^':
/* ^= */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '=':
/* == */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '~':
check_spaces_left(line, lineno, n);
break;
case '!':
/* != */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
/* !! */
else if (line[n + 1] == '!')
{
check_spaces_left(line, lineno, n);
n++;
}
else
{
check_spaces_left(line, lineno, n);
}
break;
default:
break;
}
}
}
/* Loop terminates when NUL or newline character found */
if (line[n] == '\n' || line[n] == '\0')
{
/* If the parse terminated on the NULL, then back up to the last
* character (which should be the newline).
*/
int m = n;
if (line[m] == '\0' && m > 0)
{
m--;
}
/* Check for space at the end of the line. Except for carriage
* returns which we have already reported (one time) above.
*/
if (m > 1 && isspace((int)line[m - 1]) &&
line[m - 1] != '\n' && line[m - 1] != '\r')
{
ERROR("Dangling whitespace at the end of line", lineno, m);
}
/* The line width is determined by the location of the final
* asterisk in block comments. The closing line of the block
* comment will exceed that by one one character, the '/'
* following the final asterisk.
*/
else if (m > g_maxline)
{
bool bslash;
int a;
for (bslash = false, a = m;
a > 2 && strchr("\n\r/", line[a]) != NULL;
a--)
{
if (line[a] == '/')
{
bslash = true;
}
}
if (bslash && line[a] == '*')
{
m = a + 1;
}
}
/* Check for long lines
*
* REVISIT: Long line checks suppressed on right hand comments
* for now. This just prevents a large number of difficult-to-
* fix complaints that we would have otherwise.
*/
if (m > g_maxline && !rhcomment)
{
ERROR("Long line found", lineno, m);
}
}
/* STEP 4: Check alignment */
/* Within a comment block, we need only check on the alignment of the
* comment.
*/
if ((ncomment > 0 || prevncomment > 0) && !bstring)
{
/* Nothing should begin in comment zero */
if (indent == 0 && line[0] != '/' && !bexternc)
{
/* NOTE: if this line contains a comment to the right of the
* code, then ncomment will be misleading because it was
* already incremented above.
*/
if (ncomment > 1 || rhcomment == 0)
{
ERROR("No indentation line", lineno, indent);
}
}
else if (indent == 1 && line[0] == ' ' && line[1] == '*')
{
/* Good indentation */
}
else if (indent > 0 && line[indent] == '\n')
{
ERROR("Whitespace on blank line", lineno, indent);
}
else if (indent > 0 && indent < 2)
{
if (bnest > 0)
{
ERROR("Insufficient indentation", lineno, indent);
}
else
{
ERROR("Expected indentation line", lineno, indent);
}
}
else if (indent > 0 && !bswitch)
{
if (line[indent] == '/')
{
/* Comments should like at offsets 2, 6, 10, ...
* This rule is not followed, however, if the comments are
* aligned to the right of the code.
*/
if ((indent & 3) != 2 && rhcomment == 0)
{
ERROR("Bad comment alignment", lineno, indent);
}
/* REVISIT: This screws up in cases where there is C code,
* followed by a comment that continues on the next line.
*/
else if (line[indent + 1] != '*')
{
ERROR("Missing asterisk in comment", lineno, indent);
}
}
else if (line[indent] == '*')
{
/* REVISIT: Generates false alarms on comments at the end of
* the line if there is nothing preceding (such as the aligned
* comments with a structure field definition). So disabled
* for comments before beginning of function definitions.
*
* Suppress this error if this is a comment to the right of
* code.
* Those may be unaligned.
*/
if ((indent & 3) != 3 && bfunctions && dnest == 0 &&
rhcomment == 0)
{
ERROR("Bad comment block alignment", lineno, indent);
}
if (line[indent + 1] != ' ' &&
line[indent + 1] != '*' &&
line[indent + 1] != '\n' &&
line[indent + 1] != '/')
{
ERROR("Invalid character after asterisk "
"in comment block", lineno, indent);
}
}
/* If this is not the line containing the comment start, then this
* line should begin with '*'
*/
else if (prevncomment > 0)
{
ERROR("Missing asterisk in comment block", lineno, indent);
}
}
}
/* Check for various alignment outside of the comment block */
else if ((ncomment == 0 && prevncomment == 0) && !bstring)
{
if (indent == 0 && strchr("\n#{}", line[0]) == NULL)
{
/* Ignore if we are at global scope */
if (prevbnest > 0)
{
bool blabel = false;
if (isalpha((int)line[indent]))
{
for (i = indent + 1; isalnum((int)line[i]) ||
line[i] == '_'; i++);
blabel = (line[i] == ':');
}
if (!blabel && !bexternc)
{
ERROR("No indentation line", lineno, indent);
}
}
}
else if (indent == 1 && line[0] == ' ' && line[1] == '*')
{
/* Good indentation */
}
else if (indent > 0 && line[indent] == '\n')
{
ERROR("Whitespace on blank line", lineno, indent);
}
else if (indent > 0 && indent < 2)
{
ERROR("Insufficient indentation line", lineno, indent);
}
else if (line[indent] == '{')
{
/* Check for left brace in first column, but preceded by a
* blank line. Should never happen (but could happen with
* internal compound statements).
*/
if (indent == 0 && lineno == blank_lineno + 1)
{
ERROR("Blank line before opening left brace", lineno, indent);
}
/* REVISIT: Possible false alarms in compound statements
* without a preceding conditional. That usage often violates
* the coding standard.
*/
else if (!bfunctions && (indent & 1) != 0)
{
ERROR("Bad left brace alignment", lineno, indent);
}
else if ((indent & 3) != 0 && !bswitch && dnest == 0)
{
ERROR("Bad left brace alignment", lineno, indent);
}
}
else if (line[indent] == '}')
{
/* REVISIT: Possible false alarms in compound statements
* without a preceding conditional. That usage often violates
* the coding standard.
*/
if (!bfunctions && (indent & 1) != 0)
{
ERROR("Bad left brace alignment", lineno, indent);
}
else if ((indent & 3) != 0 && !bswitch && prevdnest == 0)
{
ERROR("Bad right brace alignment", lineno, indent);
}
}
else if (indent > 0)
{
/* REVISIT: Generates false alarms when a statement continues on
* the next line. The bstatm check limits to lines beginning
* with C keywords.
* REVISIT: The bstatm check will not detect statements that
* do not begin with a C keyword (such as assignment statements).
* REVISIT: Generates false alarms on comments at the end of
* the line if there is nothing preceding (such as the aligned
* comments with a structure field definition). So disabled for
* comments before beginning of function definitions.
*/
if ((bstatm || /* Begins with C keyword */
(line[indent] == '/' &&
bfunctions &&
line[indent + 1] == '*')) && /* Comment in functions */
!bswitch && /* Not in a switch */
dnest == 0) /* Not a data definition */
{
if ((indent & 3) != 2)
{
ERROR("Bad alignment", lineno, indent);
}
}
/* Crazy cases. There should be no small odd alignments
* outside of comment/string. Odd alignments are possible
* on continued lines, but not if they are small.
*/
else if (indent == 1 || indent == 3)
{
ERROR("Small odd alignment", lineno, indent);
}
}
}
}
if (!bfunctions && g_file_type == C_SOURCE)
{
ERROR("\"Private/Public Functions\" not found!"
" File will not be checked", lineno, 1);
}
if (ncomment > 0 || bstring)
{
ERROR("Comment or string found at end of file", lineno, 1);
}
fclose(instream);
if (g_verbose == 1)
{
fprintf(stderr, "%s: %s nxstyle check\n", g_file_name,
g_status == 0 ? "PASSED" : "FAILED");
}
return g_status;
}
|
the_stack_data/243893492.c | int c = -1;
foo (p)
int *p;
{
int x;
int a;
a = p[0];
x = a + 5;
a = c;
p[0] = x - 15;
return a;
}
int main()
{
int b = 1;
int a = foo(&b);
if (a != -1 || b != (1 + 5 - 15))
abort ();
exit (0);
}
|
the_stack_data/1261669.c | #include <stdio.h>
int main(int argc, char const *argv[])
{
int count = 10;
int *int_pointer;
int_pointer = &count;
int x = *int_pointer;
printf("*int_pointer = %i x = %i",*int_pointer, x);
return 0;
}
|
the_stack_data/34474.c | /**
@Generated PIC10 / PIC12 / PIC16 / PIC18 MCUs Source File
@Company:
Microchip Technology Inc.
@File Name:
mcc.c
@Summary:
This is the device_config.c file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs
@Description:
This header file provides implementations for driver APIs for all modules selected in the GUI.
Generation Information :
Product Revision : PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.81.7
Device : PIC18F47Q43
Driver Version : 2.00
The generated drivers are tested against the following:
Compiler : XC8 2.31 and above or later
MPLAB : MPLAB X 5.45
*/
/*
(c) 2018 Microchip Technology Inc. and its subsidiaries.
Subject to your compliance with these terms, you may use Microchip software and any
derivatives exclusively with Microchip products. It is your responsibility to comply with third party
license terms applicable to your use of third party software (including open source software) that
may accompany Microchip software.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY
IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS
FOR A PARTICULAR PURPOSE.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP
HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO
THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL
CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT
OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS
SOFTWARE.
*/
// Configuration bits: selected in the GUI
// CONFIG1
#pragma config FEXTOSC = OFF // External Oscillator Selection->Oscillator not enabled
#pragma config RSTOSC = HFINTOSC_64MHZ // Reset Oscillator Selection->HFINTOSC with HFFRQ = 64 MHz and CDIV = 1:1
// CONFIG2
#pragma config CLKOUTEN = OFF // Clock out Enable bit->CLKOUT function is disabled
#pragma config PR1WAY = ON // PRLOCKED One-Way Set Enable bit->PRLOCKED bit can be cleared and set only once
#pragma config CSWEN = ON // Clock Switch Enable bit->Writing to NOSC and NDIV is allowed
#pragma config FCMEN = ON // Fail-Safe Clock Monitor Enable bit->Fail-Safe Clock Monitor enabled
// CONFIG3
#pragma config MCLRE = EXTMCLR // MCLR Enable bit->If LVP = 0, MCLR pin is MCLR; If LVP = 1, RE3 pin function is MCLR
#pragma config PWRTS = PWRT_OFF // Power-up timer selection bits->PWRT is disabled
#pragma config MVECEN = ON // Multi-vector enable bit->Multi-vector enabled, Vector table used for interrupts
#pragma config IVT1WAY = ON // IVTLOCK bit One-way set enable bit->IVTLOCKED bit can be cleared and set only once
#pragma config LPBOREN = OFF // Low Power BOR Enable bit->Low-Power BOR disabled
#pragma config BOREN = SBORDIS // Brown-out Reset Enable bits->Brown-out Reset enabled , SBOREN bit is ignored
// CONFIG4
#pragma config BORV = VBOR_1P9 // Brown-out Reset Voltage Selection bits->Brown-out Reset Voltage (VBOR) set to 1.9V
#pragma config ZCD = OFF // ZCD Disable bit->ZCD module is disabled. ZCD can be enabled by setting the ZCDSEN bit of ZCDCON
#pragma config PPS1WAY = ON // PPSLOCK bit One-Way Set Enable bit->PPSLOCKED bit can be cleared and set only once; PPS registers remain locked after one clear/set cycle
#pragma config STVREN = ON // Stack Full/Underflow Reset Enable bit->Stack full/underflow will cause Reset
#pragma config LVP = ON // Low Voltage Programming Enable bit->Low voltage programming enabled. MCLR/VPP pin function is MCLR. MCLRE configuration bit is ignored
#pragma config XINST = OFF // Extended Instruction Set Enable bit->Extended Instruction Set and Indexed Addressing Mode disabled
// CONFIG5
#pragma config WDTCPS = WDTCPS_31 // WDT Period selection bits->Divider ratio 1:65536; software control of WDTPS
#pragma config WDTE = OFF // WDT operating mode->WDT Disabled; SWDTEN is ignored
// CONFIG6
#pragma config WDTCWS = WDTCWS_7 // WDT Window Select bits->window always open (100%); software control; keyed access not required
#pragma config WDTCCS = SC // WDT input clock selector->Software Control
// CONFIG7
#pragma config BBSIZE = BBSIZE_512 // Boot Block Size selection bits->Boot Block size is 512 words
#pragma config BBEN = OFF // Boot Block enable bit->Boot block disabled
#pragma config SAFEN = OFF // Storage Area Flash enable bit->SAF disabled
#pragma config DEBUG = OFF // Background Debugger->Background Debugger disabled
// CONFIG8
#pragma config WRTB = OFF // Boot Block Write Protection bit->Boot Block not Write protected
#pragma config WRTC = OFF // Configuration Register Write Protection bit->Configuration registers not Write protected
#pragma config WRTD = OFF // Data EEPROM Write Protection bit->Data EEPROM not Write protected
#pragma config WRTSAF = OFF // SAF Write protection bit->SAF not Write Protected
#pragma config WRTAPP = OFF // Application Block write protection bit->Application Block not write protected
// CONFIG10
#pragma config CP = OFF // PFM and Data EEPROM Code Protection bit->PFM and Data EEPROM code protection disabled
|
the_stack_data/13332.c | #include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
int nanosleep(const struct timespec *req, struct timespec *rem) {
return syscall(SYS_nanosleep, req, rem);
}
unsigned sleep(unsigned seconds) {
struct timespec ts = {
.tv_sec = seconds,
.tv_nsec = 0
};
if (nanosleep(&ts, &ts))
return ts.tv_sec;
return 0;
}
|
the_stack_data/97011739.c | #include <stdio.h>
int foo;
int main() {
printf("foo is: %d\n", foo);
return 0;
}
|
the_stack_data/87638399.c | #include<stdio.h>
#define MAX(m,n) (m>n)?m:n
int main()
{
int i,j,max;
printf("请输入两个整数i和j:\n");
scanf("%d %d",&i,&j);
max = MAX(i,j);
printf("max=%d\n",max);
return 0;
}
|
the_stack_data/68886932.c | #include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node* next;
}node;
node* append(node* head,int d){
node *temp=NULL;
temp=(node *)malloc(sizeof(node));
temp->data=d;
temp->next=NULL;
if(head==NULL){
head=temp;
return head;
}
temp->next=head;
return temp;
}
void printReverse(node* head){
if (head->next==NULL)
return;
printReverse(head->next);
printf("%d ", head->data);
}
int main(void) {
int n,i,j;
scanf("%d",&n);
int a[n],lis[n];
for(i=0;i<n;i++){
scanf("%d",&a[i]);
lis[i]=1;
}
node *head[n];
for(i=0;i<n;i++){
head[i]=NULL;
head[i]=(node *)malloc(sizeof(node));
head[i]=append(head[i],a[i]);
}
for(i=1;i<n;i++){
for(j=0;j<i;j++){
if(a[i]>a[j] && lis[i]<lis[j]+1){
lis[i]=lis[j]+1;
head[i]=append(head[j],a[i]);
}
}
}
int max=0,index=0;
for (i=0;i<n;i++){
if (max<lis[i]){
max=lis[i];
index=i;
}
}
// printf("%d %d\n",max,index);
printReverse(head[index]);
printf("\n");
return 0;
} |
the_stack_data/455052.c | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB 1996-2009. All Rights Reserved.
*
* The contents of this file are subject to the Erlang Public License,
* Version 1.1, (the "License"); you may not use this file except in
* compliance with the License. You should have received a copy of the
* Erlang Public License along with this software. If not, it can be
* retrieved online at http://www.erlang.org/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* %CopyrightEnd%
*/
/*
* Makes the file erl_version.h.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
int
main(argc, argv)
int argc;
char** argv;
{
FILE *file;
time_t now;
char *cnow;
if (argc != 2) {
fprintf(stderr, "usage: mkver version\n");
exit(1);
}
if ((file = fopen("erl_version.h", "wb")) == NULL) {
fprintf(stderr, "Could not create file 'erl_version.h'!\n");
exit(1);
}
time(&now);
cnow = ctime(&now);
cnow[24] = '\0'; /* tidelipom */
fprintf(file, "/* This file was created by mkver -- don't modify.*/\n");
fprintf(file, "#define ERLANG_VERSION \"%s\"\n", argv[1]);
fprintf(file, "#define ERLANG_COMPILE_DATE \"%s\"\n", cnow);
fclose(file);
exit(0);
return 0;
}
|
the_stack_data/632546.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
void do_what_a_child_will_do(char* a) {
fprintf(stdout, "%s[%d]: Hi mother!\n", a, (int)getpid());
exit(EXIT_SUCCESS);
}
int main(int argc, char** argv) {
pid_t pid = fork();
if( pid < 0 ) {
perror("Fork");
exit(EXIT_FAILURE);
}
if(pid == 0) {
do_what_a_child_will_do(argv[0]);
}
wait(NULL);
fprintf(stdout, "%s[%d]: Hello son!\n", argv[0], (int)getpid());
return 0;
} |
the_stack_data/87639011.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
unsigned char *read_buffer(char *file_name, size_t *size_ptr)
{
FILE *f;
unsigned char *buf;
size_t size;
/* Open file */
f = fopen(file_name, "rb");
if (!f)
return NULL;
/* Obtain file size */
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
/* Allocate and read buffer */
buf = malloc(size + 1);
fread(buf, 1, size, f);
buf[size] = '\0';
/* Return size of buffer */
if (size_ptr)
*size_ptr = size;
/* Return buffer */
return buf;
}
void write_buffer(char *file_name, const char *buffer, size_t buffer_size)
{
FILE *f;
/* Open file */
f = fopen(file_name, "w+");
/* Write buffer */
if(buffer)
fwrite(buffer, 1, buffer_size, f);
/* Close file */
fclose(f);
}
int main(int argc, char const *argv[])
{
/* Get platform */
cl_platform_id platform;
cl_uint num_platforms;
cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformIDs' failed\n");
exit(1);
}
printf("Number of platforms: %d\n", num_platforms);
printf("platform=%p\n", platform);
/* Get platform name */
char platform_name[100];
ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformInfo' failed\n");
exit(1);
}
printf("platform.name='%s'\n\n", platform_name);
/* Get device */
cl_device_id device;
cl_uint num_devices;
ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceIDs' failed\n");
exit(1);
}
printf("Number of devices: %d\n", num_devices);
printf("device=%p\n", device);
/* Get device name */
char device_name[100];
ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
device_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceInfo' failed\n");
exit(1);
}
printf("device.name='%s'\n", device_name);
printf("\n");
/* Create a Context Object */
cl_context context;
context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateContext' failed\n");
exit(1);
}
printf("context=%p\n", context);
/* Create a Command Queue Object*/
cl_command_queue command_queue;
command_queue = clCreateCommandQueue(context, device, 0, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateCommandQueue' failed\n");
exit(1);
}
printf("command_queue=%p\n", command_queue);
printf("\n");
/* Program source */
unsigned char *source_code;
size_t source_length;
/* Read program from 'clz_int16.cl' */
source_code = read_buffer("clz_int16.cl", &source_length);
/* Create a program */
cl_program program;
program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateProgramWithSource' failed\n");
exit(1);
}
printf("program=%p\n", program);
/* Build program */
ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if (ret != CL_SUCCESS )
{
size_t size;
char *log;
/* Get log size */
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);
/* Allocate log and print */
log = malloc(size);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
/* Free log and exit */
free(log);
exit(1);
}
printf("program built\n");
printf("\n");
/* Create a Kernel Object */
cl_kernel kernel;
kernel = clCreateKernel(program, "clz_int16", &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateKernel' failed\n");
exit(1);
}
/* Create and allocate host buffers */
size_t num_elem = 10;
/* Create and init host side src buffer 0 */
cl_int16 *src_0_host_buffer;
src_0_host_buffer = malloc(num_elem * sizeof(cl_int16));
for (int i = 0; i < num_elem; i++)
src_0_host_buffer[i] = (cl_int16){{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}};
/* Create and init device side src buffer 0 */
cl_mem src_0_device_buffer;
src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_int16), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_int16), src_0_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create host dst buffer */
cl_int16 *dst_host_buffer;
dst_host_buffer = malloc(num_elem * sizeof(cl_int16));
memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_int16));
/* Create device dst buffer */
cl_mem dst_device_buffer;
dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_int16), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create dst buffer\n");
exit(1);
}
/* Set kernel arguments */
ret = CL_SUCCESS;
ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clSetKernelArg' failed\n");
exit(1);
}
/* Launch the kernel */
size_t global_work_size = num_elem;
size_t local_work_size = num_elem;
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
exit(1);
}
/* Wait for it to finish */
clFinish(command_queue);
/* Read results from GPU */
ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_int16), dst_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueReadBuffer' failed\n");
exit(1);
}
/* Dump dst buffer to file */
char dump_file[100];
sprintf((char *)&dump_file, "%s.result", argv[0]);
write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_int16));
printf("Result dumped to %s\n", dump_file);
/* Free host dst buffer */
free(dst_host_buffer);
/* Free device dst buffer */
ret = clReleaseMemObject(dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 0 */
free(src_0_host_buffer);
/* Free device side src buffer 0 */
ret = clReleaseMemObject(src_0_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Release kernel */
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseKernel' failed\n");
exit(1);
}
/* Release program */
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseProgram' failed\n");
exit(1);
}
/* Release command queue */
ret = clReleaseCommandQueue(command_queue);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseCommandQueue' failed\n");
exit(1);
}
/* Release context */
ret = clReleaseContext(context);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseContext' failed\n");
exit(1);
}
return 0;
} |
the_stack_data/159514757.c | #include <stdio.h>
#include <stdlib.h>
void cadastrarPacientes();
void listarPacientes();
void excluirPacientes();
void listarPacientesPorCodigo();
typedef struct estruturaPacientes
{
int codigo;
char nome[26];
char endereco[31];
char cpf[15];
int flag;
} Pacientes;
int main()
{
int opcao;
system("cls");
do
{
printf("Menu Principal\n");
printf("1 - Incluir Pacientes\n");
printf("2 - Listar Pacientes\n");
printf("3 - Excluir Pacientes\n");
printf("4 - Listar Pacientes por codigo\n");
printf("5 - Encerrar aplicativo\n");
printf("Opcao:");
scanf("%d", &opcao);
if (opcao == 1)
{
system("cls"); //system("cls");
cadastrarPacientes();
}
if (opcao == 2)
{
system("cls");
listarPacientes();
}
if (opcao == 3)
{
excluirPacientes();
}
if (opcao == 4)
{
listarPacientesPorCodigo();
}
} while (opcao != 5);
return 0;
}
void cadastrarPacientes()
{
int resp;
Pacientes TBPacientes;
printf("Cadatrar Dados de Pacientes\n\n");
printf("Codigo:");
scanf("%d", &TBPacientes.codigo);
getchar();
printf("Nome:");
fgets(TBPacientes.nome, 26, stdin);
printf("Endereco:");
fgets(TBPacientes.endereco, 31, stdin);
printf("CPF:");
fgets(TBPacientes.cpf, 15, stdin);
TBPacientes.flag = 1;
FILE *fp = fopen("pacientes.txt", "a+b");
if (fp == NULL)
{
printf("Erro na abertura do arquivo.");
exit(1);
getchar();
}
resp = fwrite(&TBPacientes, sizeof(Pacientes), 1, fp);
if (resp != 1)
{
printf("\nERRO: Nao foi possivel cadastrar o paciente.");
}
fclose(fp);
system("cls");
printf("\nPressione qualquer tecla para continuar\n");
getchar();
system("cls");
}
void listarPacientes()
{
Pacientes TBPacientes;
FILE *fp = fopen("pacientes.txt", "r+b");
if (fp == NULL)
{
printf("\nERRO: Nao foi possivel abrir o arquivo.");
exit(1);
getchar();
}
while (!feof(fp))
{
fread(&TBPacientes, sizeof(TBPacientes), 1, fp);
if (feof(fp))
{
break;
}
if (TBPacientes.flag == 1)
{
printf("\n\n");
printf("\nCodigo:%d\nNome:%sEndereco:%sCPF:%sFlag:%d\n", TBPacientes.codigo, TBPacientes.nome, TBPacientes.endereco, TBPacientes.cpf, TBPacientes.flag);
}
}
fclose(fp);
printf("\nPressione qualquer tecla para continuar\n");
getchar();
getchar();
system("cls");
}
void excluirPacientes()
{
Pacientes TBPacientes;
FILE *arquivo = fopen("pacientes.txt", "r+b");
FILE *arquivonovo = fopen("pacientesnovo.txt", "wb");
char file[] = "pacientes.txt";
char filenovo[] = "pacientesnovo.txt";
int resp, codigo, verifica = 0;
if (arquivo == NULL)
{
printf("\nERRO: Nao foi possivel abrir o arquivo.");
exit(1);
getchar();
}
printf("Digite o codigo de quem deseja excluir: ");
scanf("%d", &codigo);
while (!feof(arquivo))
{
fread(&TBPacientes, sizeof(TBPacientes), 1, arquivo);
if (feof(arquivo))
{
break;
}
if (TBPacientes.codigo == codigo)
{
verifica = 1;
TBPacientes.flag = 0;
}
if (TBPacientes.flag == 1)
{
resp = fwrite(&TBPacientes, sizeof(Pacientes), 1, arquivonovo);
if (resp != 1)
{
printf("\nNao foi possivel excluir o cliente.\n");
}
}
}
fclose(arquivo);
fclose(arquivonovo);
remove(file);
rename(filenovo, file);
if (verifica == 0)
printf("\nPaciente nao encontrado\n");
else
printf("\nPaciente:%s excluido\n", TBPacientes.nome);
printf("\nPressione qualquer tecla para continuar\n");
getchar();
getchar();
system("cls");
}
void listarPacientesPorCodigo()
{
int cod, contador = 0, i, j, aux;
int *cods = NULL;
Pacientes TBPacientes;
FILE *fp = fopen("pacientes.txt", "r+b");
if (fp == NULL)
{
printf("\nERRO: Nao foi possivel abrir o arquivo.");
exit(1);
getchar();
}
while (!feof(fp))
{
if (feof(fp))
{
break;
}
fread(&TBPacientes, sizeof(TBPacientes), 1, fp);
contador++;
}
cods = (int *)malloc(contador * sizeof(int));
rewind(fp);
for (i = 0; i < contador; i++)
{
fseek(fp, i * sizeof(Pacientes), SEEK_SET);
fread(&TBPacientes, sizeof(Pacientes), 1, fp);
if (feof(fp))
{
break;
}
cods[i] = TBPacientes.codigo;
}
for (i = 0; i < contador; i++)
{
for (j = 0; j < contador; j++)
{
if (cods[i] < cods[j])
{
aux = cods[i];
cods[i] = cods[j];
cods[j] = aux;
}
}
}
rewind(fp);
for (i = 0; i <= contador; i++)
{
while (!feof(fp))
{
fread(&TBPacientes, sizeof(TBPacientes), 1, fp);
if (feof(fp))
{
rewind(fp);
break;
}
if (TBPacientes.codigo == cods[i])
{
printf("Codigo:%d\nNome:%sEndereco:%sCPF:%s\n", TBPacientes.codigo, TBPacientes.nome, TBPacientes.endereco, TBPacientes.cpf);
getchar();
}
}
}
fclose(fp);
printf("\nPressione qualquer tecla para continuar\n");
getchar();
getchar();
system("cls");
} |
the_stack_data/51699988.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main() {
int vet[1000000] = {0};
int sz, i, j, n, k;
int c = 0;
sz = 0;
while( scanf("%d", &n) != EOF ){
vet[sz] = n;
sz++;
}
//Bouble Sort
for( i = 0; i < sz-1; i++ ){
for( j = 0; j < sz-i-1; j++ ){
if( vet[j] > vet[j+1]){
int sup = vet[j];
vet[j] = vet[j+1];
vet[j+1] = sup;
}
}
}
for(i=0; i < sz; i+=2){
if( vet[i] != vet[i+1]){
c++;
k=i;
i--;
}
}
for(i=0; i < sz; i++){
printf("%d ", vet[i]);
}
if( c == 0 ){
printf("\n0");
}
else{
printf("\n%d", vet[k]);
}
return 0;
} |
the_stack_data/90764597.c | /*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
#if defined(TARGET_LINUX_ARM64)
#include "mth_intrinsics.h"
vrd2_t
__gd_tanh_2(vrd2_t x)
{
return (__ZGVxN2v__mth_i_vr8(x, __mth_i_dtanh));
}
vrd2_t
__gd_tanh_2m(vrd2_t x, vid2_t mask)
{
return (__ZGVxM2v__mth_i_vr8(x, mask, __mth_i_dtanh));
}
double complex
__gz_tanh_1(double complex x)
{
return (ctanh(x));
}
vcd1_t
__gz_tanh_1v(vcd1_t x)
{
return (__ZGVxN1v__mth_i_vc8(x, ctanh));
}
#endif
|
the_stack_data/48574694.c | /*
Ref:
C Kerigan Richi 2001.pdf
1.5.4. Подсчет слов
*/
#include <stdio.h>
#define IN 1 // внутри слова
#define OUT 0 // вне слова
main()
{
int c, nl, nw, nc, state;
int end = getchar();
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != end)
{
++nc;
if (c == '\n')
{
++nl;
}
if (c == ' ' || ! c == '\t' || c == '\n')
{
state = OUT;
}
else if (state == OUT)
{
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
} |
the_stack_data/123089.c | #include <stdio.h>
int main(){
int a[3],n;
scanf("%d",&n);
for(int i=2;i>=0;i--){
a[i]=n%10;
n/=10;
}
printf("%d %d %d",a[0],a[1],a[2]);
return 0;
}
|
the_stack_data/122301.c | /* $NetBSD: strchkread.c,v 1.3 2003/08/07 10:30:50 agc Exp $
*
* Copyright (c) 1986, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)strchkread.c 8.1 (Berkeley) 6/8/93
*/
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BACKLOG 5
#ifndef SLEEP
#define SLEEP 5
#endif
void
handleConnection(int fd, struct sockaddr_in6 client)
{
const char *rip;
int rval;
char claddr[INET6_ADDRSTRLEN];
if ((rip = inet_ntop(PF_INET6, &(client.sin6_addr), claddr, INET6_ADDRSTRLEN)) == NULL) {
perror("inet_ntop");
rip = "unknown";
} else {
(void)printf("Client connection from %s!\n", rip);
}
do {
char buf[BUFSIZ];
bzero(buf, sizeof(buf));
if ((rval = read(fd, buf, BUFSIZ)) < 0)
perror("reading stream message");
else if (rval == 0)
printf("Ending connection from %s.\n", rip);
else
printf("Client (%s) sent: %s", rip, buf);
} while (rval != 0);
(void)close(fd);
}
/*
* This program uses select() to check that someone is trying to connect
* before calling accept().
*/
int main()
{
int sock;
socklen_t length;
struct sockaddr_in6 server;
if ((sock = socket(PF_INET6, SOCK_STREAM, 0)) < 0) {
perror("opening stream socket");
exit(EXIT_FAILURE);
/* NOTREACHED */
}
server.sin6_family = PF_INET6;
server.sin6_addr = in6addr_any;
server.sin6_port = 0;
if (bind(sock, (struct sockaddr *)&server, sizeof(server)) != 0) {
perror("binding stream socket");
exit(EXIT_FAILURE);
/* NOTREACHED */
}
/* Find out assigned port number and print it out */
length = sizeof(server);
if (getsockname(sock, (struct sockaddr *)&server, &length) != 0) {
perror("getting socket name");
exit(EXIT_FAILURE);
/* NOTREACHED */
}
(void)printf("Socket has port #%d\n", ntohs(server.sin6_port));
if (listen(sock, BACKLOG) < 0) {
perror("listening");
exit(EXIT_FAILURE);
/* NOTREACHED */
}
for (;;) {
fd_set ready;
struct timeval to;
FD_ZERO(&ready);
FD_SET(sock, &ready);
to.tv_sec = SLEEP;
to.tv_usec = 0;
if (select(sock + 1, &ready, 0, 0, &to) < 0) {
perror("select");
continue;
}
if (FD_ISSET(sock, &ready)) {
int fd;
struct sockaddr_in6 client;
length = sizeof(client);
if ((fd = accept(sock, (struct sockaddr *)&client, &length)) < 0) {
perror("accept");
continue;
}
handleConnection(fd, client);
} else {
(void)printf("Idly sitting here, waiting for connections...\n");
}
}
/* NOTREACHED */
}
|
the_stack_data/105447.c | #include<stdio.h>
int main(void){
int variable_1, *ptr_variable_1;
variable_1 = 3;
ptr_variable_1 = &variable_1;
printf("Value of variable_1 is %d \n", variable_1);
printf("Address of variable_1 is %p \n", &variable_1);
printf("Value of ptr_variable_1 is %p \n", ptr_variable_1);
return 0;
} |
the_stack_data/162644301.c | // Copyright (c) 2015 RV-Match Team. All Rights Reserved.
#include <limits.h>
int main(void){
return (int)1 >> (sizeof(int) - 1) * CHAR_BIT;
}
|
the_stack_data/1233639.c | #include <stdio.h>
int main()
{
printf("Hello!\n");
printf("Name : Remya IS\n");
printf("Age : 36\n");
printf("Username : Remya101\n");
return(0);
}
|
the_stack_data/703339.c | /*
* POK header
*
* The following file is a part of the POK project. Any modification should
* be made according to the POK licence. You CANNOT use this file or a part
* of a file for your own project.
*
* For more information on the POK licence, please see our LICENCE FILE
*
* Please follow the coding guidelines described in doc/CODING_GUIDELINES
*
* Copyright (c) 2007-2021 POK team
*/
/* @(#)k_standard.c 5.1 93/09/24 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#ifdef POK_NEEDS_LIBMATH
#include "math_private.h"
#include <errno.h>
#include <libm.h>
#ifndef _USE_WRITE
#ifdef POK_NEEDS_LIBC_STDIO
#include <libc/stdio.h>
#define WRITE2(u, v) printf(u)
#else
#define WRITE2(u, v)
#endif /* POK_NEEDS_STDIO */
#else /* !defined(_USE_WRITE) */
#include <unistd.h> /* write */
#define WRITE2(u, v) write(2, u, v)
#undef fflush
#endif /* !defined(_USE_WRITE) */
static const double zero = 0.0; /* used as const */
/*
* Standard conformance (non-IEEE) on exception cases.
* Mapping:
* 1 -- acos(|x|>1)
* 2 -- asin(|x|>1)
* 3 -- atan2(+-0,+-0)
* 4 -- hypot overflow
* 5 -- cosh overflow
* 6 -- exp overflow
* 7 -- exp underflow
* 8 -- y0(0)
* 9 -- y0(-ve)
* 10-- y1(0)
* 11-- y1(-ve)
* 12-- yn(0)
* 13-- yn(-ve)
* 14-- lgamma(finite) overflow
* 15-- lgamma(-integer)
* 16-- log(0)
* 17-- log(x<0)
* 18-- log10(0)
* 19-- log10(x<0)
* 20-- pow(0.0,0.0)
* 21-- pow(x,y) overflow
* 22-- pow(x,y) underflow
* 23-- pow(0,negative)
* 24-- pow(neg,non-integral)
* 25-- sinh(finite) overflow
* 26-- sqrt(negative)
* 27-- fmod(x,0)
* 28-- remainder(x,0)
* 29-- acosh(x<1)
* 30-- atanh(|x|>1)
* 31-- atanh(|x|=1)
* 32-- scalb overflow
* 33-- scalb underflow
* 34-- j0(|x|>X_TLOSS)
* 35-- y0(x>X_TLOSS)
* 36-- j1(|x|>X_TLOSS)
* 37-- y1(x>X_TLOSS)
* 38-- jn(|x|>X_TLOSS, n)
* 39-- yn(x>X_TLOSS, n)
* 40-- gamma(finite) overflow
* 41-- gamma(-integer)
* 42-- pow(NaN,0.0)
* 48-- log2(0)
* 49-- log2(x<0)
*/
double __kernel_standard(double x, double y, int type) {
struct exception exc;
#ifndef POK_ERRNO_HUGE_VAL /* this is the only routine that uses \
POK_ERRNO_HUGE_VAL */
#define POK_ERRNO_HUGE_VAL inf
double inf = 0.0;
SET_HIGH_WORD(inf, 0x7ff00000); /* set inf to infinite */
#endif
#ifdef _USE_WRITE
(void)fflush(stdout);
#endif
exc.arg1 = x;
exc.arg2 = y;
switch (type) {
case 1:
case 101:
/* acos(|x|>1) */
exc.type = DOMAIN;
exc.name = type < 100 ? "acos" : "acosf";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("acos: DOMAIN error\n", 19);
}
errno = POK_ERRNO_EDOM;
}
break;
case 2:
case 102:
/* asin(|x|>1) */
exc.type = DOMAIN;
exc.name = type < 100 ? "asin" : "asinf";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("asin: DOMAIN error\n", 19);
}
errno = POK_ERRNO_EDOM;
}
break;
case 3:
case 103:
/* atan2(+-0,+-0) */
exc.arg1 = y;
exc.arg2 = x;
exc.type = DOMAIN;
exc.name = type < 100 ? "atan2" : "atan2f";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("atan2: DOMAIN error\n", 20);
}
errno = POK_ERRNO_EDOM;
}
break;
case 4:
case 104:
/* hypot(finite,finite) overflow */
exc.type = OVERFLOW;
exc.name = type < 100 ? "hypot" : "hypotf";
if (_LIB_VERSION == _SVID_)
exc.retval = POK_ERRNO_HUGE_VAL;
else
exc.retval = POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 5:
case 105:
/* cosh(finite) overflow */
exc.type = OVERFLOW;
exc.name = type < 100 ? "cosh" : "coshf";
if (_LIB_VERSION == _SVID_)
exc.retval = POK_ERRNO_HUGE_VAL;
else
exc.retval = POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 6:
case 106:
/* exp(finite) overflow */
exc.type = OVERFLOW;
exc.name = type < 100 ? "exp" : "expf";
if (_LIB_VERSION == _SVID_)
exc.retval = POK_ERRNO_HUGE_VAL;
else
exc.retval = POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 7:
case 107:
/* exp(finite) underflow */
exc.type = UNDERFLOW;
exc.name = type < 100 ? "exp" : "expf";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 8:
case 108:
/* y0(0) = -inf */
exc.type = DOMAIN; /* should be SING for IEEE */
exc.name = type < 100 ? "y0" : "y0f";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("y0: DOMAIN error\n", 17);
}
errno = POK_ERRNO_EDOM;
}
break;
case 9:
case 109:
/* y0(x<0) = NaN */
exc.type = DOMAIN;
exc.name = type < 100 ? "y0" : "y0f";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("y0: DOMAIN error\n", 17);
}
errno = POK_ERRNO_EDOM;
}
break;
case 10:
case 110:
/* y1(0) = -inf */
exc.type = DOMAIN; /* should be SING for IEEE */
exc.name = type < 100 ? "y1" : "y1f";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("y1: DOMAIN error\n", 17);
}
errno = POK_ERRNO_EDOM;
}
break;
case 11:
case 111:
/* y1(x<0) = NaN */
exc.type = DOMAIN;
exc.name = type < 100 ? "y1" : "y1f";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("y1: DOMAIN error\n", 17);
}
errno = POK_ERRNO_EDOM;
}
break;
case 12:
case 112:
/* yn(n,0) = -inf */
exc.type = DOMAIN; /* should be SING for IEEE */
exc.name = type < 100 ? "yn" : "ynf";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("yn: DOMAIN error\n", 17);
}
errno = POK_ERRNO_EDOM;
}
break;
case 13:
case 113:
/* yn(x<0) = NaN */
exc.type = DOMAIN;
exc.name = type < 100 ? "yn" : "ynf";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("yn: DOMAIN error\n", 17);
}
errno = POK_ERRNO_EDOM;
}
break;
case 14:
case 114:
/* lgamma(finite) overflow */
exc.type = OVERFLOW;
exc.name = type < 100 ? "lgamma" : "lgammaf";
if (_LIB_VERSION == _SVID_)
exc.retval = POK_ERRNO_HUGE_VAL;
else
exc.retval = POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 15:
case 115:
/* lgamma(-integer) or lgamma(0) */
exc.type = SING;
exc.name = type < 100 ? "lgamma" : "lgammaf";
if (_LIB_VERSION == _SVID_)
exc.retval = POK_ERRNO_HUGE_VAL;
else
exc.retval = POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("lgamma: SING error\n", 19);
}
errno = POK_ERRNO_EDOM;
}
break;
case 16:
case 116:
/* log(0) */
exc.type = SING;
exc.name = type < 100 ? "log" : "logf";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("log: SING error\n", 16);
}
errno = POK_ERRNO_EDOM;
}
break;
case 17:
case 117:
/* log(x<0) */
exc.type = DOMAIN;
exc.name = type < 100 ? "log" : "logf";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("log: DOMAIN error\n", 18);
}
errno = POK_ERRNO_EDOM;
}
break;
case 18:
case 118:
/* log10(0) */
exc.type = SING;
exc.name = type < 100 ? "log10" : "log10f";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("log10: SING error\n", 18);
}
errno = POK_ERRNO_EDOM;
}
break;
case 19:
case 119:
/* log10(x<0) */
exc.type = DOMAIN;
exc.name = type < 100 ? "log10" : "log10f";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("log10: DOMAIN error\n", 20);
}
errno = POK_ERRNO_EDOM;
}
break;
case 20:
case 120:
/* pow(0.0,0.0) */
/* error only if _LIB_VERSION == _SVID_ */
exc.type = DOMAIN;
exc.name = type < 100 ? "pow" : "powf";
exc.retval = zero;
if (_LIB_VERSION != _SVID_)
exc.retval = 1.0;
else if (!matherr(&exc)) {
(void)WRITE2("pow(0,0): DOMAIN error\n", 23);
errno = POK_ERRNO_EDOM;
}
break;
case 21:
case 121:
/* pow(x,y) overflow */
exc.type = OVERFLOW;
exc.name = type < 100 ? "pow" : "powf";
if (_LIB_VERSION == _SVID_) {
exc.retval = POK_ERRNO_HUGE_VAL;
y *= 0.5;
if (x < zero && rint(y) != y)
exc.retval = -POK_ERRNO_HUGE_VAL;
} else {
exc.retval = POK_ERRNO_HUGE_VAL;
y *= 0.5;
if (x < zero && rint(y) != y)
exc.retval = -POK_ERRNO_HUGE_VAL;
}
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 22:
case 122:
/* pow(x,y) underflow */
exc.type = UNDERFLOW;
exc.name = type < 100 ? "pow" : "powf";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 23:
case 123:
/* 0**neg */
exc.type = DOMAIN;
exc.name = type < 100 ? "pow" : "powf";
if (_LIB_VERSION == _SVID_)
exc.retval = zero;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("pow(0,neg): DOMAIN error\n", 25);
}
errno = POK_ERRNO_EDOM;
}
break;
case 24:
case 124:
/* neg**non-integral */
exc.type = DOMAIN;
exc.name = type < 100 ? "pow" : "powf";
if (_LIB_VERSION == _SVID_)
exc.retval = zero;
else
exc.retval = zero / zero; /* X/Open allow NaN */
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("neg**non-integral: DOMAIN error\n", 32);
}
errno = POK_ERRNO_EDOM;
}
break;
case 25:
case 125:
/* sinh(finite) overflow */
exc.type = OVERFLOW;
exc.name = type < 100 ? "sinh" : "sinhf";
if (_LIB_VERSION == _SVID_)
exc.retval = ((x > zero) ? POK_ERRNO_HUGE_VAL : -POK_ERRNO_HUGE_VAL);
else
exc.retval = ((x > zero) ? POK_ERRNO_HUGE_VAL : -POK_ERRNO_HUGE_VAL);
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 26:
case 126:
/* sqrt(x<0) */
exc.type = DOMAIN;
exc.name = type < 100 ? "sqrt" : "sqrtf";
if (_LIB_VERSION == _SVID_)
exc.retval = zero;
else
exc.retval = zero / zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("sqrt: DOMAIN error\n", 19);
}
errno = POK_ERRNO_EDOM;
}
break;
case 27:
case 127:
/* fmod(x,0) */
exc.type = DOMAIN;
exc.name = type < 100 ? "fmod" : "fmodf";
if (_LIB_VERSION == _SVID_)
exc.retval = x;
else
exc.retval = zero / zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("fmod: DOMAIN error\n", 20);
}
errno = POK_ERRNO_EDOM;
}
break;
case 28:
case 128:
/* remainder(x,0) */
exc.type = DOMAIN;
exc.name = type < 100 ? "remainder" : "remainderf";
exc.retval = zero / zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("remainder: DOMAIN error\n", 24);
}
errno = POK_ERRNO_EDOM;
}
break;
case 29:
case 129:
/* acosh(x<1) */
exc.type = DOMAIN;
exc.name = type < 100 ? "acosh" : "acoshf";
exc.retval = zero / zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("acosh: DOMAIN error\n", 20);
}
errno = POK_ERRNO_EDOM;
}
break;
case 30:
case 130:
/* atanh(|x|>1) */
exc.type = DOMAIN;
exc.name = type < 100 ? "atanh" : "atanhf";
exc.retval = zero / zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("atanh: DOMAIN error\n", 20);
}
errno = POK_ERRNO_EDOM;
}
break;
case 31:
case 131:
/* atanh(|x|=1) */
exc.type = SING;
exc.name = type < 100 ? "atanh" : "atanhf";
exc.retval = x / zero; /* sign(x)*inf */
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("atanh: SING error\n", 18);
}
errno = POK_ERRNO_EDOM;
}
break;
case 32:
case 132:
/* scalb overflow; SVID also returns +-POK_ERRNO_HUGE_VAL */
exc.type = OVERFLOW;
exc.name = type < 100 ? "scalb" : "scalbf";
exc.retval = x > zero ? POK_ERRNO_HUGE_VAL : -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 33:
case 133:
/* scalb underflow */
exc.type = UNDERFLOW;
exc.name = type < 100 ? "scalb" : "scalbf";
exc.retval = copysign(zero, x);
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 34:
case 134:
/* j0(|x|>X_TLOSS) */
exc.type = TLOSS;
exc.name = type < 100 ? "j0" : "j0f";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2(exc.name, 2);
(void)WRITE2(": TLOSS error\n", 14);
}
errno = POK_ERRNO_ERANGE;
}
break;
case 35:
case 135:
/* y0(x>X_TLOSS) */
exc.type = TLOSS;
exc.name = type < 100 ? "y0" : "y0f";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2(exc.name, 2);
(void)WRITE2(": TLOSS error\n", 14);
}
errno = POK_ERRNO_ERANGE;
}
break;
case 36:
case 136:
/* j1(|x|>X_TLOSS) */
exc.type = TLOSS;
exc.name = type < 100 ? "j1" : "j1f";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2(exc.name, 2);
(void)WRITE2(": TLOSS error\n", 14);
}
errno = POK_ERRNO_ERANGE;
}
break;
case 37:
case 137:
/* y1(x>X_TLOSS) */
exc.type = TLOSS;
exc.name = type < 100 ? "y1" : "y1f";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2(exc.name, 2);
(void)WRITE2(": TLOSS error\n", 14);
}
errno = POK_ERRNO_ERANGE;
}
break;
case 38:
case 138:
/* jn(|x|>X_TLOSS) */
exc.type = TLOSS;
exc.name = type < 100 ? "jn" : "jnf";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2(exc.name, 2);
(void)WRITE2(": TLOSS error\n", 14);
}
errno = POK_ERRNO_ERANGE;
}
break;
case 39:
case 139:
/* yn(x>X_TLOSS) */
exc.type = TLOSS;
exc.name = type < 100 ? "yn" : "ynf";
exc.retval = zero;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2(exc.name, 2);
(void)WRITE2(": TLOSS error\n", 14);
}
errno = POK_ERRNO_ERANGE;
}
break;
case 40:
case 140:
/* gamma(finite) overflow */
exc.type = OVERFLOW;
exc.name = type < 100 ? "gamma" : "gammaf";
if (_LIB_VERSION == _SVID_)
exc.retval = POK_ERRNO_HUGE_VAL;
else
exc.retval = POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
errno = POK_ERRNO_ERANGE;
}
break;
case 41:
case 141:
/* gamma(-integer) or gamma(0) */
exc.type = SING;
exc.name = type < 100 ? "gamma" : "gammaf";
if (_LIB_VERSION == _SVID_)
exc.retval = POK_ERRNO_HUGE_VAL;
else
exc.retval = POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("gamma: SING error\n", 18);
}
errno = POK_ERRNO_EDOM;
}
break;
case 42:
case 142:
/* pow(NaN,0.0) */
/* error only if _LIB_VERSION == _SVID_ & _XOPEN_ */
exc.type = DOMAIN;
exc.name = type < 100 ? "pow" : "powf";
exc.retval = x;
if (_LIB_VERSION == _IEEE_ || _LIB_VERSION == _POSIX_)
exc.retval = 1.0;
else if (!matherr(&exc)) {
errno = POK_ERRNO_EDOM;
}
break;
case 48:
case 148:
/* log2(0) */
exc.type = SING;
exc.name = type < 100 ? "log2" : "log2f";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_ERANGE;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("log2: SING error\n", 18);
}
errno = POK_ERRNO_EDOM;
}
break;
case 49:
case 149:
/* log2(x<0) */
exc.type = DOMAIN;
exc.name = type < 100 ? "log2" : "log2f";
if (_LIB_VERSION == _SVID_)
exc.retval = -POK_ERRNO_HUGE_VAL;
else
exc.retval = -POK_ERRNO_HUGE_VAL;
if (_LIB_VERSION == _POSIX_)
errno = POK_ERRNO_EDOM;
else if (!matherr(&exc)) {
if (_LIB_VERSION == _SVID_) {
(void)WRITE2("log2: DOMAIN error\n", 20);
}
errno = POK_ERRNO_EDOM;
}
break;
default:
exc.retval = -POK_ERRNO_HUGE_VAL;
break;
/*
* Default case introduced for POK to avoid a warning
*/
}
return exc.retval;
}
#endif
|
the_stack_data/231392657.c | /*
* This program is for setting TTF files to Installable Embedding mode.
*
* Note that using this to embed fonts which you are not licensed to embed
* does not make it legal.
*
* This code was written by Tom Murphy 7 (http://www.cs.cmu.edu/~tom7/)
* and is public domain. Use at your own risk...
*/
#include <stdio.h>
#include <stdlib.h>
void fatal();
int main (int argc, char**argv) {
FILE * inways;
if (argc != 2)
printf("Usage: %s font.ttf\n\nPublic Domain software by Tom 7. Use at your own risk.\n",argv[0]);
else if (inways = fopen(argv[1],"rb+")) {
int a,x;
char type[5];
type[4]=0;
fseek(inways,12,0);
for (;;) {
for (x=0;x<4;x++) if (EOF == (type[x] = getc(inways))) fatal();
if (!strcmp(type,"OS/2")) {
int length;
unsigned long loc, fstype, sum=0;
loc=ftell(inways); /* location for checksum */
for (x=4;x--;) if (EOF == getc(inways)) fatal();
fstype = fgetc(inways) << 24;
fstype |= fgetc(inways) << 16;
fstype |= fgetc(inways) << 8 ;
fstype |= fgetc(inways) ;
length = fgetc(inways) << 24;
length |= fgetc(inways) << 16;
length |= fgetc(inways) << 8 ;
length |= fgetc(inways) ;
/* printf("fstype: %d length: %d\n",fstype,length);*/
if (fseek(inways,fstype+8,0)) fatal();
fputc(0,inways);
fputc(0,inways);
fseek(inways,fstype,0);
for (x=length;x--;)
sum += fgetc(inways);
fseek(inways,loc,0); /* write checksum */
fputc(sum>>24,inways);
fputc(255&(sum>>16),inways);
fputc(255&(sum>>8), inways);
fputc(255&sum , inways);
fclose(inways);
exit(0);
}
for (x=12;x--;) if (EOF == getc(inways)) fatal();
}
} else
printf("I wasn't able to open the file %s.\n", argv[1]);
}
void fatal() {
fprintf(stderr,"Malformed TTF file.\n");
exit(-1);
}
|
the_stack_data/165766911.c | /*Program to maintain a database of employee records in memory */
#include <stdio.h>
#define MAX_PERSONS 100
/* Structure definitions */
struct date
{
int day;
int month;
int year;
};
typedef struct date DATE;
struct personnel
{
int number;
char surname[26];
char first_name[11];
DATE dob;
int dept;
DATE joined;
};
typedef struct personnel EMPLOYEE;
/* Function prototypes */
void add_an_employee(EMPLOYEE []);
void delete_an_employee(EMPLOYEE []);
void display_an_employee(EMPLOYEE []);
void display_employee_details(EMPLOYEE *);
void init_database(EMPLOYEE []);
int search_database(EMPLOYEE [], int);
int menu(void);
void main()
{
EMPLOYEE persons[MAX_PERSONS];
int menu_choice;
init_database(persons);
do
{
menu_choice = menu();
switch ( menu_choice )
{
case 1 :
add_an_employee( persons );
break;
case 2 :
delete_an_employee( persons );
break;
case 3 :
display_an_employee( persons );
break;
}
}
while ( menu_choice != 0) ;
}
void add_an_employee( EMPLOYEE person_array[] )
{
int i=0;
while ( person_array[i].number != 0 && i < MAX_PERSONS )
i++;
if ( i == MAX_PERSONS )
printf("\nSorry, the database is full\n");
else {
printf( "\n\nEmployee Number (1 to 3 digits, except 0) : " );
do
scanf( "%3d",&person_array[i].number );
while ( person_array[i].number <= 0 );
printf( "\nEmployee Surname (Maximum 25 characters) : " );
scanf( "%25s",person_array[i].surname );
printf( "\n First Name (Maximum 10 characters) : " );
scanf( "%10s",person_array[i].first_name );
printf( "\nDate of Birth\n" );
printf( " Day (1 or 2 digits) : " );
scanf( "%2d",&person_array[i].dob.day );
printf( " Month (1 or 2 digits) : " );
scanf( "%2d",&person_array[i].dob.month );
printf( " Year (1 or 2 digits) : " );
scanf( "%2d",&person_array[i].dob.year );
printf( "\nDepartment Code (1 to 4 digits): " );
scanf( "%4d",&person_array[i].dept );
printf( "\nDate Joined\n" );
printf( " Day (1 or 2 digits) : " );
scanf( "%2d",&person_array[i].joined.day );
printf( " Month (1 or 2 digits) : " );
scanf( "%2d",&person_array[i].joined.month );
printf( " Year (1 or 2 digits) : " );
scanf( "%2d",&person_array[i].joined.year );
}
}
void delete_an_employee( EMPLOYEE person_array[] )
{
int employee_number;
int pos;
printf("Employee Number to Delete (1 to 3 digits, except 0) :");
do
scanf( "%3d",&employee_number );
while ( employee_number <= 0 ) ;
pos = search_database( person_array, employee_number );
if ( pos == MAX_PERSONS )
printf( "This employee is not in the database\n" );
else
{
printf("Employee %3d deleted", employee_number);
person_array[pos].number = 0;
}
}
void display_an_employee( EMPLOYEE person_array[] )
{
int employee_number;
int pos;
printf("Employee Number to Display (1 to 3 digits, except 0):" );
do
scanf( "%3d",&employee_number );
while ( employee_number <= 0 );
pos = search_database( person_array, employee_number );
if ( pos == MAX_PERSONS )
printf( "This employee is not in the database\n" );
else
display_employee_details( &person_array[pos] );
}
void display_employee_details( EMPLOYEE *ptr )
{
printf("\n\n");
printf("Employee Number: %d\n",ptr->number);
printf("Surname : %s\n",ptr->surname);
printf("Initial : %s\n",ptr->first_name);
printf("Date of Birth : %2d/%2d/%2d\n",
ptr->dob.day,ptr->dob.month,ptr->dob.year);
printf("Department : %d\n", ptr->dept);
printf("Date Joined : %2d/%2d/%2d\n",
ptr->joined.day,ptr->joined.month,ptr->joined.year);
}
void init_database( EMPLOYEE person_array[] )
{
int i;
for ( i=0; i < MAX_PERSONS; i++ )
person_array[i].number = 0;
}
int menu(void)
{
int choice;
/* Display the menu. */
printf("\n\n 1. Add an Employee\n\n");
printf(" 2. Delete an Employee\n\n");
printf(" 3. Display an Employee\n\n");
printf(" 0. Quit\n\n");
printf( "Please enter your choice (0 to 3) " );
/* Get the option. */
do
scanf( "%d", &choice );
while ( choice <0 || choice > 3 );
return (choice);
}
int search_database( EMPLOYEE person_array[], int emp_number )
{
int i = 0;
while ( i < MAX_PERSONS && person_array[i].number != emp_number )
i++;
return (i);
} |
the_stack_data/148410.c | /*******************************************************************************
* SERVIDOR no porto 9000, à escuta de novos clientes. Quando surgem
* novos clientes os dados por eles enviados são lidos e descarregados no ecran.
*******************************************************************************/
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define SERVER_PORT 9000
#define BUF_SIZE 1024
void process_client(int fd);
void erro(char *msg);
int main() {
int fd, client;
struct sockaddr_in addr, client_addr;
int client_addr_size;
bzero((void *) &addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(SERVER_PORT);
if ( (fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
erro("na funcao socket");
if ( bind(fd,(struct sockaddr*)&addr,sizeof(addr)) < 0)
erro("na funcao bind");
if( listen(fd, 5) < 0)
erro("na funcao listen");
client_addr_size = sizeof(client_addr);
while (1) {
//clean finished child processes, avoiding zombies
//must use WNOHANG or would block whenever a child process was working
while(waitpid(-1,NULL,WNOHANG)>0);
//wait for new connection
client = accept(fd,(struct sockaddr *)&client_addr,(socklen_t *)&client_addr_size);
if (client > 0) {
if (fork() == 0) {
close(fd);
process_client(client);
exit(0);
}
close(client);
}
}
return 0;
}
void process_client(int client_fd)
{
int nread = 0;
char buffer[BUF_SIZE];
do {
nread = read(client_fd, buffer, BUF_SIZE-1);
buffer[nread] = '\0';
printf("%s\n", buffer);
fflush(stdout);
} while (nread>0);
close(client_fd);
}
void erro(char *msg){
printf("Erro: %s\n", msg);
exit(-1);
}
|
the_stack_data/86029.c | #include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
static struct TreeNode *partition(int *nums, int lo, int hi)
{
int mid = lo + (hi - lo) / 2;
struct TreeNode *node = malloc(sizeof(*node));
node->val = nums[mid];
node->left = mid > lo ? partition(nums, lo, mid - 1) : NULL;
node->right = mid < hi ? partition(nums, mid + 1, hi) : NULL;
return node;
}
static struct TreeNode* sortedArrayToBST(int* nums, int numsSize)
{
if (numsSize == 0) {
return NULL;
}
return partition(nums, 0, numsSize - 1);
}
int main(int argc, char **argv)
{
int i, count = argc - 1;
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = atoi(argv[i + 1]);
}
sortedArrayToBST(nums, count);
return 0;
}
|
the_stack_data/992531.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main (int argc, char **argv) {
//number of parallel threads that OpenMP should use
int NumThreads = 10;
//tell OpenMP to use NumThreads threads
omp_set_num_threads(NumThreads);
float *val = (float*) malloc(NumThreads*sizeof(float));
int winner = 0;
float sum = 0;
//fork into a parallel region, declare shared variables
#pragma omp parallel shared(val, winner) reduction(+:sum)
{
//variables declared inside a parallel region are private
int rank = omp_get_thread_num(); //thread's rank
int size = omp_get_num_threads();//total number of threads
printf("Hello World from thread %d of %d. \n", rank, size);
val[rank] = (float) rank;
#pragma omp for
for (int n=1; n<10000; n++) {
sum += 1/(float) n;
}
//this is bad. We've made a 'data race'
//we can find it suing the master region
#pragma omp master
{
winner = rank;
}
//we can safely do this with a cirtical region
//#pragma omp critical
//{
// sum += rank;
//}
//a better way is to tell OpenMP that we want that variable reduced
sum += (float) rank;
}
//merge back to serial
#pragma omp parallel for
for (int n=0; n<NumThreads; n++) {
printf("val[%d] = %f \n", n, val[n]);
}
#pragma omp parallel
{
int rank = omp_get_thread_num();
for (int n = 0; n<NumThreads; n++) {
if (rank == n) {
printf("val[%d] = %f \n", n, val[n]);
}
}
}
printf("The winner was %d \n", winner);
printf("The sum is %f \n", sum);
return 0;
}
|
the_stack_data/9513715.c | /*============================================================================
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- All advertising materials mentioning features or use of this software must
display the following acknowledgement:
"This product includes software developed by the German Cancer Research
Center (DKFZ)."
- Neither the name of the German Cancer Research Center (DKFZ) nor the names
of its contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE GERMAN CANCER RESEARCH CENTER (DKFZ) AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GERMAN
CANCER RESEARCH CENTER (DKFZ) OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
============================================================================*/
#ifdef WIN
#include <windows.h>
#include <stdio.h>
DWORD hfread(LPSTR ptr, DWORD size, DWORD n, FILE *stream)
{
if( (size < 0xffff) && (n < 0xffff) )
return fread( ptr, (WORD)size, (WORD)n, stream );
else
{
DWORD Bytes;
BYTE huge *lpwork;
Bytes = size*n;
for( lpwork = ptr; Bytes > 0xffff; Bytes-=0xffff, lpwork+=0xffff )
fread( (char far*)lpwork, 0xffff, 1, stream );
return fread( (char far*)lpwork, (WORD)Bytes, 1, stream );
}
}
#endif
|
the_stack_data/165764442.c | /*numPass=2, numTotal=4
Verdict:WRONG_ANSWER, Visibility:1, Input:"liril", ExpOutput:"Yes
", Output:"YesNo"
Verdict:ACCEPTED, Visibility:1, Input:"oolaleloo", ExpOutput:"No
", Output:"No"
Verdict:WRONG_ANSWER, Visibility:0, Input:"sorewaslerelsaweros", ExpOutput:"Yes
", Output:"YesNo"
Verdict:ACCEPTED, Visibility:0, Input:"qwertyuiiuytrpwq", ExpOutput:"No
", Output:"No"
*/
#include <stdio.h>
#include <string.h>
void check_palindrome(char s[],int x,int y,char*z)
{
if(x==y/2) printf("Yes");
if(*s==*(z+x-1)) check_palindrome(s+1,x-1,y,z);
else printf("No");
}
int main()
{
char s[100];
scanf("%s",s);
int x=strlen(s);
char*y;
y=s;
check_palindrome(s,x,x,y);
return 0;
} |
the_stack_data/1111087.c | /* PR debug/41695 */
/* { dg-do compile } */
/* { dg-options "-gdwarf -O2 -dA -fno-merge-debug-strings" } */
int bar (int);
void
foo (void)
{
int b = 0;
b = bar (b);
b = bar (b);
b = bar (b);
b = bar (b);
bar (b);
}
/* { dg-final { scan-assembler-not "LVL(\[0-9\]+)-\[^1\]\[^\\r\\n\]*Location list begin address\[^\\r\\n\]*\[\\r\\n\]+\[^\\r\\n\]*LVL\\1-1-" } } */
|
the_stack_data/107914.c | // Make sure instrementation data from available_externally functions doesn't
// get thrown out.
// RUN: %clang_cc1 -O2 -triple x86_64-apple-macosx10.9 -main-file-name c-linkage-available_externally.c %s -o - -emit-llvm37 -fprofile-instr-generate | FileCheck %s
// CHECK: @__llvm37_profile_name_foo = linkonce_odr hidden constant [3 x i8] c"foo", section "__DATA,__llvm37_prf_names", align 1
// CHECK: @__llvm37_profile_counters_foo = linkonce_odr hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm37_prf_cnts", align 8
// CHECK: @__llvm37_profile_data_foo = linkonce_odr hidden constant { i32, i32, i64, i8*, i64* } { i32 3, i32 1, i64 {{[0-9]+}}, i8* getelementptr inbounds ([3 x i8], [3 x i8]* @__llvm37_profile_name_foo, i32 0, i32 0), i64* getelementptr inbounds ([1 x i64], [1 x i64]* @__llvm37_profile_counters_foo, i32 0, i32 0) }, section "__DATA,__llvm37_prf_data", align 8
inline int foo(void) { return 1; }
int main(void) {
return foo();
}
|
the_stack_data/149798.c | #include<stdio.h>
#include<string.h>
#include<locale.h>
void main(){
setlocale(LC_ALL, "portuguese");
int t, i, num[3][4];
for(t=0; t<3; ++t){
for(i=0; i<4; ++i){
num[t][i] = (t*4)+i+1;
}
}
/* now print them out */
for(t=0; t<3; ++t){
for(i=0; i<4; ++i){
printf("%3d", num[t][i]);
}
printf("\n");
}
return 0;
}
|
the_stack_data/41229.c | /*
Copyright (C) 1991-2018 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it andor
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 10.0.0. Version 10.0 of the Unicode Standard is
synchronized with ISOIEC 10646:2017, fifth edition, plus
the following additions from Amendment 1 to the fifth edition:
- 56 emoji characters
- 285 hentaigana
- 3 additional Zanabazar Square characters
*/
/*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: [email protected], [email protected], [email protected],
[email protected], [email protected])
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https:github.comLLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <stdio.h>
/*
This is a program based on a test contributed by Yizi Gu@Rice Univ.
Proper user of ordered directive and clause, no data races
*/
int main()
{
int x = 0;
int _ret_val_0;
{
int i = 0;
#pragma loop name main#0
#pragma cetus reduction(+: x)
for (; i<100; ++ i)
{
x ++ ;
}
}
(((void)sizeof ((x==100) ? 1 : 0)), ({
if (x==100)
{
;
}
else
{
__assert_fail("x==100", "DRB110-ordered-orig-no.c", 57, __PRETTY_FUNCTION__);
}
}));
printf("x=%d\n", x);
_ret_val_0=0;
return _ret_val_0;
}
|
the_stack_data/1006236.c | /*
* This little program is used to parse the FreeType headers and
* find the declaration of all public APIs. This is easy, because
* they all look like the following:
*
* FT_EXPORT( return_type )
* function_name( function arguments );
*
* You must pass the list of header files as arguments. Wildcards are
* accepted if you are using GCC for compilation (and probably by
* other compilers too).
*
* Author: David Turner, 2005, 2006, 2008-2013
*
* This code is explicitly placed into the public domain.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define PROGRAM_NAME "apinames"
#define PROGRAM_VERSION "0.2"
#define LINEBUFF_SIZE 1024
typedef enum OutputFormat_
{
OUTPUT_LIST = 0, /* output the list of names, one per line */
OUTPUT_WINDOWS_DEF, /* output a Windows .DEF file for Visual C++ or Mingw */
OUTPUT_BORLAND_DEF, /* output a Windows .DEF file for Borland C++ */
OUTPUT_WATCOM_LBC, /* output a Watcom Linker Command File */
OUTPUT_NETWARE_IMP /* output a NetWare ImportFile */
} OutputFormat;
static void
panic( const char* message )
{
fprintf( stderr, "PANIC: %s\n", message );
exit(2);
}
typedef struct NameRec_
{
char* name;
unsigned int hash;
} NameRec, *Name;
static Name the_names;
static int num_names;
static int max_names;
static void
names_add( const char* name,
const char* end )
{
unsigned int h;
int nn, len;
Name nm;
if ( end <= name )
return;
/* compute hash value */
len = (int)(end - name);
h = 0;
for ( nn = 0; nn < len; nn++ )
h = h*33 + name[nn];
/* check for an pre-existing name */
for ( nn = 0; nn < num_names; nn++ )
{
nm = the_names + nn;
if ( (int)nm->hash == h &&
memcmp( name, nm->name, len ) == 0 &&
nm->name[len] == 0 )
return;
}
/* add new name */
if ( num_names >= max_names )
{
max_names += (max_names >> 1) + 4;
the_names = (NameRec*)realloc( the_names,
sizeof ( the_names[0] ) * max_names );
if ( the_names == NULL )
panic( "not enough memory" );
}
nm = &the_names[num_names++];
nm->hash = h;
nm->name = (char*)malloc( len+1 );
if ( nm->name == NULL )
panic( "not enough memory" );
memcpy( nm->name, name, len );
nm->name[len] = 0;
}
static int
name_compare( const void* name1,
const void* name2 )
{
Name n1 = (Name)name1;
Name n2 = (Name)name2;
return strcmp( n1->name, n2->name );
}
static void
names_sort( void )
{
qsort( the_names, (size_t)num_names,
sizeof ( the_names[0] ), name_compare );
}
static void
names_dump( FILE* out,
OutputFormat format,
const char* dll_name )
{
int nn;
switch ( format )
{
case OUTPUT_WINDOWS_DEF:
if ( dll_name )
fprintf( out, "LIBRARY %s\n", dll_name );
fprintf( out, "DESCRIPTION FreeType 2 DLL\n" );
fprintf( out, "EXPORTS\n" );
for ( nn = 0; nn < num_names; nn++ )
fprintf( out, " %s\n", the_names[nn].name );
break;
case OUTPUT_BORLAND_DEF:
if ( dll_name )
fprintf( out, "LIBRARY %s\n", dll_name );
fprintf( out, "DESCRIPTION FreeType 2 DLL\n" );
fprintf( out, "EXPORTS\n" );
for ( nn = 0; nn < num_names; nn++ )
fprintf( out, " _%s\n", the_names[nn].name );
break;
case OUTPUT_WATCOM_LBC:
{
const char* dot;
if ( dll_name == NULL )
{
fprintf( stderr,
"you must provide a DLL name with the -d option!\n" );
exit( 4 );
}
/* we must omit the .dll suffix from the library name */
dot = strchr( dll_name, '.' );
if ( dot != NULL )
{
char temp[512];
int len = dot - dll_name;
if ( len > (int)( sizeof ( temp ) - 1 ) )
len = sizeof ( temp ) - 1;
memcpy( temp, dll_name, len );
temp[len] = 0;
dll_name = (const char*)temp;
}
for ( nn = 0; nn < num_names; nn++ )
fprintf( out, "++_%s.%s.%s\n", the_names[nn].name, dll_name,
the_names[nn].name );
}
break;
case OUTPUT_NETWARE_IMP:
{
if ( dll_name != NULL )
fprintf( out, " (%s)\n", dll_name );
for ( nn = 0; nn < num_names - 1; nn++ )
fprintf( out, " %s,\n", the_names[nn].name );
fprintf( out, " %s\n", the_names[num_names - 1].name );
}
break;
default: /* LIST */
for ( nn = 0; nn < num_names; nn++ )
fprintf( out, "%s\n", the_names[nn].name );
}
}
/* states of the line parser */
typedef enum State_
{
STATE_START = 0, /* waiting for FT_EXPORT keyword and return type */
STATE_TYPE /* type was read, waiting for function name */
} State;
static int
read_header_file( FILE* file, int verbose )
{
static char buff[LINEBUFF_SIZE + 1];
State state = STATE_START;
while ( !feof( file ) )
{
char* p;
if ( !fgets( buff, LINEBUFF_SIZE, file ) )
break;
p = buff;
while ( *p && (*p == ' ' || *p == '\\') ) /* skip leading whitespace */
p++;
if ( *p == '\n' || *p == '\r' ) /* skip empty lines */
continue;
switch ( state )
{
case STATE_START:
{
if ( memcmp( p, "FT_EXPORT(", 10 ) != 0 )
break;
p += 10;
for (;;)
{
if ( *p == 0 || *p == '\n' || *p == '\r' )
goto NextLine;
if ( *p == ')' )
{
p++;
break;
}
p++;
}
state = STATE_TYPE;
/* sometimes, the name is just after the FT_EXPORT(...), so
* skip whitespace, and fall-through if we find an alphanumeric
* character
*/
while ( *p == ' ' || *p == '\t' )
p++;
if ( !isalpha(*p) )
break;
}
/* fall-through */
case STATE_TYPE:
{
char* name = p;
while ( isalnum(*p) || *p == '_' )
p++;
if ( p > name )
{
if ( verbose )
fprintf( stderr, ">>> %.*s\n", (int)(p - name), name );
names_add( name, p );
}
state = STATE_START;
}
break;
default:
;
}
NextLine:
;
}
return 0;
}
static void
usage( void )
{
static const char* const format =
"%s %s: extract FreeType API names from header files\n\n"
"this program is used to extract the list of public FreeType API\n"
"functions. It receives the list of header files as argument and\n"
"generates a sorted list of unique identifiers\n\n"
"usage: %s header1 [options] [header2 ...]\n\n"
"options: - : parse the content of stdin, ignore arguments\n"
" -v : verbose mode, output sent to standard error\n"
" -oFILE : write output to FILE instead of standard output\n"
" -dNAME : indicate DLL file name, 'freetype.dll' by default\n"
" -w : output .DEF file for Visual C++ and Mingw\n"
" -wB : output .DEF file for Borland C++\n"
" -wW : output Watcom Linker Response File\n"
" -wN : output NetWare Import File\n"
"\n";
fprintf( stderr,
format,
PROGRAM_NAME,
PROGRAM_VERSION,
PROGRAM_NAME
);
exit(1);
}
int main( int argc, const char* const* argv )
{
int from_stdin = 0;
int verbose = 0;
OutputFormat format = OUTPUT_LIST; /* the default */
FILE* out = stdout;
const char* library_name = NULL;
if ( argc < 2 )
usage();
/* '-' used as a single argument means read source file from stdin */
while ( argc > 1 && argv[1][0] == '-' )
{
const char* arg = argv[1];
switch ( arg[1] )
{
case 'v':
verbose = 1;
break;
case 'o':
if ( arg[2] == 0 )
{
if ( argc < 2 )
usage();
arg = argv[2];
argv++;
argc--;
}
else
arg += 2;
out = fopen( arg, "wt" );
if ( out == NULL )
{
fprintf( stderr, "could not open '%s' for writing\n", argv[2] );
exit(3);
}
break;
case 'd':
if ( arg[2] == 0 )
{
if ( argc < 2 )
usage();
arg = argv[2];
argv++;
argc--;
}
else
arg += 2;
library_name = arg;
break;
case 'w':
format = OUTPUT_WINDOWS_DEF;
switch ( arg[2] )
{
case 'B':
format = OUTPUT_BORLAND_DEF;
break;
case 'W':
format = OUTPUT_WATCOM_LBC;
break;
case 'N':
format = OUTPUT_NETWARE_IMP;
break;
case 0:
break;
default:
usage();
}
break;
case 0:
from_stdin = 1;
break;
default:
usage();
}
argc--;
argv++;
}
if ( from_stdin )
{
read_header_file( stdin, verbose );
}
else
{
for ( --argc, argv++; argc > 0; argc--, argv++ )
{
FILE* file = fopen( argv[0], "rb" );
if ( file == NULL )
fprintf( stderr, "unable to open '%s'\n", argv[0] );
else
{
if ( verbose )
fprintf( stderr, "opening '%s'\n", argv[0] );
read_header_file( file, verbose );
fclose( file );
}
}
}
if ( num_names == 0 )
panic( "could not find exported functions !!\n" );
names_sort();
names_dump( out, format, library_name );
if ( out != stdout )
fclose( out );
return 0;
}
|
the_stack_data/1261722.c | /* Code from Head First C.
Modified by Allen Downey.
*/
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
int listener_d = 0;
/* Print an error message and exit.
*/
void error(char *msg) {
fprintf(stderr, "%s: %s\n", msg, strerror(errno));
exit(1);
}
/* Set up the signal catcher.
*/
int catch_signal(int sig, void (*handler)(int)) {
struct sigaction action;
action.sa_handler = handler;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
return sigaction(sig, &action, NULL);
}
/* Signal handler for SHUTDOWN
*/
void handle_shutdown(int sig) {
if (listener_d)
close(listener_d);
fprintf(stderr, "Bye!\n");
exit(EXIT_SUCCESS);
}
/* Create the listener socket.
*/
int open_listener_socket(void) {
int s = socket(PF_INET, SOCK_STREAM, 0);
if (s == -1)
error("Can't open listener socket");
return s;
}
/* Wait for clients to connect.
*/
int open_client_socket(void) {
static struct sockaddr_storage client_address;
static unsigned int address_size = sizeof(client_address);
int s;
if ((s = accept(listener_d, (struct sockaddr *)&client_address,
&address_size)) == -1)
error("Can't open client socket");
return s;
}
/* Bind the socket to a port.
*/
void bind_to_port(int socket, int port) {
struct sockaddr_in name;
name.sin_family = PF_INET;
name.sin_port = (in_port_t)htons(port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
int reuse = 1;
int res = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR,
(char *)&reuse, sizeof(int));
if (res == -1)
error("Can't set the 'reuse' option on the socket");
res = bind(socket, (struct sockaddr *)&name, sizeof(name));
if (res == -1)
error("Can't bind to socket");
}
/* Send to the client.
*/
int say(int socket, char *s)
{
int res = send(socket, s, strlen(s), 0);
if (res == -1)
error("Error talking to the client");
return res;
}
/* Read from the client.
Returns: number of characters read.
*/
int read_in(int socket, char *buf, int len)
{
/* treat the socket stream as a regular IO stream,
so we can do character IO */
FILE *fp = fdopen(socket, "r");
int i = 0, ch;
/* eat any leading whitespace */
while (isspace(ch = fgetc(fp)) && ch != EOF) {
// do nothing
}
if (ferror(fp))
error("fgetc");
while (ch != '\n' && ch != EOF) {
if (i < len)
buf[i++] = ch;
ch = fgetc(fp);
}
if (ferror(fp))
error("fgetc");
/* terminate the string, eating any trailing whitespace */
while (isspace(buf[--i])) {
buf[i] = '\0';
}
return strlen(buf);
}
char intro_msg[] = "Internet Knock-Knock Protocol Server\nKnock, knock.\n";
int main(int argc, char *argv[])
{
char buf[255];
// set up the signal handler
if (catch_signal(SIGINT, handle_shutdown) == -1)
error("Setting interrupt handler");
// create the listening socket
int port = 30000;
listener_d = open_listener_socket();
bind_to_port(listener_d, port);
if (listen(listener_d, 10) == -1)
error("Can't listen");
while (1) {
printf("Waiting for connection on port %d\n", port);
int connect_d = open_client_socket();
pid_t pid;
if ((pid = fork()) == 0) {
// child
close(listener_d);
if (say(connect_d, intro_msg) == -1) {
close(connect_d);
exit(1);
}
read_in(connect_d, buf, sizeof(buf));
// TODO (optional): check to make sure they said "Who's there?"
if (say(connect_d, "Surrealist giraffe.\n") == -1) {
close(connect_d);
exit(1);
}
read_in(connect_d, buf, sizeof(buf));
// TODO (optional): check to make sure they said "Surrealist giraffe who?"
if (say(connect_d, "Bathtub full of brightly-colored machine tools.\n") == -1) {
close(connect_d);
exit(1);
}
// close socket and die
close(connect_d);
exit(0);
} else {
// main process
close(connect_d);
}
}
return 0;
}
|
the_stack_data/842580.c | #include <pthread.h>
#define NUM_THREADS 4
void *BusyWork(void *t) {
int i;
long tid = (long)t;
double result=0.0;
printf("Thread %ld starting...\n",tid);
for (i=0; i<1000000; i++) {
result = result + sin(i) * tan(i);
}
printf("Thread %ld done. Result = %e\n",tid, result);
pthread_exit((void*) t);
}
int main (int argc, char *argv[])
{
pthread_t thread[NUM_THREADS];
pthread_attr_t attr;
long t;
void *status;
/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(t=0; t<NUM_THREADS; t++) {
printf("Main: creating thread %ld\n", t);
pthread_create(&thread[t], &attr, BusyWork, (void *)t);
}
/* Free attribute and wait for the other threads */
pthread_attr_destroy(&attr);
for(t=0; t<NUM_THREADS; t++) {
pthread_join(thread[t], &status);
printf("Main: joined with thread %ld, status: %ld\n", t, (long)status);
}
printf("Main: program completed. Exiting.\n");
pthread_exit(NULL);
}
|
the_stack_data/1246064.c | #include<stdio.h>
#include<stdlib.h>
//program to create a linear machine to adapt and spot patterns{size fixed}
/*So you have a number, you "teach the program a part of the number,
you assign good and bad, if good, it stores the number, if bad it does not,
compares numbers and uses it to improve test, uses 1's and 0's ",
only able to compare patterns though :'(*/
//Basic code, no rotation check included
//ML Linear Draft1
char checker[10];
char x[10];
int run_count=0;
//inputs number
void input(){
printf("Enter your input\n");
int i=0;
while(i<10){
scanf(" %c", &x[i]);
//" %c"-> does not take EOL, "%c" takes EOL
i+=1;
}
}
//Creating key
void calculate(){
int i=0;
while (i<10){
if(run_count==0){
checker[i]=x[i];
}
else{
if(checker[i]!=x[i])
checker[i]='X';
}
i=i+1;
}
run_count+=1;
}
//testing
int test(){
int i;
for(i=0;i<10;i++){
if((checker[i]!='X')&&(checker[i]!=x[i])){
printf("Fails\n");
return 0;
}
printf("Yep, it passes\n");
return 1;
}
}
void main(){
int inp, flag=1;
while(flag){
printf("\nEnter 1 to input, 0 for test\n");
scanf("%d",&inp);
if(inp==0){
input();
test();
}
else{
input();
calculate();
}
printf("\nDo you wish to continue(1/0)\n");
scanf("%d",&flag);
}
}
|
the_stack_data/62638796.c | /**
******************************************************************************
* @file stm32mp1xx_ll_spi.c
* @author MCD Application Team
* @brief SPI LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* 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(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32mp1xx_ll_spi.h"
#include "stm32mp1xx_ll_bus.h"
#include "stm32mp1xx_ll_rcc.h"
#ifdef GENERATOR_I2S_PRESENT
#include "stm32mp1xx_ll_rcc.h"
#endif /* GENERATOR_I2S_PRESENT*/
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32MP1xx_LL_Driver
* @{
*/
#if defined(SPI1) || defined(SPI2) || defined(SPI3) || defined(SPI4) || defined(SPI5) || defined(SPI6)
/** @addtogroup SPI_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup SPI_LL_Private_Macros
* @{
*/
#define IS_LL_SPI_MODE(__VALUE__) (((__VALUE__) == LL_SPI_MODE_MASTER) \
|| ((__VALUE__) == LL_SPI_MODE_SLAVE))
#define IS_LL_SPI_SS_IDLENESS(__VALUE__) (((__VALUE__) == LL_SPI_SS_IDLENESS_00CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_01CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_02CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_03CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_04CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_05CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_06CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_07CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_08CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_09CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_10CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_11CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_12CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_13CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_14CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_15CYCLE))
#define IS_LL_SPI_ID_IDLENESS(__VALUE__) (((__VALUE__) == LL_SPI_ID_IDLENESS_00CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_01CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_02CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_03CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_04CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_05CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_06CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_07CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_08CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_09CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_10CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_11CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_12CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_13CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_14CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_15CYCLE))
#define IS_LL_SPI_TXCRCINIT_PATTERN(__VALUE__) (((__VALUE__) == LL_SPI_TXCRCINIT_ALL_ZERO_PATTERN) \
|| ((__VALUE__) == LL_SPI_TXCRCINIT_ALL_ONES_PATTERN))
#define IS_LL_SPI_RXCRCINIT_PATTERN(__VALUE__) (((__VALUE__) == LL_SPI_RXCRCINIT_ALL_ZERO_PATTERN) \
|| ((__VALUE__) == LL_SPI_RXCRCINIT_ALL_ONES_PATTERN))
#define IS_LL_SPI_UDR_CONFIG_REGISTER(__VALUE__) (((__VALUE__) == LL_SPI_UDR_CONFIG_REGISTER_PATTERN) \
|| ((__VALUE__) == LL_SPI_UDR_CONFIG_LAST_RECEIVED) \
|| ((__VALUE__) == LL_SPI_UDR_CONFIG_LAST_TRANSMITTED))
#define IS_LL_SPI_UDR_DETECT_BEGIN_DATA(__VALUE__) (((__VALUE__) == LL_SPI_UDR_DETECT_BEGIN_DATA_FRAME) \
|| ((__VALUE__) == LL_SPI_UDR_DETECT_END_DATA_FRAME) \
|| ((__VALUE__) == LL_SPI_UDR_DETECT_BEGIN_ACTIVE_NSS))
#define IS_LL_SPI_PROTOCOL(__VALUE__) (((__VALUE__) == LL_SPI_PROTOCOL_MOTOROLA) \
|| ((__VALUE__) == LL_SPI_PROTOCOL_TI))
#define IS_LL_SPI_PHASE(__VALUE__) (((__VALUE__) == LL_SPI_PHASE_1EDGE) \
|| ((__VALUE__) == LL_SPI_PHASE_2EDGE))
#define IS_LL_SPI_POLARITY(__VALUE__) (((__VALUE__) == LL_SPI_POLARITY_LOW) \
|| ((__VALUE__) == LL_SPI_POLARITY_HIGH))
#define IS_LL_SPI_BAUDRATEPRESCALER(__VALUE__) (((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV2) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV4) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV8) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV16) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV32) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV64) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV128) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV256))
#define IS_LL_SPI_BITORDER(__VALUE__) (((__VALUE__) == LL_SPI_LSB_FIRST) \
|| ((__VALUE__) == LL_SPI_MSB_FIRST))
#define IS_LL_SPI_TRANSFER_DIRECTION(__VALUE__) (((__VALUE__) == LL_SPI_FULL_DUPLEX) \
|| ((__VALUE__) == LL_SPI_SIMPLEX_TX) \
|| ((__VALUE__) == LL_SPI_SIMPLEX_RX) \
|| ((__VALUE__) == LL_SPI_HALF_DUPLEX_RX) \
|| ((__VALUE__) == LL_SPI_HALF_DUPLEX_TX))
#define IS_LL_SPI_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_SPI_DATAWIDTH_4BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_5BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_6BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_7BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_8BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_9BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_10BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_11BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_12BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_13BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_14BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_15BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_16BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_17BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_18BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_19BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_20BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_21BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_22BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_23BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_24BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_25BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_26BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_27BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_28BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_29BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_30BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_31BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_32BIT))
#define IS_LL_SPI_FIFO_TH(__VALUE__) (((__VALUE__) == LL_SPI_FIFO_TH_01DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_02DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_03DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_04DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_05DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_06DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_07DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_08DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_09DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_10DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_11DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_12DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_13DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_14DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_15DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_16DATA))
#define IS_LL_SPI_CRC(__VALUE__) (((__VALUE__) == LL_SPI_CRC_4BIT) \
|| ((__VALUE__) == LL_SPI_CRC_5BIT) \
|| ((__VALUE__) == LL_SPI_CRC_6BIT) \
|| ((__VALUE__) == LL_SPI_CRC_7BIT) \
|| ((__VALUE__) == LL_SPI_CRC_8BIT) \
|| ((__VALUE__) == LL_SPI_CRC_9BIT) \
|| ((__VALUE__) == LL_SPI_CRC_10BIT) \
|| ((__VALUE__) == LL_SPI_CRC_11BIT) \
|| ((__VALUE__) == LL_SPI_CRC_12BIT) \
|| ((__VALUE__) == LL_SPI_CRC_13BIT) \
|| ((__VALUE__) == LL_SPI_CRC_14BIT) \
|| ((__VALUE__) == LL_SPI_CRC_15BIT) \
|| ((__VALUE__) == LL_SPI_CRC_16BIT) \
|| ((__VALUE__) == LL_SPI_CRC_17BIT) \
|| ((__VALUE__) == LL_SPI_CRC_18BIT) \
|| ((__VALUE__) == LL_SPI_CRC_19BIT) \
|| ((__VALUE__) == LL_SPI_CRC_20BIT) \
|| ((__VALUE__) == LL_SPI_CRC_21BIT) \
|| ((__VALUE__) == LL_SPI_CRC_22BIT) \
|| ((__VALUE__) == LL_SPI_CRC_23BIT) \
|| ((__VALUE__) == LL_SPI_CRC_24BIT) \
|| ((__VALUE__) == LL_SPI_CRC_25BIT) \
|| ((__VALUE__) == LL_SPI_CRC_26BIT) \
|| ((__VALUE__) == LL_SPI_CRC_27BIT) \
|| ((__VALUE__) == LL_SPI_CRC_28BIT) \
|| ((__VALUE__) == LL_SPI_CRC_29BIT) \
|| ((__VALUE__) == LL_SPI_CRC_30BIT) \
|| ((__VALUE__) == LL_SPI_CRC_31BIT) \
|| ((__VALUE__) == LL_SPI_CRC_32BIT))
#define IS_LL_SPI_NSS(__VALUE__) (((__VALUE__) == LL_SPI_NSS_SOFT) \
|| ((__VALUE__) == LL_SPI_NSS_HARD_INPUT) \
|| ((__VALUE__) == LL_SPI_NSS_HARD_OUTPUT))
#define IS_LL_SPI_RX_FIFO(__VALUE__) (((__VALUE__) == LL_SPI_RX_FIFO_0PACKET) \
|| ((__VALUE__) == LL_SPI_RX_FIFO_1PACKET) \
|| ((__VALUE__) == LL_SPI_RX_FIFO_2PACKET) \
|| ((__VALUE__) == LL_SPI_RX_FIFO_3PACKET))
#define IS_LL_SPI_CRCCALCULATION(__VALUE__) (((__VALUE__) == LL_SPI_CRCCALCULATION_ENABLE) \
|| ((__VALUE__) == LL_SPI_CRCCALCULATION_DISABLE))
#define IS_LL_SPI_CRC_POLYNOMIAL(__VALUE__) ((__VALUE__) >= 0x1UL)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup SPI_LL_Exported_Functions
* @{
*/
/** @addtogroup SPI_LL_EF_Init
* @{
*/
/**
* @brief De-initialize the SPI registers to their default reset values.
* @param SPIx SPI Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: SPI registers are de-initialized
* - ERROR: SPI registers are not de-initialized
*/
ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx)
{
ErrorStatus status = ERROR;
/* Check the parameters */
assert_param(IS_SPI_ALL_INSTANCE(SPIx));
#if defined(SPI1)
if (SPIx == SPI1)
{
/* Force reset of SPI clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI1);
/* Release reset of SPI clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI1);
status = SUCCESS;
}
#endif /* SPI1 */
#if defined(SPI2)
if (SPIx == SPI2)
{
/* Force reset of SPI clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2);
/* Release reset of SPI clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2);
status = SUCCESS;
}
#endif /* SPI2 */
#if defined(SPI3)
if (SPIx == SPI3)
{
/* Force reset of SPI clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI3);
/* Release reset of SPI clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI3);
status = SUCCESS;
}
#endif /* SPI3 */
#if defined(SPI4)
if (SPIx == SPI4)
{
/* Force reset of SPI clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI4);
/* Release reset of SPI clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI4);
status = SUCCESS;
}
#endif /* SPI4 */
#if defined(SPI5)
if (SPIx == SPI5)
{
/* Force reset of SPI clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI5);
/* Release reset of SPI clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI5);
status = SUCCESS;
}
#endif /* SPI5 */
#if defined(SPI6)
if (SPIx == SPI6)
{
/* Force reset of SPI clock */
LL_APB5_GRP1_ForceReset(LL_APB5_GRP1_PERIPH_SPI6);
/* Release reset of SPI clock */
LL_APB5_GRP1_ReleaseReset(LL_APB5_GRP1_PERIPH_SPI6);
status = SUCCESS;
}
#endif /* SPI6 */
return status;
}
/**
* @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct.
* @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0),
* SPI IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @param SPIx SPI Instance
* @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure
* @retval An ErrorStatus enumeration value. (Return always SUCCESS)
*/
ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct)
{
ErrorStatus status = ERROR;
uint32_t tmp_nss;
uint32_t tmp_mode;
/* Check the SPI Instance SPIx*/
assert_param(IS_SPI_ALL_INSTANCE(SPIx));
/* Check the SPI parameters from SPI_InitStruct*/
assert_param(IS_LL_SPI_TRANSFER_DIRECTION(SPI_InitStruct->TransferDirection));
assert_param(IS_LL_SPI_MODE(SPI_InitStruct->Mode));
assert_param(IS_LL_SPI_DATAWIDTH(SPI_InitStruct->DataWidth));
assert_param(IS_LL_SPI_POLARITY(SPI_InitStruct->ClockPolarity));
assert_param(IS_LL_SPI_PHASE(SPI_InitStruct->ClockPhase));
assert_param(IS_LL_SPI_NSS(SPI_InitStruct->NSS));
assert_param(IS_LL_SPI_BAUDRATEPRESCALER(SPI_InitStruct->BaudRate));
assert_param(IS_LL_SPI_BITORDER(SPI_InitStruct->BitOrder));
assert_param(IS_LL_SPI_CRCCALCULATION(SPI_InitStruct->CRCCalculation));
if (LL_SPI_IsEnabled(SPIx) == 0x00000000UL)
{
/*---------------------------- SPIx CFG1 Configuration ------------------------
* Configure SPIx CFG1 with parameters:
* - Master Baud Rate : SPI_CFG1_MBR[2:0] bits
* - CRC Computation Enable : SPI_CFG1_CRCEN bit
* - Length of data frame : SPI_CFG1_DSIZE[4:0] bits
*/
MODIFY_REG(SPIx->CFG1, SPI_CFG1_MBR | SPI_CFG1_CRCEN | SPI_CFG1_DSIZE,
SPI_InitStruct->BaudRate | SPI_InitStruct->CRCCalculation | SPI_InitStruct->DataWidth);
tmp_nss = SPI_InitStruct->NSS;
tmp_mode = SPI_InitStruct->Mode;
/* Checks to setup Internal SS signal level and avoid a MODF Error */
if ((LL_SPI_GetNSSPolarity(SPIx) == LL_SPI_NSS_POLARITY_LOW) && (tmp_nss == LL_SPI_NSS_SOFT) && (tmp_mode == LL_SPI_MODE_MASTER))
{
LL_SPI_SetInternalSSLevel(SPIx, LL_SPI_SS_LEVEL_HIGH);
}
/*---------------------------- SPIx CFG2 Configuration ------------------------
* Configure SPIx CFG2 with parameters:
* - NSS management : SPI_CFG2_SSM, SPI_CFG2_SSOE bits
* - ClockPolarity : SPI_CFG2_CPOL bit
* - ClockPhase : SPI_CFG2_CPHA bit
* - BitOrder : SPI_CFG2_LSBFRST bit
* - Master/Slave Mode : SPI_CFG2_MASTER bit
* - SPI Mode : SPI_CFG2_COMM[1:0] bits
*/
MODIFY_REG(SPIx->CFG2, SPI_CFG2_SSM | SPI_CFG2_SSOE |
SPI_CFG2_CPOL | SPI_CFG2_CPHA |
SPI_CFG2_LSBFRST | SPI_CFG2_MASTER | SPI_CFG2_COMM,
SPI_InitStruct->NSS | SPI_InitStruct->ClockPolarity |
SPI_InitStruct->ClockPhase | SPI_InitStruct->BitOrder |
SPI_InitStruct->Mode | (SPI_InitStruct->TransferDirection & SPI_CFG2_COMM));
/*---------------------------- SPIx CR1 Configuration ------------------------
* Configure SPIx CR1 with parameter:
* - Half Duplex Direction : SPI_CR1_HDDIR bit
*/
MODIFY_REG(SPIx->CR1, SPI_CR1_HDDIR, SPI_InitStruct->TransferDirection & SPI_CR1_HDDIR);
/*---------------------------- SPIx CRCPOLY Configuration ----------------------
* Configure SPIx CRCPOLY with parameter:
* - CRCPoly : CRCPOLY[31:0] bits
*/
if (SPI_InitStruct->CRCCalculation == LL_SPI_CRCCALCULATION_ENABLE)
{
assert_param(IS_LL_SPI_CRC_POLYNOMIAL(SPI_InitStruct->CRCPoly));
LL_SPI_SetCRCPolynomial(SPIx, SPI_InitStruct->CRCPoly);
}
/* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */
CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD);
status = SUCCESS;
}
return status;
}
/**
* @brief Set each @ref LL_SPI_InitTypeDef field to default value.
* @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct)
{
/* Set SPI_InitStruct fields to default values */
SPI_InitStruct->TransferDirection = LL_SPI_FULL_DUPLEX;
SPI_InitStruct->Mode = LL_SPI_MODE_SLAVE;
SPI_InitStruct->DataWidth = LL_SPI_DATAWIDTH_8BIT;
SPI_InitStruct->ClockPolarity = LL_SPI_POLARITY_LOW;
SPI_InitStruct->ClockPhase = LL_SPI_PHASE_1EDGE;
SPI_InitStruct->NSS = LL_SPI_NSS_HARD_INPUT;
SPI_InitStruct->BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV2;
SPI_InitStruct->BitOrder = LL_SPI_MSB_FIRST;
SPI_InitStruct->CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE;
SPI_InitStruct->CRCPoly = 7UL;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/** @addtogroup I2S_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup I2S_LL_Private_Constants I2S Private Constants
* @{
*/
/* I2S registers Masks */
#define I2S_I2SCFGR_CLEAR_MASK (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | \
SPI_I2SCFGR_DATFMT | SPI_I2SCFGR_CKPOL | \
SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_MCKOE | \
SPI_I2SCFGR_I2SCFG | SPI_I2SCFGR_I2SMOD )
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup I2S_LL_Private_Macros I2S Private Macros
* @{
*/
#define IS_LL_I2S_DATAFORMAT(__VALUE__) (((__VALUE__) == LL_I2S_DATAFORMAT_16B) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_16B_EXTENDED) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_24B) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_24B_LEFT_ALIGNED) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_32B))
#define IS_LL_I2S_CHANNEL_LENGTH_TYPE (__VALUE__) (((__VALUE__) == LL_I2S_SLAVE_VARIABLE_CH_LENGTH) \
|| ((__VALUE__) == LL_I2S_SLAVE_FIXED_CH_LENGTH))
#define IS_LL_I2S_CKPOL(__VALUE__) (((__VALUE__) == LL_I2S_POLARITY_LOW) \
|| ((__VALUE__) == LL_I2S_POLARITY_HIGH))
#define IS_LL_I2S_STANDARD(__VALUE__) (((__VALUE__) == LL_I2S_STANDARD_PHILIPS) \
|| ((__VALUE__) == LL_I2S_STANDARD_MSB) \
|| ((__VALUE__) == LL_I2S_STANDARD_LSB) \
|| ((__VALUE__) == LL_I2S_STANDARD_PCM_SHORT) \
|| ((__VALUE__) == LL_I2S_STANDARD_PCM_LONG))
#define IS_LL_I2S_MODE(__VALUE__) (((__VALUE__) == LL_I2S_MODE_SLAVE_TX) \
|| ((__VALUE__) == LL_I2S_MODE_SLAVE_RX) \
|| ((__VALUE__) == LL_I2S_MODE_SLAVE_FULL_DUPLEX) \
|| ((__VALUE__) == LL_I2S_MODE_MASTER_TX) \
|| ((__VALUE__) == LL_I2S_MODE_MASTER_RX) \
|| ((__VALUE__) == LL_I2S_MODE_MASTER_FULL_DUPLEX))
#define IS_LL_I2S_MCLK_OUTPUT(__VALUE__) (((__VALUE__) == LL_I2S_MCLK_OUTPUT_ENABLE) \
|| ((__VALUE__) == LL_I2S_MCLK_OUTPUT_DISABLE))
#define IS_LL_I2S_AUDIO_FREQ(__VALUE__) ((((__VALUE__) >= LL_I2S_AUDIOFREQ_8K) \
&& ((__VALUE__) <= LL_I2S_AUDIOFREQ_192K)) \
|| ((__VALUE__) == LL_I2S_AUDIOFREQ_DEFAULT))
#define IS_LL_I2S_PRESCALER_LINEAR(__VALUE__) ((__VALUE__) <= 0xFFUL)
#define IS_LL_I2S_PRESCALER_PARITY(__VALUE__) (((__VALUE__) == LL_I2S_PRESCALER_PARITY_EVEN) \
|| ((__VALUE__) == LL_I2S_PRESCALER_PARITY_ODD))
#define IS_LL_I2S_FIFO_TH (__VALUE__) (((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_01DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_02DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_03DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_04DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_05DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_06DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_07DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_08DATA))
#define IS_LL_I2S_BIT_ORDER(__VALUE__) (((__VALUE__) == LL_I2S_LSB_FIRST) \
|| ((__VALUE__) == LL_I2S_MSB_FIRST))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup I2S_LL_Exported_Functions
* @{
*/
/** @addtogroup I2S_LL_EF_Init
* @{
*/
/**
* @brief De-initialize the SPI/I2S registers to their default reset values.
* @param SPIx SPI Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: SPI registers are de-initialized
* - ERROR: SPI registers are not de-initialized
*/
ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx)
{
return LL_SPI_DeInit(SPIx);
}
/**
* @brief Initializes the SPI/I2S registers according to the specified parameters in I2S_InitStruct.
* @note As some bits in I2S configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0),
* SPI IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @note I2S (SPI) source clock must be ready before calling this function. Otherwise will results in wrong programming.
* @param SPIx SPI Instance
* @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: SPI registers are Initialized
* - ERROR: SPI registers are not Initialized
*/
ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct)
{
uint32_t i2sdiv = 0UL, i2sodd = 0UL, packetlength = 1UL, ispcm = 0UL;
uint32_t tmp;
uint32_t sourceclock = 0UL;
ErrorStatus status = ERROR;
/* Check the I2S parameters */
assert_param(IS_I2S_ALL_INSTANCE(SPIx));
assert_param(IS_LL_I2S_MODE(I2S_InitStruct->Mode));
assert_param(IS_LL_I2S_STANDARD(I2S_InitStruct->Standard));
assert_param(IS_LL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat));
assert_param(IS_LL_I2S_MCLK_OUTPUT(I2S_InitStruct->MCLKOutput));
assert_param(IS_LL_I2S_AUDIO_FREQ(I2S_InitStruct->AudioFreq));
assert_param(IS_LL_I2S_CKPOL(I2S_InitStruct->ClockPolarity));
/* Check that SPE bit is set to 0 in order to be sure that SPI/I2S block is disabled.
* In this case, it is useless to check if the I2SMOD bit is set to 0 because
* this bit I2SMOD only serves to select the desired mode.
*/
if (LL_SPI_IsEnabled(SPIx) == 0x00000000UL)
{
/*---------------------------- SPIx I2SCFGR Configuration --------------------
* Configure SPIx I2SCFGR with parameters:
* - Mode : SPI_I2SCFGR_I2SCFG[2:0] bits
* - Standard : SPI_I2SCFGR_I2SSTD[1:0] and SPI_I2SCFGR_PCMSYNC bits
* - DataFormat : SPI_I2SCFGR_CHLEN, SPI_I2SCFGR_DATFMT and SPI_I2SCFGR_DATLEN[1:0] bits
* - ClockPolarity : SPI_I2SCFGR_CKPOL bit
* - MCLKOutput : SPI_I2SPR_MCKOE bit
* - I2S mode : SPI_I2SCFGR_I2SMOD bit
*/
/* Write to SPIx I2SCFGR */
MODIFY_REG(SPIx->I2SCFGR,
I2S_I2SCFGR_CLEAR_MASK,
I2S_InitStruct->Mode | I2S_InitStruct->Standard |
I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity |
I2S_InitStruct->MCLKOutput | SPI_I2SCFGR_I2SMOD);
/*---------------------------- SPIx I2SCFGR Configuration ----------------------
* Configure SPIx I2SCFGR with parameters:
* - AudioFreq : SPI_I2SCFGR_I2SDIV[7:0] and SPI_I2SCFGR_ODD bits
*/
/* If the requested audio frequency is not the default, compute the prescaler (i2sodd, i2sdiv)
* else, default values are used: i2sodd = 0U, i2sdiv = 0U.
*/
if (I2S_InitStruct->AudioFreq != LL_I2S_AUDIOFREQ_DEFAULT)
{
/* Check the frame length (For the Prescaler computing)
* Default value: LL_I2S_DATAFORMAT_16B (packetlength = 1U).
*/
if (I2S_InitStruct->DataFormat != LL_I2S_DATAFORMAT_16B)
{
/* Packet length is 32 bits */
packetlength = 2UL;
}
/* Check if PCM standard is used */
if ((I2S_InitStruct->Standard == LL_I2S_STANDARD_PCM_SHORT) ||
(I2S_InitStruct->Standard == LL_I2S_STANDARD_PCM_LONG))
{
ispcm = 1UL;
}
/* Get the I2S (SPI) source clock value */
#if defined(SPI1)
if (SPIx == SPI1)
{
sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI1_CLKSOURCE);
}
#endif
#if defined(SPI2)
if (SPIx == SPI2)
{
sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI23_CLKSOURCE);
}
#endif
#if defined(SPI3)
if (SPIx == SPI3)
{
sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI23_CLKSOURCE);
}
#endif
/* Compute the Real divider depending on the MCLK output state with a fixed point */
if (I2S_InitStruct->MCLKOutput == LL_I2S_MCLK_OUTPUT_ENABLE)
{
/* MCLK output is enabled */
tmp = (((sourceclock / (256UL >> ispcm)) * 16UL) / I2S_InitStruct->AudioFreq) + 8UL;
}
else
{
/* MCLK output is disabled */
tmp = (((sourceclock / ((32UL >> ispcm) * packetlength)) * 16UL) / I2S_InitStruct->AudioFreq) + 8UL;
}
/* Remove the fixed point */
tmp = tmp / 16UL;
/* Check the parity of the divider */
i2sodd = tmp & 0x1UL;
/* Compute the i2sdiv prescaler */
i2sdiv = tmp / 2UL;
}
/* Test if the obtain values are forbiden or out of range */
if (((i2sodd == 1UL) && (i2sdiv == 1UL)) || (i2sdiv > 0xFFUL))
{
/* Set the default values */
i2sdiv = 0UL;
i2sodd = 0UL;
}
/* Write to SPIx I2SCFGR register the computed value */
MODIFY_REG(SPIx->I2SCFGR,
SPI_I2SCFGR_ODD | SPI_I2SCFGR_I2SDIV,
(i2sodd << SPI_I2SCFGR_ODD_Pos) | (i2sdiv << SPI_I2SCFGR_I2SDIV_Pos));
status = SUCCESS;
}
return status;
}
/**
* @brief Set each @ref LL_I2S_InitTypeDef field to default value.
* @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct)
{
/*--------------- Reset I2S init structure parameters values -----------------*/
I2S_InitStruct->Mode = LL_I2S_MODE_SLAVE_TX;
I2S_InitStruct->Standard = LL_I2S_STANDARD_PHILIPS;
I2S_InitStruct->DataFormat = LL_I2S_DATAFORMAT_16B;
I2S_InitStruct->MCLKOutput = LL_I2S_MCLK_OUTPUT_DISABLE;
I2S_InitStruct->AudioFreq = LL_I2S_AUDIOFREQ_DEFAULT;
I2S_InitStruct->ClockPolarity = LL_I2S_POLARITY_LOW;
}
/**
* @brief Set linear and parity prescaler.
* @note To calculate value of PrescalerLinear(I2SDIV[7:0] bits) and PrescalerParity(ODD bit)\n
* Check Audio frequency table and formulas inside Reference Manual (SPI/I2S).
* @param SPIx SPI Instance
* @param PrescalerLinear Value between Min_Data=0x00 and Max_Data=0xFF
* @note PrescalerLinear '1' is not authorized with parity LL_I2S_PRESCALER_PARITY_ODD
* @param PrescalerParity This parameter can be one of the following values:
* @arg @ref LL_I2S_PRESCALER_PARITY_EVEN
* @arg @ref LL_I2S_PRESCALER_PARITY_ODD
* @retval None
*/
void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity)
{
/* Check the I2S parameters */
assert_param(IS_I2S_ALL_INSTANCE(SPIx));
assert_param(IS_LL_I2S_PRESCALER_LINEAR(PrescalerLinear));
assert_param(IS_LL_I2S_PRESCALER_PARITY(PrescalerParity));
/* Write to SPIx I2SPR */
MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_I2SDIV | SPI_I2SCFGR_ODD, (PrescalerLinear << SPI_I2SCFGR_I2SDIV_Pos) |
(PrescalerParity << SPI_I2SCFGR_ODD_Pos));
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(SPI1) || defined(SPI2) || defined(SPI3) || defined(SPI4) || defined(SPI5) || defined(SPI6) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/99165.c | #include <stdio.h>
/*
print the corresponding Celsius to Fahrenheit table.
*/
int main(int argc, char const *argv[])
{
float celsius, fahr;
int lower, upper, step;
lower = 0;
upper = 300;
step = 20;
fahr = lower;
while (fahr <= upper) {
celsius = (fahr - 32) * (5.0/9.0);
printf("%6.1f\t%3.0f\n", celsius,fahr);
fahr = fahr + step;
}
return 0;
} |
the_stack_data/36927.c | /*C Program to create segment tree of a given array*/
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#define minimum(x,y) (x<y)?x:y
void create(int[],int,int[],int,int); //Creates segment tree
void inorder(int[],int); //traversal
void preorder(int[],int);
int sub_min(int[],int,int,int,int,int); //finds minimum in given subsequence
int main()
{
int a[]={2,5,1,4,9,3},n=6,i,start,end;
int *tree=(int*)calloc(sizeof(int),4*n+10);
for(i=0;i<n;i++)
printf(" %d",*(a+i));
printf("\n");
create(tree,1,a,0,n-1);
printf(" Inorder: ");
inorder(tree,1);
printf("\n");
printf("Preorder: ");
preorder(tree,1);
printf("\n\n");
printf("Enter Subsequence:-\n");
printf("Enter start of subsequence: ");
scanf("%d",&start);
printf("Enter end of subsequence: ");
scanf("%d",&end);
printf("\nMinimum = %d\n\n",sub_min(tree,1,0,n-1,start,end));
return 0;
}
void create(int tree[],int index,int a[],int first,int last)
{
if(first<last)
{
int mid=(first+last)/2;
tree[2*index]=tree[2*index+1]=0;
create(tree,2*index,a,first,mid);
create(tree,2*index+1,a,mid+1,last);
}
if(first==last)
{
tree[index]=a[first];
tree[2*index]=tree[2*index+1]=0;
}
if(tree[2*index]!=0&&tree[2*index+1]!=0) //if root is not leaf node then take minimum of of its left and right child
tree[index]=minimum(tree[2*index],tree[2*index+1]);
return;
}
void inorder(int tree[],int index)
{
if(tree[index]!=0)
{
inorder(tree,2*index);
printf(" %d",tree[index]);
inorder(tree,2*index+1);
}
return;
}
void preorder(int tree[],int index)
{
if(tree[index]!=0)
{
printf(" %d",tree[index]);
preorder(tree,2*index);
preorder(tree,2*index+1);
}
return;
}
int sub_min(int tree[],int index,int first,int last,int start,int end)
{
int mid=(first+last)/2;
if(start<=first&&end>=last)
return tree[index];
if(last<start||first>end)
return INT_MAX;
return minimum(sub_min(tree,2*index,first,mid,start,end),sub_min(tree,2*index+1,mid+1,last,start,end));
}
|
the_stack_data/243892651.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
scanf("%d", &n);
for (i = 0; i < 2; i++)
printf("hello%d\n", n);
return 0;
}
|
the_stack_data/3262772.c | #include <stdio.h>
#include <ctype.h>
int main()
{
int n, i, p, num;
char ar[9999];
while (scanf("%d", &n) != EOF)
{
for (p = 1; p <= n; p++)
{
num = 0;
for (i = 0; i < 9999; i++)
{
scanf("%c", &ar[i]);
if (isdigit(ar[i]))
num++;
if (i > 0 && ar[i] == '\n')
break;
}
printf("%d\n", num);
}
}
return 0;
}
|
the_stack_data/6262.c | /* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh, 2018 */
#ifdef CAPSTONE_HAS_EVM
#include <string.h>
#include "../../cs_priv.h"
#include "../../utils.h"
#include "EVMMapping.h"
#ifndef CAPSTONE_DIET
static cs_evm insns[] = {
#include "EVMMappingInsn.inc"
};
#endif
// look for @id in @insns, given its size in @max. first time call will update @cache.
// return 0 if not found
static int evm_insn_find(cs_evm *insns, unsigned int max, unsigned int id)
{
if (id > max)
return -1;
if (insns[id].fee == 0xffffffff)
// unused opcode
return -1;
return (int)id;
}
// fill in details
void EVM_get_insn_id(cs_struct *h, cs_insn *insn, unsigned int id)
{
#ifndef CAPSTONE_DIET
int i = evm_insn_find(insns, ARR_SIZE(insns), id);
//printf(">> id = %u\n", id);
if (i >= 0) {
if (h->detail) {
cs_struct handle;
handle.detail = h->detail;
memcpy(&insn->detail->evm, &insns[i], sizeof(insns[i]));
}
}
#endif
}
#ifndef CAPSTONE_DIET
static name_map insn_name_maps[] = {
{ EVM_INS_STOP, "stop" },
{ EVM_INS_ADD, "add" },
{ EVM_INS_MUL, "mul" },
{ EVM_INS_SUB, "sub" },
{ EVM_INS_DIV, "div" },
{ EVM_INS_SDIV, "sdiv" },
{ EVM_INS_MOD, "mod" },
{ EVM_INS_SMOD, "smod" },
{ EVM_INS_ADDMOD, "addmod" },
{ EVM_INS_MULMOD, "mulmod" },
{ EVM_INS_EXP, "exp" },
{ EVM_INS_SIGNEXTEND, "signextend" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_LT, "lt" },
{ EVM_INS_GT, "gt" },
{ EVM_INS_SLT, "slt" },
{ EVM_INS_SGT, "sgt" },
{ EVM_INS_EQ, "eq" },
{ EVM_INS_ISZERO, "iszero" },
{ EVM_INS_AND, "and" },
{ EVM_INS_OR, "or" },
{ EVM_INS_XOR, "xor" },
{ EVM_INS_NOT, "not" },
{ EVM_INS_BYTE, "byte" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_SHA3, "sha3" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_ADDRESS, "address" },
{ EVM_INS_BALANCE, "balance" },
{ EVM_INS_ORIGIN, "origin" },
{ EVM_INS_CALLER, "caller" },
{ EVM_INS_CALLVALUE, "callvalue" },
{ EVM_INS_CALLDATALOAD, "calldataload" },
{ EVM_INS_CALLDATASIZE, "calldatasize" },
{ EVM_INS_CALLDATACOPY, "calldatacopy" },
{ EVM_INS_CODESIZE, "codesize" },
{ EVM_INS_CODECOPY, "codecopy" },
{ EVM_INS_GASPRICE, "gasprice" },
{ EVM_INS_EXTCODESIZE, "extcodesize" },
{ EVM_INS_EXTCODECOPY, "extcodecopy" },
{ EVM_INS_RETURNDATASIZE, "returndatasize" },
{ EVM_INS_RETURNDATACOPY, "returndatacopy" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_BLOCKHASH, "blockhash" },
{ EVM_INS_COINBASE, "coinbase" },
{ EVM_INS_TIMESTAMP, "timestamp" },
{ EVM_INS_NUMBER, "number" },
{ EVM_INS_DIFFICULTY, "difficulty" },
{ EVM_INS_GASLIMIT, "gaslimit" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_POP, "pop" },
{ EVM_INS_MLOAD, "mload" },
{ EVM_INS_MSTORE, "mstore" },
{ EVM_INS_MSTORE8, "mstore8" },
{ EVM_INS_SLOAD, "sload" },
{ EVM_INS_SSTORE, "sstore" },
{ EVM_INS_JUMP, "jump" },
{ EVM_INS_JUMPI, "jumpi" },
{ EVM_INS_PC, "pc" },
{ EVM_INS_MSIZE, "msize" },
{ EVM_INS_GAS, "gas" },
{ EVM_INS_JUMPDEST, "jumpdest" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_PUSH1, "push1" },
{ EVM_INS_PUSH2, "push2" },
{ EVM_INS_PUSH3, "push3" },
{ EVM_INS_PUSH4, "push4" },
{ EVM_INS_PUSH5, "push5" },
{ EVM_INS_PUSH6, "push6" },
{ EVM_INS_PUSH7, "push7" },
{ EVM_INS_PUSH8, "push8" },
{ EVM_INS_PUSH9, "push9" },
{ EVM_INS_PUSH10, "push10" },
{ EVM_INS_PUSH11, "push11" },
{ EVM_INS_PUSH12, "push12" },
{ EVM_INS_PUSH13, "push13" },
{ EVM_INS_PUSH14, "push14" },
{ EVM_INS_PUSH15, "push15" },
{ EVM_INS_PUSH16, "push16" },
{ EVM_INS_PUSH17, "push17" },
{ EVM_INS_PUSH18, "push18" },
{ EVM_INS_PUSH19, "push19" },
{ EVM_INS_PUSH20, "push20" },
{ EVM_INS_PUSH21, "push21" },
{ EVM_INS_PUSH22, "push22" },
{ EVM_INS_PUSH23, "push23" },
{ EVM_INS_PUSH24, "push24" },
{ EVM_INS_PUSH25, "push25" },
{ EVM_INS_PUSH26, "push26" },
{ EVM_INS_PUSH27, "push27" },
{ EVM_INS_PUSH28, "push28" },
{ EVM_INS_PUSH29, "push29" },
{ EVM_INS_PUSH30, "push30" },
{ EVM_INS_PUSH31, "push31" },
{ EVM_INS_PUSH32, "push32" },
{ EVM_INS_DUP1, "dup1" },
{ EVM_INS_DUP2, "dup2" },
{ EVM_INS_DUP3, "dup3" },
{ EVM_INS_DUP4, "dup4" },
{ EVM_INS_DUP5, "dup5" },
{ EVM_INS_DUP6, "dup6" },
{ EVM_INS_DUP7, "dup7" },
{ EVM_INS_DUP8, "dup8" },
{ EVM_INS_DUP9, "dup9" },
{ EVM_INS_DUP10, "dup10" },
{ EVM_INS_DUP11, "dup11" },
{ EVM_INS_DUP12, "dup12" },
{ EVM_INS_DUP13, "dup13" },
{ EVM_INS_DUP14, "dup14" },
{ EVM_INS_DUP15, "dup15" },
{ EVM_INS_DUP16, "dup16" },
{ EVM_INS_SWAP1, "swap1" },
{ EVM_INS_SWAP2, "swap2" },
{ EVM_INS_SWAP3, "swap3" },
{ EVM_INS_SWAP4, "swap4" },
{ EVM_INS_SWAP5, "swap5" },
{ EVM_INS_SWAP6, "swap6" },
{ EVM_INS_SWAP7, "swap7" },
{ EVM_INS_SWAP8, "swap8" },
{ EVM_INS_SWAP9, "swap9" },
{ EVM_INS_SWAP10, "swap10" },
{ EVM_INS_SWAP11, "swap11" },
{ EVM_INS_SWAP12, "swap12" },
{ EVM_INS_SWAP13, "swap13" },
{ EVM_INS_SWAP14, "swap14" },
{ EVM_INS_SWAP15, "swap15" },
{ EVM_INS_SWAP16, "swap16" },
{ EVM_INS_LOG0, "log0" },
{ EVM_INS_LOG1, "log1" },
{ EVM_INS_LOG2, "log2" },
{ EVM_INS_LOG3, "log3" },
{ EVM_INS_LOG4, "log4" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_CREATE, "create" },
{ EVM_INS_CALL, "call" },
{ EVM_INS_CALLCODE, "callcode" },
{ EVM_INS_RETURN, "return" },
{ EVM_INS_DELEGATECALL, "delegatecall" },
{ EVM_INS_CALLBLACKBOX, "callblackbox" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_STATICCALL, "staticcall" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_REVERT, "revert" },
{ EVM_INS_INVALID, NULL },
{ EVM_INS_SUICIDE, "suicide" },
};
#endif
const char *EVM_insn_name(csh handle, unsigned int id)
{
#ifndef CAPSTONE_DIET
if (id >= ARR_SIZE(insn_name_maps))
return NULL;
else
return insn_name_maps[id].name;
#else
return NULL;
#endif
}
#ifndef CAPSTONE_DIET
static name_map group_name_maps[] = {
// generic groups
{ EVM_GRP_INVALID, NULL },
{ EVM_GRP_JUMP, "jump" },
// special groups
{ EVM_GRP_MATH, "math" },
{ EVM_GRP_MATH, "math" },
{ EVM_GRP_STACK_WRITE, "stack_write" },
{ EVM_GRP_STACK_READ, "stack_read" },
{ EVM_GRP_MEM_WRITE, "mem_write" },
{ EVM_GRP_MEM_READ, "mem_read" },
{ EVM_GRP_STORE_WRITE, "store_write" },
{ EVM_GRP_STORE_READ, "store_read" },
{ EVM_GRP_HALT, "halt" },
};
#endif
const char *EVM_group_name(csh handle, unsigned int id)
{
#ifndef CAPSTONE_DIET
return id2name(group_name_maps, ARR_SIZE(group_name_maps), id);
#else
return NULL;
#endif
}
#endif
|
the_stack_data/118858.c | // C implementation of #
#include <stdio.h>
__int128 main(){
return -1;
}
|
the_stack_data/79423.c | #include <stdio.h>
int main() {
printf("Hola Mundo1!\n");
return 0;
}
|
the_stack_data/1167801.c | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
} Node;
Node *head;
void addFront(Node *root, int data) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = root->next;
root->next = node;
}
void removeFront(Node *root) {
Node *front = root->next;
root->next = front->next;
free(front);
}
void freeAll(Node *root) {
Node *cur = head->next;
while (cur != NULL) {
Node *next = cur->next;
free(cur);
cur = next;
}
}
void showAll(Node *root){
Node *cur = head->next;
while (cur != NULL) {
printf("%d" , cur->data);
cur= cur->next;
}
}
int main(void) {
head = (Node*) malloc(sizeof(Node));
head->next = NULL;
addFront(head, 2);
addFront(head ,1);
addFront(head, 7);
addFront(head, 9);
addFront(head, 8);
removeFront(head);
showAll(head);
freeAll(head);
return 0;
} |
the_stack_data/154826769.c | /* ************************************************************************** */
/* */
/* :::::::: */
/* ft_memccpy.c :+: :+: */
/* +:+ */
/* By: anijssen <[email protected]> +#+ */
/* +#+ */
/* Created: 2019/10/30 12:48:13 by anijssen #+# #+# */
/* Updated: 2019/11/13 07:01:10 by anijssen ######## odam.nl */
/* */
/* ************************************************************************** */
#include <stddef.h>
void *ft_memccpy(void *dst, const void *src, int c, size_t n)
{
size_t i;
unsigned char *p1;
unsigned char *p2;
p1 = (unsigned char *)src;
p2 = (unsigned char *)dst;
i = 0;
while (i < n)
{
p2[i] = p1[i];
if (p1[i] == (unsigned char)c)
return (p2 + i + 1);
i++;
}
return (NULL);
}
|
the_stack_data/51373.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern int __VERIFIER_nondet_int(void);
/* Generated by CIL v. 1.3.7 */
/* print_CIL_Input is true */
struct JoinPoint {
void **(*fp)(struct JoinPoint * ) ;
void **args ;
int argsCount ;
char const **argsType ;
void *(*arg)(int , struct JoinPoint * ) ;
char const *(*argType)(int , struct JoinPoint * ) ;
void **retValue ;
char const *retType ;
char const *funcName ;
char const *targetName ;
char const *fileName ;
char const *kind ;
void *excep_return ;
};
struct __UTAC__CFLOW_FUNC {
int (*func)(int , int ) ;
int val ;
struct __UTAC__CFLOW_FUNC *next ;
};
struct __UTAC__EXCEPTION {
void *jumpbuf ;
unsigned long long prtValue ;
int pops ;
struct __UTAC__CFLOW_FUNC *cflowfuncs ;
};
typedef unsigned int size_t;
struct __ACC__ERR {
void *v ;
struct __ACC__ERR *next ;
};
#pragma merger(0,"scenario.i","")
void bigMacCall(void) ;
void cleanup(void) ;
void test(void)
{
{
{
bigMacCall();
cleanup();
}
return;
}
}
#pragma merger(0,"Floor.i","")
int isFloorCalling(int floorID ) ;
void resetCallOnFloor(int floorID ) ;
void callOnFloor(int floorID ) ;
int isPersonOnFloor(int person , int floor ) ;
void initPersonOnFloor(int person , int floor ) ;
void removePersonFromFloor(int person , int floor ) ;
int isTopFloor(int floorID ) ;
void initFloors(void) ;
int calls_0 ;
int calls_1 ;
int calls_2 ;
int calls_3 ;
int calls_4 ;
int personOnFloor_0_0 ;
int personOnFloor_0_1 ;
int personOnFloor_0_2 ;
int personOnFloor_0_3 ;
int personOnFloor_0_4 ;
int personOnFloor_1_0 ;
int personOnFloor_1_1 ;
int personOnFloor_1_2 ;
int personOnFloor_1_3 ;
int personOnFloor_1_4 ;
int personOnFloor_2_0 ;
int personOnFloor_2_1 ;
int personOnFloor_2_2 ;
int personOnFloor_2_3 ;
int personOnFloor_2_4 ;
int personOnFloor_3_0 ;
int personOnFloor_3_1 ;
int personOnFloor_3_2 ;
int personOnFloor_3_3 ;
int personOnFloor_3_4 ;
int personOnFloor_4_0 ;
int personOnFloor_4_1 ;
int personOnFloor_4_2 ;
int personOnFloor_4_3 ;
int personOnFloor_4_4 ;
int personOnFloor_5_0 ;
int personOnFloor_5_1 ;
int personOnFloor_5_2 ;
int personOnFloor_5_3 ;
int personOnFloor_5_4 ;
void initFloors(void)
{
{
calls_0 = 0;
calls_1 = 0;
calls_2 = 0;
calls_3 = 0;
calls_4 = 0;
personOnFloor_0_0 = 0;
personOnFloor_0_1 = 0;
personOnFloor_0_2 = 0;
personOnFloor_0_3 = 0;
personOnFloor_0_4 = 0;
personOnFloor_1_0 = 0;
personOnFloor_1_1 = 0;
personOnFloor_1_2 = 0;
personOnFloor_1_3 = 0;
personOnFloor_1_4 = 0;
personOnFloor_2_0 = 0;
personOnFloor_2_1 = 0;
personOnFloor_2_2 = 0;
personOnFloor_2_3 = 0;
personOnFloor_2_4 = 0;
personOnFloor_3_0 = 0;
personOnFloor_3_1 = 0;
personOnFloor_3_2 = 0;
personOnFloor_3_3 = 0;
personOnFloor_3_4 = 0;
personOnFloor_4_0 = 0;
personOnFloor_4_1 = 0;
personOnFloor_4_2 = 0;
personOnFloor_4_3 = 0;
personOnFloor_4_4 = 0;
personOnFloor_5_0 = 0;
personOnFloor_5_1 = 0;
personOnFloor_5_2 = 0;
personOnFloor_5_3 = 0;
personOnFloor_5_4 = 0;
return;
}
}
int isFloorCalling(int floorID )
{ int retValue_acc ;
{
if (floorID == 0) {
retValue_acc = calls_0;
return (retValue_acc);
} else {
if (floorID == 1) {
retValue_acc = calls_1;
return (retValue_acc);
} else {
if (floorID == 2) {
retValue_acc = calls_2;
return (retValue_acc);
} else {
if (floorID == 3) {
retValue_acc = calls_3;
return (retValue_acc);
} else {
if (floorID == 4) {
retValue_acc = calls_4;
return (retValue_acc);
} else {
}
}
}
}
}
retValue_acc = 0;
return (retValue_acc);
return (retValue_acc);
}
}
void resetCallOnFloor(int floorID )
{
{
if (floorID == 0) {
calls_0 = 0;
} else {
if (floorID == 1) {
calls_1 = 0;
} else {
if (floorID == 2) {
calls_2 = 0;
} else {
if (floorID == 3) {
calls_3 = 0;
} else {
if (floorID == 4) {
calls_4 = 0;
} else {
}
}
}
}
}
return;
}
}
void callOnFloor(int floorID )
{
{
if (floorID == 0) {
calls_0 = 1;
} else {
if (floorID == 1) {
calls_1 = 1;
} else {
if (floorID == 2) {
calls_2 = 1;
} else {
if (floorID == 3) {
calls_3 = 1;
} else {
if (floorID == 4) {
calls_4 = 1;
} else {
}
}
}
}
}
return;
}
}
int isPersonOnFloor(int person , int floor )
{ int retValue_acc ;
{
if (floor == 0) {
if (person == 0) {
retValue_acc = personOnFloor_0_0;
return (retValue_acc);
} else {
if (person == 1) {
retValue_acc = personOnFloor_1_0;
return (retValue_acc);
} else {
if (person == 2) {
retValue_acc = personOnFloor_2_0;
return (retValue_acc);
} else {
if (person == 3) {
retValue_acc = personOnFloor_3_0;
return (retValue_acc);
} else {
if (person == 4) {
retValue_acc = personOnFloor_4_0;
return (retValue_acc);
} else {
if (person == 5) {
retValue_acc = personOnFloor_5_0;
return (retValue_acc);
} else {
}
}
}
}
}
}
} else {
if (floor == 1) {
if (person == 0) {
retValue_acc = personOnFloor_0_1;
return (retValue_acc);
} else {
if (person == 1) {
retValue_acc = personOnFloor_1_1;
return (retValue_acc);
} else {
if (person == 2) {
retValue_acc = personOnFloor_2_1;
return (retValue_acc);
} else {
if (person == 3) {
retValue_acc = personOnFloor_3_1;
return (retValue_acc);
} else {
if (person == 4) {
retValue_acc = personOnFloor_4_1;
return (retValue_acc);
} else {
if (person == 5) {
retValue_acc = personOnFloor_5_1;
return (retValue_acc);
} else {
}
}
}
}
}
}
} else {
if (floor == 2) {
if (person == 0) {
retValue_acc = personOnFloor_0_2;
return (retValue_acc);
} else {
if (person == 1) {
retValue_acc = personOnFloor_1_2;
return (retValue_acc);
} else {
if (person == 2) {
retValue_acc = personOnFloor_2_2;
return (retValue_acc);
} else {
if (person == 3) {
retValue_acc = personOnFloor_3_2;
return (retValue_acc);
} else {
if (person == 4) {
retValue_acc = personOnFloor_4_2;
return (retValue_acc);
} else {
if (person == 5) {
retValue_acc = personOnFloor_5_2;
return (retValue_acc);
} else {
}
}
}
}
}
}
} else {
if (floor == 3) {
if (person == 0) {
retValue_acc = personOnFloor_0_3;
return (retValue_acc);
} else {
if (person == 1) {
retValue_acc = personOnFloor_1_3;
return (retValue_acc);
} else {
if (person == 2) {
retValue_acc = personOnFloor_2_3;
return (retValue_acc);
} else {
if (person == 3) {
retValue_acc = personOnFloor_3_3;
return (retValue_acc);
} else {
if (person == 4) {
retValue_acc = personOnFloor_4_3;
return (retValue_acc);
} else {
if (person == 5) {
retValue_acc = personOnFloor_5_3;
return (retValue_acc);
} else {
}
}
}
}
}
}
} else {
if (floor == 4) {
if (person == 0) {
retValue_acc = personOnFloor_0_4;
return (retValue_acc);
} else {
if (person == 1) {
retValue_acc = personOnFloor_1_4;
return (retValue_acc);
} else {
if (person == 2) {
retValue_acc = personOnFloor_2_4;
return (retValue_acc);
} else {
if (person == 3) {
retValue_acc = personOnFloor_3_4;
return (retValue_acc);
} else {
if (person == 4) {
retValue_acc = personOnFloor_4_4;
return (retValue_acc);
} else {
if (person == 5) {
retValue_acc = personOnFloor_5_4;
return (retValue_acc);
} else {
}
}
}
}
}
}
} else {
}
}
}
}
}
retValue_acc = 0;
return (retValue_acc);
return (retValue_acc);
}
}
void initPersonOnFloor(int person , int floor )
{
{
if (floor == 0) {
if (person == 0) {
personOnFloor_0_0 = 1;
} else {
if (person == 1) {
personOnFloor_1_0 = 1;
} else {
if (person == 2) {
personOnFloor_2_0 = 1;
} else {
if (person == 3) {
personOnFloor_3_0 = 1;
} else {
if (person == 4) {
personOnFloor_4_0 = 1;
} else {
if (person == 5) {
personOnFloor_5_0 = 1;
} else {
}
}
}
}
}
}
} else {
if (floor == 1) {
if (person == 0) {
personOnFloor_0_1 = 1;
} else {
if (person == 1) {
personOnFloor_1_1 = 1;
} else {
if (person == 2) {
personOnFloor_2_1 = 1;
} else {
if (person == 3) {
personOnFloor_3_1 = 1;
} else {
if (person == 4) {
personOnFloor_4_1 = 1;
} else {
if (person == 5) {
personOnFloor_5_1 = 1;
} else {
}
}
}
}
}
}
} else {
if (floor == 2) {
if (person == 0) {
personOnFloor_0_2 = 1;
} else {
if (person == 1) {
personOnFloor_1_2 = 1;
} else {
if (person == 2) {
personOnFloor_2_2 = 1;
} else {
if (person == 3) {
personOnFloor_3_2 = 1;
} else {
if (person == 4) {
personOnFloor_4_2 = 1;
} else {
if (person == 5) {
personOnFloor_5_2 = 1;
} else {
}
}
}
}
}
}
} else {
if (floor == 3) {
if (person == 0) {
personOnFloor_0_3 = 1;
} else {
if (person == 1) {
personOnFloor_1_3 = 1;
} else {
if (person == 2) {
personOnFloor_2_3 = 1;
} else {
if (person == 3) {
personOnFloor_3_3 = 1;
} else {
if (person == 4) {
personOnFloor_4_3 = 1;
} else {
if (person == 5) {
personOnFloor_5_3 = 1;
} else {
}
}
}
}
}
}
} else {
if (floor == 4) {
if (person == 0) {
personOnFloor_0_4 = 1;
} else {
if (person == 1) {
personOnFloor_1_4 = 1;
} else {
if (person == 2) {
personOnFloor_2_4 = 1;
} else {
if (person == 3) {
personOnFloor_3_4 = 1;
} else {
if (person == 4) {
personOnFloor_4_4 = 1;
} else {
if (person == 5) {
personOnFloor_5_4 = 1;
} else {
}
}
}
}
}
}
} else {
}
}
}
}
}
{
callOnFloor(floor);
}
return;
}
}
void removePersonFromFloor(int person , int floor )
{
{
if (floor == 0) {
if (person == 0) {
personOnFloor_0_0 = 0;
} else {
if (person == 1) {
personOnFloor_1_0 = 0;
} else {
if (person == 2) {
personOnFloor_2_0 = 0;
} else {
if (person == 3) {
personOnFloor_3_0 = 0;
} else {
if (person == 4) {
personOnFloor_4_0 = 0;
} else {
if (person == 5) {
personOnFloor_5_0 = 0;
} else {
}
}
}
}
}
}
} else {
if (floor == 1) {
if (person == 0) {
personOnFloor_0_1 = 0;
} else {
if (person == 1) {
personOnFloor_1_1 = 0;
} else {
if (person == 2) {
personOnFloor_2_1 = 0;
} else {
if (person == 3) {
personOnFloor_3_1 = 0;
} else {
if (person == 4) {
personOnFloor_4_1 = 0;
} else {
if (person == 5) {
personOnFloor_5_1 = 0;
} else {
}
}
}
}
}
}
} else {
if (floor == 2) {
if (person == 0) {
personOnFloor_0_2 = 0;
} else {
if (person == 1) {
personOnFloor_1_2 = 0;
} else {
if (person == 2) {
personOnFloor_2_2 = 0;
} else {
if (person == 3) {
personOnFloor_3_2 = 0;
} else {
if (person == 4) {
personOnFloor_4_2 = 0;
} else {
if (person == 5) {
personOnFloor_5_2 = 0;
} else {
}
}
}
}
}
}
} else {
if (floor == 3) {
if (person == 0) {
personOnFloor_0_3 = 0;
} else {
if (person == 1) {
personOnFloor_1_3 = 0;
} else {
if (person == 2) {
personOnFloor_2_3 = 0;
} else {
if (person == 3) {
personOnFloor_3_3 = 0;
} else {
if (person == 4) {
personOnFloor_4_3 = 0;
} else {
if (person == 5) {
personOnFloor_5_3 = 0;
} else {
}
}
}
}
}
}
} else {
if (floor == 4) {
if (person == 0) {
personOnFloor_0_4 = 0;
} else {
if (person == 1) {
personOnFloor_1_4 = 0;
} else {
if (person == 2) {
personOnFloor_2_4 = 0;
} else {
if (person == 3) {
personOnFloor_3_4 = 0;
} else {
if (person == 4) {
personOnFloor_4_4 = 0;
} else {
if (person == 5) {
personOnFloor_5_4 = 0;
} else {
}
}
}
}
}
}
} else {
}
}
}
}
}
{
resetCallOnFloor(floor);
}
return;
}
}
int isTopFloor(int floorID )
{ int retValue_acc ;
{
retValue_acc = floorID == 4;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"Test.i","")
extern __attribute__((__nothrow__, __noreturn__)) void exit(int __status ) ;
int cleanupTimeShifts = 12;
int get_nondetMinMax07(void)
{ int retValue_acc ;
int nd ;
nd = __VERIFIER_nondet_int();
{
if (nd == 0) {
retValue_acc = 0;
return (retValue_acc);
} else {
if (nd == 1) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (nd == 2) {
retValue_acc = 2;
return (retValue_acc);
} else {
if (nd == 3) {
retValue_acc = 3;
return (retValue_acc);
} else {
if (nd == 4) {
retValue_acc = 4;
return (retValue_acc);
} else {
if (nd == 5) {
retValue_acc = 5;
return (retValue_acc);
} else {
if (nd == 6) {
retValue_acc = 6;
return (retValue_acc);
} else {
if (nd == 7) {
retValue_acc = 7;
return (retValue_acc);
} else {
{
exit(0);
}
}
}
}
}
}
}
}
}
return (retValue_acc);
}
}
int getOrigin(int person ) ;
void bobCall(void)
{ int tmp ;
{
{
tmp = getOrigin(0);
initPersonOnFloor(0, tmp);
}
return;
}
}
void aliceCall(void)
{ int tmp ;
{
{
tmp = getOrigin(1);
initPersonOnFloor(1, tmp);
}
return;
}
}
void angelinaCall(void)
{ int tmp ;
{
{
tmp = getOrigin(2);
initPersonOnFloor(2, tmp);
}
return;
}
}
void chuckCall(void)
{ int tmp ;
{
{
tmp = getOrigin(3);
initPersonOnFloor(3, tmp);
}
return;
}
}
void monicaCall(void)
{ int tmp ;
{
{
tmp = getOrigin(4);
initPersonOnFloor(4, tmp);
}
return;
}
}
void bigMacCall(void)
{ int tmp ;
{
{
tmp = getOrigin(5);
initPersonOnFloor(5, tmp);
}
return;
}
}
void timeShift(void) ;
void threeTS(void)
{
{
{
timeShift();
timeShift();
timeShift();
}
return;
}
}
int isIdle(void) ;
int isBlocked(void) ;
void cleanup(void)
{ int i ;
int tmp ;
int tmp___0 ;
int __cil_tmp4 ;
{
{
timeShift();
i = 0;
}
{
while (1) {
while_0_continue: /* CIL Label */ ;
{
__cil_tmp4 = cleanupTimeShifts - 1;
if (i < __cil_tmp4) {
{
tmp___0 = isBlocked();
}
if (tmp___0 != 1) {
} else {
goto while_0_break;
}
} else {
goto while_0_break;
}
}
{
tmp = isIdle();
}
if (tmp) {
return;
} else {
{
timeShift();
}
}
i = i + 1;
}
while_0_break: /* CIL Label */ ;
}
return;
}
}
void initTopDown(void) ;
void initBottomUp(void) ;
void randomSequenceOfActions(void)
{ int maxLength ;
int tmp ;
int counter ;
int action ;
int tmp___0 ;
int origin ;
int tmp___1 ;
int tmp___2 ;
{
{
maxLength = 4;
tmp = __VERIFIER_nondet_int();
}
if (tmp) {
{
initTopDown();
}
} else {
{
initBottomUp();
}
}
counter = 0;
{
while (1) {
while_1_continue: /* CIL Label */ ;
if (counter < maxLength) {
} else {
goto while_1_break;
}
{
counter = counter + 1;
tmp___0 = get_nondetMinMax07();
action = tmp___0;
}
if (action < 6) {
{
tmp___1 = getOrigin(action);
origin = tmp___1;
initPersonOnFloor(action, origin);
}
} else {
if (action == 6) {
{
timeShift();
}
} else {
if (action == 7) {
{
timeShift();
timeShift();
timeShift();
}
} else {
}
}
}
{
tmp___2 = isBlocked();
}
if (tmp___2) {
return;
} else {
}
}
while_1_break: /* CIL Label */ ;
}
{
cleanup();
}
return;
}
}
void runTest_Simple(void)
{
{
{
bigMacCall();
angelinaCall();
cleanup();
}
return;
}
}
void Specification1(void)
{
{
{
bigMacCall();
angelinaCall();
cleanup();
}
return;
}
}
void Specification2(void)
{
{
{
bigMacCall();
cleanup();
}
return;
}
}
void Specification3(void)
{
{
{
bobCall();
timeShift();
timeShift();
timeShift();
timeShift();
timeShift();
bobCall();
cleanup();
}
return;
}
}
void setup(void)
{
{
return;
}
}
void __utac_acc__Specification9_spec__1(void) ;
void __utac_acc__Specification9_spec__4(void) ;
void runTest(void)
{
{
{
__utac_acc__Specification9_spec__1();
test();
__utac_acc__Specification9_spec__4();
}
return;
}
}
void select_helpers(void) ;
void select_features(void) ;
int valid_product(void) ;
int main(void)
{ int retValue_acc ;
int tmp ;
{
{
select_helpers();
select_features();
tmp = valid_product();
}
if (tmp) {
{
setup();
runTest();
}
} else {
}
retValue_acc = 0;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"Elevator.i","")
extern int printf(char const * __restrict __format , ...) ;
int getDestination(int person ) ;
void enterElevator(int p ) ;
void printState(void) ;
int isEmpty(void) ;
int isAnyLiftButtonPressed(void) ;
int buttonForFloorIsPressed(int floorID ) ;
int areDoorsOpen(void) ;
int getCurrentFloorID(void) ;
int currentHeading = 1;
int currentFloorID = 0;
int persons_0 ;
int persons_1 ;
int persons_2 ;
int persons_3 ;
int persons_4 ;
int persons_5 ;
int doorState = 1;
int floorButtons_0 ;
int floorButtons_1 ;
int floorButtons_2 ;
int floorButtons_3 ;
int floorButtons_4 ;
void initTopDown(void)
{
{
{
currentFloorID = 4;
currentHeading = 0;
floorButtons_0 = 0;
floorButtons_1 = 0;
floorButtons_2 = 0;
floorButtons_3 = 0;
floorButtons_4 = 0;
persons_0 = 0;
persons_1 = 0;
persons_2 = 0;
persons_3 = 0;
persons_4 = 0;
persons_5 = 0;
initFloors();
}
return;
}
}
void initBottomUp(void)
{
{
{
currentFloorID = 0;
currentHeading = 1;
floorButtons_0 = 0;
floorButtons_1 = 0;
floorButtons_2 = 0;
floorButtons_3 = 0;
floorButtons_4 = 0;
persons_0 = 0;
persons_1 = 0;
persons_2 = 0;
persons_3 = 0;
persons_4 = 0;
persons_5 = 0;
initFloors();
}
return;
}
}
int isBlocked(void)
{ int retValue_acc ;
{
retValue_acc = 0;
return (retValue_acc);
return (retValue_acc);
}
}
void enterElevator(int p )
{
{
if (p == 0) {
persons_0 = 1;
} else {
if (p == 1) {
persons_1 = 1;
} else {
if (p == 2) {
persons_2 = 1;
} else {
if (p == 3) {
persons_3 = 1;
} else {
if (p == 4) {
persons_4 = 1;
} else {
if (p == 5) {
persons_5 = 1;
} else {
}
}
}
}
}
}
return;
}
}
void leaveElevator__wrappee__base(int p )
{
{
if (p == 0) {
persons_0 = 0;
} else {
if (p == 1) {
persons_1 = 0;
} else {
if (p == 2) {
persons_2 = 0;
} else {
if (p == 3) {
persons_3 = 0;
} else {
if (p == 4) {
persons_4 = 0;
} else {
if (p == 5) {
persons_5 = 0;
} else {
}
}
}
}
}
}
return;
}
}
void leaveElevator(int p )
{ int tmp ;
{
{
leaveElevator__wrappee__base(p);
tmp = isEmpty();
}
if (tmp) {
floorButtons_0 = 0;
floorButtons_1 = 0;
floorButtons_2 = 0;
floorButtons_3 = 0;
floorButtons_4 = 0;
} else {
}
return;
}
}
void __utac_acc__Specification9_spec__2(int floor ) ;
void pressInLiftFloorButton(int floorID )
{ int __utac__ad__arg1 ;
{
{
__utac__ad__arg1 = floorID;
__utac_acc__Specification9_spec__2(__utac__ad__arg1);
}
if (floorID == 0) {
floorButtons_0 = 1;
} else {
if (floorID == 1) {
floorButtons_1 = 1;
} else {
if (floorID == 2) {
floorButtons_2 = 1;
} else {
if (floorID == 3) {
floorButtons_3 = 1;
} else {
if (floorID == 4) {
floorButtons_4 = 1;
} else {
}
}
}
}
}
return;
}
}
void resetFloorButton(int floorID )
{
{
if (floorID == 0) {
floorButtons_0 = 0;
} else {
if (floorID == 1) {
floorButtons_1 = 0;
} else {
if (floorID == 2) {
floorButtons_2 = 0;
} else {
if (floorID == 3) {
floorButtons_3 = 0;
} else {
if (floorID == 4) {
floorButtons_4 = 0;
} else {
}
}
}
}
}
return;
}
}
int getCurrentFloorID(void)
{ int retValue_acc ;
{
retValue_acc = currentFloorID;
return (retValue_acc);
return (retValue_acc);
}
}
int areDoorsOpen(void)
{ int retValue_acc ;
{
retValue_acc = doorState;
return (retValue_acc);
return (retValue_acc);
}
}
int buttonForFloorIsPressed(int floorID )
{ int retValue_acc ;
{
if (floorID == 0) {
retValue_acc = floorButtons_0;
return (retValue_acc);
} else {
if (floorID == 1) {
retValue_acc = floorButtons_1;
return (retValue_acc);
} else {
if (floorID == 2) {
retValue_acc = floorButtons_2;
return (retValue_acc);
} else {
if (floorID == 3) {
retValue_acc = floorButtons_3;
return (retValue_acc);
} else {
if (floorID == 4) {
retValue_acc = floorButtons_4;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
}
}
}
}
return (retValue_acc);
}
}
int getCurrentHeading(void)
{ int retValue_acc ;
{
retValue_acc = currentHeading;
return (retValue_acc);
return (retValue_acc);
}
}
int isEmpty(void)
{ int retValue_acc ;
{
if (persons_0 == 1) {
retValue_acc = 0;
return (retValue_acc);
} else {
if (persons_1 == 1) {
retValue_acc = 0;
return (retValue_acc);
} else {
if (persons_2 == 1) {
retValue_acc = 0;
return (retValue_acc);
} else {
if (persons_3 == 1) {
retValue_acc = 0;
return (retValue_acc);
} else {
if (persons_4 == 1) {
retValue_acc = 0;
return (retValue_acc);
} else {
if (persons_5 == 1) {
retValue_acc = 0;
return (retValue_acc);
} else {
}
}
}
}
}
}
retValue_acc = 1;
return (retValue_acc);
return (retValue_acc);
}
}
int anyStopRequested(void)
{ int retValue_acc ;
int tmp ;
int tmp___0 ;
int tmp___1 ;
int tmp___2 ;
int tmp___3 ;
{
{
tmp___3 = isFloorCalling(0);
}
if (tmp___3) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (floorButtons_0) {
retValue_acc = 1;
return (retValue_acc);
} else {
{
tmp___2 = isFloorCalling(1);
}
if (tmp___2) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (floorButtons_1) {
retValue_acc = 1;
return (retValue_acc);
} else {
{
tmp___1 = isFloorCalling(2);
}
if (tmp___1) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (floorButtons_2) {
retValue_acc = 1;
return (retValue_acc);
} else {
{
tmp___0 = isFloorCalling(3);
}
if (tmp___0) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (floorButtons_3) {
retValue_acc = 1;
return (retValue_acc);
} else {
{
tmp = isFloorCalling(4);
}
if (tmp) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (floorButtons_4) {
retValue_acc = 1;
return (retValue_acc);
} else {
}
}
}
}
}
}
}
}
}
}
retValue_acc = 0;
return (retValue_acc);
return (retValue_acc);
}
}
int isIdle(void)
{ int retValue_acc ;
int tmp ;
{
{
tmp = anyStopRequested();
retValue_acc = tmp == 0;
}
return (retValue_acc);
return (retValue_acc);
}
}
int stopRequestedInDirection(int dir , int respectFloorCalls , int respectInLiftCalls )
{ int retValue_acc ;
int tmp ;
int tmp___0 ;
int tmp___1 ;
int tmp___2 ;
int tmp___3 ;
int tmp___4 ;
int tmp___5 ;
int tmp___6 ;
int tmp___7 ;
int tmp___8 ;
int tmp___9 ;
{
if (dir == 1) {
{
tmp = isTopFloor(currentFloorID);
}
if (tmp) {
retValue_acc = 0;
return (retValue_acc);
} else {
}
if (currentFloorID < 0) {
if (respectFloorCalls) {
{
tmp___4 = isFloorCalling(0);
}
if (tmp___4) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___16;
}
} else {
goto _L___16;
}
} else {
_L___16: /* CIL Label */
if (currentFloorID < 0) {
if (respectInLiftCalls) {
if (floorButtons_0) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___14;
}
} else {
goto _L___14;
}
} else {
_L___14: /* CIL Label */
if (currentFloorID < 1) {
if (respectFloorCalls) {
{
tmp___3 = isFloorCalling(1);
}
if (tmp___3) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___12;
}
} else {
goto _L___12;
}
} else {
_L___12: /* CIL Label */
if (currentFloorID < 1) {
if (respectInLiftCalls) {
if (floorButtons_1) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___10;
}
} else {
goto _L___10;
}
} else {
_L___10: /* CIL Label */
if (currentFloorID < 2) {
if (respectFloorCalls) {
{
tmp___2 = isFloorCalling(2);
}
if (tmp___2) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___8;
}
} else {
goto _L___8;
}
} else {
_L___8: /* CIL Label */
if (currentFloorID < 2) {
if (respectInLiftCalls) {
if (floorButtons_2) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___6;
}
} else {
goto _L___6;
}
} else {
_L___6: /* CIL Label */
if (currentFloorID < 3) {
if (respectFloorCalls) {
{
tmp___1 = isFloorCalling(3);
}
if (tmp___1) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___4;
}
} else {
goto _L___4;
}
} else {
_L___4: /* CIL Label */
if (currentFloorID < 3) {
if (respectInLiftCalls) {
if (floorButtons_3) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___2;
}
} else {
goto _L___2;
}
} else {
_L___2: /* CIL Label */
if (currentFloorID < 4) {
if (respectFloorCalls) {
{
tmp___0 = isFloorCalling(4);
}
if (tmp___0) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___0;
}
} else {
goto _L___0;
}
} else {
_L___0: /* CIL Label */
if (currentFloorID < 4) {
if (respectInLiftCalls) {
if (floorButtons_4) {
retValue_acc = 1;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
} else {
retValue_acc = 0;
return (retValue_acc);
}
} else {
retValue_acc = 0;
return (retValue_acc);
}
}
}
}
}
}
}
}
}
}
} else {
if (currentFloorID == 0) {
retValue_acc = 0;
return (retValue_acc);
} else {
}
if (currentFloorID > 0) {
if (respectFloorCalls) {
{
tmp___9 = isFloorCalling(0);
}
if (tmp___9) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___34;
}
} else {
goto _L___34;
}
} else {
_L___34: /* CIL Label */
if (currentFloorID > 0) {
if (respectInLiftCalls) {
if (floorButtons_0) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___32;
}
} else {
goto _L___32;
}
} else {
_L___32: /* CIL Label */
if (currentFloorID > 1) {
if (respectFloorCalls) {
{
tmp___8 = isFloorCalling(1);
}
if (tmp___8) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___30;
}
} else {
goto _L___30;
}
} else {
_L___30: /* CIL Label */
if (currentFloorID > 1) {
if (respectInLiftCalls) {
if (floorButtons_1) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___28;
}
} else {
goto _L___28;
}
} else {
_L___28: /* CIL Label */
if (currentFloorID > 2) {
if (respectFloorCalls) {
{
tmp___7 = isFloorCalling(2);
}
if (tmp___7) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___26;
}
} else {
goto _L___26;
}
} else {
_L___26: /* CIL Label */
if (currentFloorID > 2) {
if (respectInLiftCalls) {
if (floorButtons_2) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___24;
}
} else {
goto _L___24;
}
} else {
_L___24: /* CIL Label */
if (currentFloorID > 3) {
if (respectFloorCalls) {
{
tmp___6 = isFloorCalling(3);
}
if (tmp___6) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___22;
}
} else {
goto _L___22;
}
} else {
_L___22: /* CIL Label */
if (currentFloorID > 3) {
if (respectInLiftCalls) {
if (floorButtons_3) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___20;
}
} else {
goto _L___20;
}
} else {
_L___20: /* CIL Label */
if (currentFloorID > 4) {
if (respectFloorCalls) {
{
tmp___5 = isFloorCalling(4);
}
if (tmp___5) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___18;
}
} else {
goto _L___18;
}
} else {
_L___18: /* CIL Label */
if (currentFloorID > 4) {
if (respectInLiftCalls) {
if (floorButtons_4) {
retValue_acc = 1;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
} else {
retValue_acc = 0;
return (retValue_acc);
}
} else {
retValue_acc = 0;
return (retValue_acc);
}
}
}
}
}
}
}
}
}
}
}
return (retValue_acc);
}
}
int isAnyLiftButtonPressed(void)
{ int retValue_acc ;
{
if (floorButtons_0) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (floorButtons_1) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (floorButtons_2) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (floorButtons_3) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (floorButtons_4) {
retValue_acc = 1;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
}
}
}
}
return (retValue_acc);
}
}
void continueInDirection(int dir )
{ int tmp ;
{
currentHeading = dir;
if (currentHeading == 1) {
{
tmp = isTopFloor(currentFloorID);
}
if (tmp) {
currentHeading = 0;
} else {
}
} else {
if (currentFloorID == 0) {
currentHeading = 1;
} else {
}
}
if (currentHeading == 1) {
currentFloorID = currentFloorID + 1;
} else {
currentFloorID = currentFloorID - 1;
}
return;
}
}
int stopRequestedAtCurrentFloor(void)
{ int retValue_acc ;
int tmp ;
int tmp___0 ;
{
{
tmp___0 = isFloorCalling(currentFloorID);
}
if (tmp___0) {
retValue_acc = 1;
return (retValue_acc);
} else {
{
tmp = buttonForFloorIsPressed(currentFloorID);
}
if (tmp) {
retValue_acc = 1;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
}
return (retValue_acc);
}
}
int getReverseHeading(int ofHeading )
{ int retValue_acc ;
{
if (ofHeading == 0) {
retValue_acc = 1;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
return (retValue_acc);
}
}
void processWaitingOnFloor(int floorID )
{ int tmp ;
int tmp___0 ;
int tmp___1 ;
int tmp___2 ;
int tmp___3 ;
int tmp___4 ;
int tmp___5 ;
int tmp___6 ;
int tmp___7 ;
int tmp___8 ;
int tmp___9 ;
int tmp___10 ;
{
{
tmp___0 = isPersonOnFloor(0, floorID);
}
if (tmp___0) {
{
removePersonFromFloor(0, floorID);
tmp = getDestination(0);
pressInLiftFloorButton(tmp);
enterElevator(0);
}
} else {
}
{
tmp___2 = isPersonOnFloor(1, floorID);
}
if (tmp___2) {
{
removePersonFromFloor(1, floorID);
tmp___1 = getDestination(1);
pressInLiftFloorButton(tmp___1);
enterElevator(1);
}
} else {
}
{
tmp___4 = isPersonOnFloor(2, floorID);
}
if (tmp___4) {
{
removePersonFromFloor(2, floorID);
tmp___3 = getDestination(2);
pressInLiftFloorButton(tmp___3);
enterElevator(2);
}
} else {
}
{
tmp___6 = isPersonOnFloor(3, floorID);
}
if (tmp___6) {
{
removePersonFromFloor(3, floorID);
tmp___5 = getDestination(3);
pressInLiftFloorButton(tmp___5);
enterElevator(3);
}
} else {
}
{
tmp___8 = isPersonOnFloor(4, floorID);
}
if (tmp___8) {
{
removePersonFromFloor(4, floorID);
tmp___7 = getDestination(4);
pressInLiftFloorButton(tmp___7);
enterElevator(4);
}
} else {
}
{
tmp___10 = isPersonOnFloor(5, floorID);
}
if (tmp___10) {
{
removePersonFromFloor(5, floorID);
tmp___9 = getDestination(5);
pressInLiftFloorButton(tmp___9);
enterElevator(5);
}
} else {
}
{
resetCallOnFloor(floorID);
}
return;
}
}
void __utac_acc__Specification9_spec__3(void) ;
void timeShift(void)
{ int tmp ;
int tmp___0 ;
int tmp___1 ;
int tmp___2 ;
int tmp___3 ;
int tmp___4 ;
int tmp___5 ;
int tmp___6 ;
int tmp___7 ;
int tmp___8 ;
int tmp___9 ;
{
{
tmp___9 = stopRequestedAtCurrentFloor();
}
if (tmp___9) {
doorState = 1;
if (persons_0) {
{
tmp = getDestination(0);
}
if (tmp == currentFloorID) {
{
leaveElevator(0);
}
} else {
}
} else {
}
if (persons_1) {
{
tmp___0 = getDestination(1);
}
if (tmp___0 == currentFloorID) {
{
leaveElevator(1);
}
} else {
}
} else {
}
if (persons_2) {
{
tmp___1 = getDestination(2);
}
if (tmp___1 == currentFloorID) {
{
leaveElevator(2);
}
} else {
}
} else {
}
if (persons_3) {
{
tmp___2 = getDestination(3);
}
if (tmp___2 == currentFloorID) {
{
leaveElevator(3);
}
} else {
}
} else {
}
if (persons_4) {
{
tmp___3 = getDestination(4);
}
if (tmp___3 == currentFloorID) {
{
leaveElevator(4);
}
} else {
}
} else {
}
if (persons_5) {
{
tmp___4 = getDestination(5);
}
if (tmp___4 == currentFloorID) {
{
leaveElevator(5);
}
} else {
}
} else {
}
{
processWaitingOnFloor(currentFloorID);
resetFloorButton(currentFloorID);
}
} else {
if (doorState == 1) {
doorState = 0;
} else {
}
{
tmp___8 = stopRequestedInDirection(currentHeading, 1, 1);
}
if (tmp___8) {
{
continueInDirection(currentHeading);
}
} else {
{
tmp___6 = getReverseHeading(currentHeading);
tmp___7 = stopRequestedInDirection(tmp___6, 1, 1);
}
if (tmp___7) {
{
tmp___5 = getReverseHeading(currentHeading);
continueInDirection(tmp___5);
}
} else {
{
continueInDirection(currentHeading);
}
}
}
}
{
__utac_acc__Specification9_spec__3();
}
return;
}
}
void printState(void)
{ int tmp ;
int tmp___0 ;
int tmp___1 ;
int tmp___2 ;
int tmp___3 ;
char const * __restrict __cil_tmp6 ;
char const * __restrict __cil_tmp7 ;
char const * __restrict __cil_tmp8 ;
char const * __restrict __cil_tmp9 ;
char const * __restrict __cil_tmp10 ;
char const * __restrict __cil_tmp11 ;
char const * __restrict __cil_tmp12 ;
char const * __restrict __cil_tmp13 ;
char const * __restrict __cil_tmp14 ;
char const * __restrict __cil_tmp15 ;
char const * __restrict __cil_tmp16 ;
char const * __restrict __cil_tmp17 ;
char const * __restrict __cil_tmp18 ;
char const * __restrict __cil_tmp19 ;
char const * __restrict __cil_tmp20 ;
char const * __restrict __cil_tmp21 ;
char const * __restrict __cil_tmp22 ;
char const * __restrict __cil_tmp23 ;
char const * __restrict __cil_tmp24 ;
char const * __restrict __cil_tmp25 ;
char const * __restrict __cil_tmp26 ;
{
{
__cil_tmp6 = (char const * __restrict )"Elevator ";
printf(__cil_tmp6);
}
if (doorState) {
{
__cil_tmp7 = (char const * __restrict )"[_]";
printf(__cil_tmp7);
}
} else {
{
__cil_tmp8 = (char const * __restrict )"[] ";
printf(__cil_tmp8);
}
}
{
__cil_tmp9 = (char const * __restrict )" at ";
printf(__cil_tmp9);
__cil_tmp10 = (char const * __restrict )"%i";
printf(__cil_tmp10, currentFloorID);
__cil_tmp11 = (char const * __restrict )" heading ";
printf(__cil_tmp11);
}
if (currentHeading) {
{
__cil_tmp12 = (char const * __restrict )"up";
printf(__cil_tmp12);
}
} else {
{
__cil_tmp13 = (char const * __restrict )"down";
printf(__cil_tmp13);
}
}
{
__cil_tmp14 = (char const * __restrict )" IL_p:";
printf(__cil_tmp14);
}
if (floorButtons_0) {
{
__cil_tmp15 = (char const * __restrict )" %i";
printf(__cil_tmp15, 0);
}
} else {
}
if (floorButtons_1) {
{
__cil_tmp16 = (char const * __restrict )" %i";
printf(__cil_tmp16, 1);
}
} else {
}
if (floorButtons_2) {
{
__cil_tmp17 = (char const * __restrict )" %i";
printf(__cil_tmp17, 2);
}
} else {
}
if (floorButtons_3) {
{
__cil_tmp18 = (char const * __restrict )" %i";
printf(__cil_tmp18, 3);
}
} else {
}
if (floorButtons_4) {
{
__cil_tmp19 = (char const * __restrict )" %i";
printf(__cil_tmp19, 4);
}
} else {
}
{
__cil_tmp20 = (char const * __restrict )" F_p:";
printf(__cil_tmp20);
tmp = isFloorCalling(0);
}
if (tmp) {
{
__cil_tmp21 = (char const * __restrict )" %i";
printf(__cil_tmp21, 0);
}
} else {
}
{
tmp___0 = isFloorCalling(1);
}
if (tmp___0) {
{
__cil_tmp22 = (char const * __restrict )" %i";
printf(__cil_tmp22, 1);
}
} else {
}
{
tmp___1 = isFloorCalling(2);
}
if (tmp___1) {
{
__cil_tmp23 = (char const * __restrict )" %i";
printf(__cil_tmp23, 2);
}
} else {
}
{
tmp___2 = isFloorCalling(3);
}
if (tmp___2) {
{
__cil_tmp24 = (char const * __restrict )" %i";
printf(__cil_tmp24, 3);
}
} else {
}
{
tmp___3 = isFloorCalling(4);
}
if (tmp___3) {
{
__cil_tmp25 = (char const * __restrict )" %i";
printf(__cil_tmp25, 4);
}
} else {
}
{
__cil_tmp26 = (char const * __restrict )"\n";
printf(__cil_tmp26);
}
return;
}
}
int existInLiftCallsInDirection(int d )
{ int retValue_acc ;
int i ;
int i___0 ;
{
if (d == 1) {
i = 0;
i = currentFloorID + 1;
{
while (1) {
while_2_continue: /* CIL Label */ ;
if (i < 5) {
} else {
goto while_2_break;
}
if (i == 0) {
if (floorButtons_0) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___2;
}
} else {
_L___2: /* CIL Label */
if (i == 1) {
if (floorButtons_1) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___1;
}
} else {
_L___1: /* CIL Label */
if (i == 2) {
if (floorButtons_2) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___0;
}
} else {
_L___0: /* CIL Label */
if (i == 3) {
if (floorButtons_3) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L;
}
} else {
_L: /* CIL Label */
if (i == 4) {
if (floorButtons_4) {
retValue_acc = 1;
return (retValue_acc);
} else {
}
} else {
}
}
}
}
}
i = i + 1;
}
while_2_break: /* CIL Label */ ;
}
} else {
if (d == 0) {
i___0 = 0;
i___0 = currentFloorID - 1;
{
while (1) {
while_3_continue: /* CIL Label */ ;
if (i___0 >= 0) {
} else {
goto while_3_break;
}
i___0 = currentFloorID + 1;
{
while (1) {
while_4_continue: /* CIL Label */ ;
if (i___0 < 5) {
} else {
goto while_4_break;
}
if (i___0 == 0) {
if (floorButtons_0) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___6;
}
} else {
_L___6: /* CIL Label */
if (i___0 == 1) {
if (floorButtons_1) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___5;
}
} else {
_L___5: /* CIL Label */
if (i___0 == 2) {
if (floorButtons_2) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___4;
}
} else {
_L___4: /* CIL Label */
if (i___0 == 3) {
if (floorButtons_3) {
retValue_acc = 1;
return (retValue_acc);
} else {
goto _L___3;
}
} else {
_L___3: /* CIL Label */
if (i___0 == 4) {
if (floorButtons_4) {
retValue_acc = 1;
return (retValue_acc);
} else {
}
} else {
}
}
}
}
}
i___0 = i___0 + 1;
}
while_4_break: /* CIL Label */ ;
}
i___0 = i___0 - 1;
}
while_3_break: /* CIL Label */ ;
}
} else {
}
}
retValue_acc = 0;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"libacc.i","")
extern __attribute__((__nothrow__, __noreturn__)) void __assert_fail(char const *__assertion ,
char const *__file ,
unsigned int __line ,
char const *__function ) ;
extern __attribute__((__nothrow__)) void *malloc(size_t __size ) __attribute__((__malloc__)) ;
extern __attribute__((__nothrow__)) void free(void *__ptr ) ;
void __utac__exception__cf_handler_set(void *exception , int (*cflow_func)(int ,
int ) ,
int val )
{ struct __UTAC__EXCEPTION *excep ;
struct __UTAC__CFLOW_FUNC *cf ;
void *tmp ;
unsigned long __cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
unsigned long __cil_tmp10 ;
unsigned long __cil_tmp11 ;
unsigned long __cil_tmp12 ;
unsigned long __cil_tmp13 ;
unsigned long __cil_tmp14 ;
int (**mem_15)(int , int ) ;
int *mem_16 ;
struct __UTAC__CFLOW_FUNC **mem_17 ;
struct __UTAC__CFLOW_FUNC **mem_18 ;
struct __UTAC__CFLOW_FUNC **mem_19 ;
{
{
excep = (struct __UTAC__EXCEPTION *)exception;
tmp = malloc(24UL);
cf = (struct __UTAC__CFLOW_FUNC *)tmp;
mem_15 = (int (**)(int , int ))cf;
*mem_15 = cflow_func;
__cil_tmp7 = (unsigned long )cf;
__cil_tmp8 = __cil_tmp7 + 8;
mem_16 = (int *)__cil_tmp8;
*mem_16 = val;
__cil_tmp9 = (unsigned long )cf;
__cil_tmp10 = __cil_tmp9 + 16;
__cil_tmp11 = (unsigned long )excep;
__cil_tmp12 = __cil_tmp11 + 24;
mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp10;
mem_18 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp12;
*mem_17 = *mem_18;
__cil_tmp13 = (unsigned long )excep;
__cil_tmp14 = __cil_tmp13 + 24;
mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14;
*mem_19 = cf;
}
return;
}
}
void __utac__exception__cf_handler_free(void *exception )
{ struct __UTAC__EXCEPTION *excep ;
struct __UTAC__CFLOW_FUNC *cf ;
struct __UTAC__CFLOW_FUNC *tmp ;
unsigned long __cil_tmp5 ;
unsigned long __cil_tmp6 ;
struct __UTAC__CFLOW_FUNC *__cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
unsigned long __cil_tmp10 ;
unsigned long __cil_tmp11 ;
void *__cil_tmp12 ;
unsigned long __cil_tmp13 ;
unsigned long __cil_tmp14 ;
struct __UTAC__CFLOW_FUNC **mem_15 ;
struct __UTAC__CFLOW_FUNC **mem_16 ;
struct __UTAC__CFLOW_FUNC **mem_17 ;
{
excep = (struct __UTAC__EXCEPTION *)exception;
__cil_tmp5 = (unsigned long )excep;
__cil_tmp6 = __cil_tmp5 + 24;
mem_15 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6;
cf = *mem_15;
{
while (1) {
while_5_continue: /* CIL Label */ ;
{
__cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0;
__cil_tmp8 = (unsigned long )__cil_tmp7;
__cil_tmp9 = (unsigned long )cf;
if (__cil_tmp9 != __cil_tmp8) {
} else {
goto while_5_break;
}
}
{
tmp = cf;
__cil_tmp10 = (unsigned long )cf;
__cil_tmp11 = __cil_tmp10 + 16;
mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp11;
cf = *mem_16;
__cil_tmp12 = (void *)tmp;
free(__cil_tmp12);
}
}
while_5_break: /* CIL Label */ ;
}
__cil_tmp13 = (unsigned long )excep;
__cil_tmp14 = __cil_tmp13 + 24;
mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14;
*mem_17 = (struct __UTAC__CFLOW_FUNC *)0;
return;
}
}
void __utac__exception__cf_handler_reset(void *exception )
{ struct __UTAC__EXCEPTION *excep ;
struct __UTAC__CFLOW_FUNC *cf ;
unsigned long __cil_tmp5 ;
unsigned long __cil_tmp6 ;
struct __UTAC__CFLOW_FUNC *__cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
int (*__cil_tmp10)(int , int ) ;
unsigned long __cil_tmp11 ;
unsigned long __cil_tmp12 ;
int __cil_tmp13 ;
unsigned long __cil_tmp14 ;
unsigned long __cil_tmp15 ;
struct __UTAC__CFLOW_FUNC **mem_16 ;
int (**mem_17)(int , int ) ;
int *mem_18 ;
struct __UTAC__CFLOW_FUNC **mem_19 ;
{
excep = (struct __UTAC__EXCEPTION *)exception;
__cil_tmp5 = (unsigned long )excep;
__cil_tmp6 = __cil_tmp5 + 24;
mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6;
cf = *mem_16;
{
while (1) {
while_6_continue: /* CIL Label */ ;
{
__cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0;
__cil_tmp8 = (unsigned long )__cil_tmp7;
__cil_tmp9 = (unsigned long )cf;
if (__cil_tmp9 != __cil_tmp8) {
} else {
goto while_6_break;
}
}
{
mem_17 = (int (**)(int , int ))cf;
__cil_tmp10 = *mem_17;
__cil_tmp11 = (unsigned long )cf;
__cil_tmp12 = __cil_tmp11 + 8;
mem_18 = (int *)__cil_tmp12;
__cil_tmp13 = *mem_18;
(*__cil_tmp10)(4, __cil_tmp13);
__cil_tmp14 = (unsigned long )cf;
__cil_tmp15 = __cil_tmp14 + 16;
mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp15;
cf = *mem_19;
}
}
while_6_break: /* CIL Label */ ;
}
{
__utac__exception__cf_handler_free(exception);
}
return;
}
}
void *__utac__error_stack_mgt(void *env , int mode , int count ) ;
static struct __ACC__ERR *head = (struct __ACC__ERR *)0;
void *__utac__error_stack_mgt(void *env , int mode , int count )
{ void *retValue_acc ;
struct __ACC__ERR *new ;
void *tmp ;
struct __ACC__ERR *temp ;
struct __ACC__ERR *next ;
void *excep ;
unsigned long __cil_tmp10 ;
unsigned long __cil_tmp11 ;
unsigned long __cil_tmp12 ;
unsigned long __cil_tmp13 ;
void *__cil_tmp14 ;
unsigned long __cil_tmp15 ;
unsigned long __cil_tmp16 ;
void *__cil_tmp17 ;
void **mem_18 ;
struct __ACC__ERR **mem_19 ;
struct __ACC__ERR **mem_20 ;
void **mem_21 ;
struct __ACC__ERR **mem_22 ;
void **mem_23 ;
void **mem_24 ;
{
if (count == 0) {
return (retValue_acc);
} else {
}
if (mode == 0) {
{
tmp = malloc(16UL);
new = (struct __ACC__ERR *)tmp;
mem_18 = (void **)new;
*mem_18 = env;
__cil_tmp10 = (unsigned long )new;
__cil_tmp11 = __cil_tmp10 + 8;
mem_19 = (struct __ACC__ERR **)__cil_tmp11;
*mem_19 = head;
head = new;
retValue_acc = (void *)new;
}
return (retValue_acc);
} else {
}
if (mode == 1) {
temp = head;
{
while (1) {
while_7_continue: /* CIL Label */ ;
if (count > 1) {
} else {
goto while_7_break;
}
{
__cil_tmp12 = (unsigned long )temp;
__cil_tmp13 = __cil_tmp12 + 8;
mem_20 = (struct __ACC__ERR **)__cil_tmp13;
next = *mem_20;
mem_21 = (void **)temp;
excep = *mem_21;
__cil_tmp14 = (void *)temp;
free(__cil_tmp14);
__utac__exception__cf_handler_reset(excep);
temp = next;
count = count - 1;
}
}
while_7_break: /* CIL Label */ ;
}
{
__cil_tmp15 = (unsigned long )temp;
__cil_tmp16 = __cil_tmp15 + 8;
mem_22 = (struct __ACC__ERR **)__cil_tmp16;
head = *mem_22;
mem_23 = (void **)temp;
excep = *mem_23;
__cil_tmp17 = (void *)temp;
free(__cil_tmp17);
__utac__exception__cf_handler_reset(excep);
retValue_acc = excep;
}
return (retValue_acc);
} else {
}
if (mode == 2) {
if (head) {
mem_24 = (void **)head;
retValue_acc = *mem_24;
return (retValue_acc);
} else {
retValue_acc = (void *)0;
return (retValue_acc);
}
} else {
}
return (retValue_acc);
}
}
void *__utac__get_this_arg(int i , struct JoinPoint *this )
{ void *retValue_acc ;
unsigned long __cil_tmp4 ;
unsigned long __cil_tmp5 ;
int __cil_tmp6 ;
int __cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
void **__cil_tmp10 ;
void **__cil_tmp11 ;
int *mem_12 ;
void ***mem_13 ;
{
if (i > 0) {
{
__cil_tmp4 = (unsigned long )this;
__cil_tmp5 = __cil_tmp4 + 16;
mem_12 = (int *)__cil_tmp5;
__cil_tmp6 = *mem_12;
if (i <= __cil_tmp6) {
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
123U, "__utac__get_this_arg");
}
}
}
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
123U, "__utac__get_this_arg");
}
}
__cil_tmp7 = i - 1;
__cil_tmp8 = (unsigned long )this;
__cil_tmp9 = __cil_tmp8 + 8;
mem_13 = (void ***)__cil_tmp9;
__cil_tmp10 = *mem_13;
__cil_tmp11 = __cil_tmp10 + __cil_tmp7;
retValue_acc = *__cil_tmp11;
return (retValue_acc);
return (retValue_acc);
}
}
char const *__utac__get_this_argtype(int i , struct JoinPoint *this )
{ char const *retValue_acc ;
unsigned long __cil_tmp4 ;
unsigned long __cil_tmp5 ;
int __cil_tmp6 ;
int __cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
char const **__cil_tmp10 ;
char const **__cil_tmp11 ;
int *mem_12 ;
char const ***mem_13 ;
{
if (i > 0) {
{
__cil_tmp4 = (unsigned long )this;
__cil_tmp5 = __cil_tmp4 + 16;
mem_12 = (int *)__cil_tmp5;
__cil_tmp6 = *mem_12;
if (i <= __cil_tmp6) {
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
131U, "__utac__get_this_argtype");
}
}
}
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
131U, "__utac__get_this_argtype");
}
}
__cil_tmp7 = i - 1;
__cil_tmp8 = (unsigned long )this;
__cil_tmp9 = __cil_tmp8 + 24;
mem_13 = (char const ***)__cil_tmp9;
__cil_tmp10 = *mem_13;
__cil_tmp11 = __cil_tmp10 + __cil_tmp7;
retValue_acc = *__cil_tmp11;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"Specification9_spec.i","")
void __automaton_fail(void) ;
int floorButtons_spc9_0 ;
int floorButtons_spc9_1 ;
int floorButtons_spc9_2 ;
int floorButtons_spc9_3 ;
int floorButtons_spc9_4 ;
void __utac_acc__Specification9_spec__1(void)
{
{
floorButtons_spc9_0 = 0;
floorButtons_spc9_1 = 0;
floorButtons_spc9_2 = 0;
floorButtons_spc9_3 = 0;
floorButtons_spc9_4 = 0;
return;
}
}
void __utac_acc__Specification9_spec__2(int floor )
{
{
if (floor == 0) {
floorButtons_spc9_0 = 1;
} else {
if (floor == 1) {
floorButtons_spc9_1 = 1;
} else {
if (floor == 2) {
floorButtons_spc9_2 = 1;
} else {
if (floor == 3) {
floorButtons_spc9_3 = 1;
} else {
if (floor == 4) {
floorButtons_spc9_4 = 1;
} else {
}
}
}
}
}
return;
}
}
void __utac_acc__Specification9_spec__3(void)
{ int floor ;
int tmp ;
int tmp___0 ;
int tmp___1 ;
{
{
tmp = getCurrentFloorID();
floor = tmp;
tmp___1 = isEmpty();
}
if (tmp___1) {
floorButtons_spc9_0 = 0;
floorButtons_spc9_1 = 0;
floorButtons_spc9_2 = 0;
floorButtons_spc9_3 = 0;
floorButtons_spc9_4 = 0;
} else {
{
tmp___0 = areDoorsOpen();
}
if (tmp___0) {
if (floor == 0) {
if (floorButtons_spc9_0) {
floorButtons_spc9_0 = 0;
} else {
goto _L___2;
}
} else {
_L___2: /* CIL Label */
if (floor == 1) {
if (floorButtons_spc9_1) {
floorButtons_spc9_1 = 0;
} else {
goto _L___1;
}
} else {
_L___1: /* CIL Label */
if (floor == 2) {
if (floorButtons_spc9_2) {
floorButtons_spc9_2 = 0;
} else {
goto _L___0;
}
} else {
_L___0: /* CIL Label */
if (floor == 3) {
if (floorButtons_spc9_3) {
floorButtons_spc9_3 = 0;
} else {
goto _L;
}
} else {
_L: /* CIL Label */
if (floor == 4) {
if (floorButtons_spc9_4) {
floorButtons_spc9_4 = 0;
} else {
}
} else {
}
}
}
}
}
} else {
}
}
return;
}
}
void __utac_acc__Specification9_spec__4(void)
{
{
if (floorButtons_spc9_0) {
{
__automaton_fail();
}
} else {
if (floorButtons_spc9_1) {
{
__automaton_fail();
}
} else {
if (floorButtons_spc9_2) {
{
__automaton_fail();
}
} else {
if (floorButtons_spc9_3) {
{
__automaton_fail();
}
} else {
if (floorButtons_spc9_4) {
{
__automaton_fail();
}
} else {
}
}
}
}
}
return;
}
}
#pragma merger(0,"Person.i","")
int getWeight(int person ) ;
int getWeight(int person )
{ int retValue_acc ;
{
if (person == 0) {
retValue_acc = 40;
return (retValue_acc);
} else {
if (person == 1) {
retValue_acc = 40;
return (retValue_acc);
} else {
if (person == 2) {
retValue_acc = 40;
return (retValue_acc);
} else {
if (person == 3) {
retValue_acc = 40;
return (retValue_acc);
} else {
if (person == 4) {
retValue_acc = 30;
return (retValue_acc);
} else {
if (person == 5) {
retValue_acc = 150;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
}
}
}
}
}
return (retValue_acc);
}
}
int getOrigin(int person )
{ int retValue_acc ;
{
if (person == 0) {
retValue_acc = 4;
return (retValue_acc);
} else {
if (person == 1) {
retValue_acc = 3;
return (retValue_acc);
} else {
if (person == 2) {
retValue_acc = 2;
return (retValue_acc);
} else {
if (person == 3) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (person == 4) {
retValue_acc = 0;
return (retValue_acc);
} else {
if (person == 5) {
retValue_acc = 1;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
}
}
}
}
}
return (retValue_acc);
}
}
int getDestination(int person )
{ int retValue_acc ;
{
if (person == 0) {
retValue_acc = 0;
return (retValue_acc);
} else {
if (person == 1) {
retValue_acc = 0;
return (retValue_acc);
} else {
if (person == 2) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (person == 3) {
retValue_acc = 3;
return (retValue_acc);
} else {
if (person == 4) {
retValue_acc = 1;
return (retValue_acc);
} else {
if (person == 5) {
retValue_acc = 3;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
}
}
}
}
}
return (retValue_acc);
}
}
#pragma merger(0,"UnitTests.i","")
void spec1(void)
{ int tmp ;
int tmp___0 ;
int i ;
int tmp___1 ;
{
{
initBottomUp();
tmp = getOrigin(5);
initPersonOnFloor(5, tmp);
printState();
tmp___0 = getOrigin(2);
initPersonOnFloor(2, tmp___0);
printState();
i = 0;
}
{
while (1) {
while_8_continue: /* CIL Label */ ;
if (i < cleanupTimeShifts) {
{
tmp___1 = isBlocked();
}
if (tmp___1 != 1) {
} else {
goto while_8_break;
}
} else {
goto while_8_break;
}
{
timeShift();
printState();
i = i + 1;
}
}
while_8_break: /* CIL Label */ ;
}
return;
}
}
void spec14(void)
{ int tmp ;
int tmp___0 ;
int i ;
int tmp___1 ;
{
{
initTopDown();
tmp = getOrigin(5);
initPersonOnFloor(5, tmp);
printState();
timeShift();
timeShift();
timeShift();
timeShift();
tmp___0 = getOrigin(0);
initPersonOnFloor(0, tmp___0);
printState();
i = 0;
}
{
while (1) {
while_9_continue: /* CIL Label */ ;
if (i < cleanupTimeShifts) {
{
tmp___1 = isBlocked();
}
if (tmp___1 != 1) {
} else {
goto while_9_break;
}
} else {
goto while_9_break;
}
{
timeShift();
printState();
i = i + 1;
}
}
while_9_break: /* CIL Label */ ;
}
return;
}
}
#pragma merger(0,"featureselect.i","")
int select_one(void) ;
int select_one(void)
{ int retValue_acc ;
int choice = __VERIFIER_nondet_int();
{
retValue_acc = choice;
return (retValue_acc);
return (retValue_acc);
}
}
void select_features(void)
{
{
return;
}
}
void select_helpers(void)
{
{
return;
}
}
int valid_product(void)
{ int retValue_acc ;
{
retValue_acc = 1;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"wsllib_check.i","")
void __automaton_fail(void)
{
{
ERROR: __VERIFIER_error();
return;
}
}
|
the_stack_data/170452496.c | #include<stdio.h>
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<6;i++){
if(n%2==0)n++;
printf("%d\n",n);
n+=2;
}
return 0;
}
|
the_stack_data/76435.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE_ARRAY 50
#define RANGE_RANDOM_INTEGERS 100
int array[SIZE_ARRAY];
void fillArrayRandomValues();
void insertionSort();
void swap(int *previous, int *next);
int main() {
fillArrayRandomValues();
insertionSort();
for (int i = 0; i < SIZE_ARRAY; i++)
printf("Value: %d\n", array[i]);
return 0;
}
void fillArrayRandomValues() {
srand(time(NULL));
for (int i = 0; i < SIZE_ARRAY; i++)
array[i] = rand() % RANGE_RANDOM_INTEGERS;
}
void insertionSort() {
for (int i = 1; i < SIZE_ARRAY; i++)
for(int j = i; j > 0 && array[j - 1] > array[j]; j--)
swap(&array[j], &array[j - 1]);
}
void swap(int *previous, int *next) {
int aux = *previous;
*previous = *next;
*next = aux;
} |
the_stack_data/9274.c | // SPDX-License-Identifier: GPL-2.0
#ifdef HAVE_EVENTFD_SUPPORT
/*
* Copyright (C) 2018 Davidlohr Bueso.
*
* This program benchmarks concurrent epoll_wait(2) monitoring multiple
* file descriptors under one or two load balancing models. The first,
* and default, is the single/combined queueing (which refers to a single
* epoll instance for N worker threads):
*
* |---> [worker A]
* |---> [worker B]
* [combined queue] .---> [worker C]
* |---> [worker D]
* |---> [worker E]
*
* While the second model, enabled via --multiq option, uses multiple
* queueing (which refers to one epoll instance per worker). For example,
* short lived tcp connections in a high throughput httpd server will
* ditribute the accept()'ing connections across CPUs. In this case each
* worker does a limited amount of processing.
*
* [queue A] ---> [worker]
* [queue B] ---> [worker]
* [queue C] ---> [worker]
* [queue D] ---> [worker]
* [queue E] ---> [worker]
*
* Naturally, the single queue will enforce more concurrency on the epoll
* instance, and can therefore scale poorly compared to multiple queues.
* However, this is a benchmark raw data and must be taken with a grain of
* salt when choosing how to make use of sys_epoll.
* Each thread has a number of private, nonblocking file descriptors,
* referred to as fdmap. A writer thread will constantly be writing to
* the fdmaps of all threads, minimizing each threads's chances of
* epoll_wait not finding any ready read events and blocking as this
* is not what we want to stress. The size of the fdmap can be adjusted
* by the user; enlarging the value will increase the chances of
* epoll_wait(2) blocking as the lineal writer thread will take "longer",
* at least at a high level.
*
* Note that because fds are private to each thread, this workload does
* not stress scenarios where multiple tasks are awoken per ready IO; ie:
* EPOLLEXCLUSIVE semantics.
*
* The end result/metric is throughput: number of ops/second where an
* operation consists of:
*
* epoll_wait(2) + [others]
*
* ... where [others] is the cost of re-adding the fd (EPOLLET),
* or rearming it (EPOLLONESHOT).
*
*
* The purpose of this is program is that it be useful for measuring
* kernel related changes to the sys_epoll, and not comparing different
* IO polling methods, for example. Hence everything is very adhoc and
* outputs raw microbenchmark numbers. Also this uses eventfd, similar
* tools tend to use pipes or sockets, but the result is the same.
*/
/* For the CLR_() macros */
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <inttypes.h>
#include <signal.h>
#include <stdlib.h>
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/types.h>
#include <perf/cpumap.h>
#include "../util/stat.h"
#include <subcmd/parse-options.h>
#include "bench.h"
#include <err.h>
#define printinfo(fmt, arg...) \
do { if (__verbose) { printf(fmt, ## arg); fflush(stdout); } } while (0)
static unsigned int nthreads = 0;
static unsigned int nsecs = 8;
static bool wdone, done, __verbose, randomize, nonblocking;
/*
* epoll related shared variables.
*/
/* Maximum number of nesting allowed inside epoll sets */
#define EPOLL_MAXNESTS 4
static int epollfd;
static int *epollfdp;
static bool noaffinity;
static unsigned int nested = 0;
static bool et; /* edge-trigger */
static bool oneshot;
static bool multiq; /* use an epoll instance per thread */
/* amount of fds to monitor, per thread */
static unsigned int nfds = 64;
static pthread_mutex_t thread_lock;
static unsigned int threads_starting;
static struct stats throughput_stats;
static pthread_cond_t thread_parent, thread_worker;
struct worker {
int tid;
int epollfd; /* for --multiq */
pthread_t thread;
unsigned long ops;
int *fdmap;
};
static const struct option options[] = {
/* general benchmark options */
OPT_UINTEGER('t', "threads", &nthreads, "Specify amount of threads"),
OPT_UINTEGER('r', "runtime", &nsecs, "Specify runtime (in seconds)"),
OPT_UINTEGER('f', "nfds", &nfds, "Specify amount of file descriptors to monitor for each thread"),
OPT_BOOLEAN( 'n', "noaffinity", &noaffinity, "Disables CPU affinity"),
OPT_BOOLEAN('R', "randomize", &randomize, "Enable random write behaviour (default is lineal)"),
OPT_BOOLEAN( 'v', "verbose", &__verbose, "Verbose mode"),
/* epoll specific options */
OPT_BOOLEAN( 'm', "multiq", &multiq, "Use multiple epoll instances (one per thread)"),
OPT_BOOLEAN( 'B', "nonblocking", &nonblocking, "Nonblocking epoll_wait(2) behaviour"),
OPT_UINTEGER( 'N', "nested", &nested, "Nesting level epoll hierarchy (default is 0, no nesting)"),
OPT_BOOLEAN( 'S', "oneshot", &oneshot, "Use EPOLLONESHOT semantics"),
OPT_BOOLEAN( 'E', "edge", &et, "Use Edge-triggered interface (default is LT)"),
OPT_END()
};
static const char * const bench_epoll_wait_usage[] = {
"perf bench epoll wait <options>",
NULL
};
/*
* Arrange the N elements of ARRAY in random order.
* Only effective if N is much smaller than RAND_MAX;
* if this may not be the case, use a better random
* number generator. -- Ben Pfaff.
*/
static void shuffle(void *array, size_t n, size_t size)
{
char *carray = array;
void *aux;
size_t i;
if (n <= 1)
return;
aux = calloc(1, size);
if (!aux)
err(EXIT_FAILURE, "calloc");
for (i = 1; i < n; ++i) {
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
j *= size;
memcpy(aux, &carray[j], size);
memcpy(&carray[j], &carray[i*size], size);
memcpy(&carray[i*size], aux, size);
}
free(aux);
}
static void *workerfn(void *arg)
{
int fd, ret, r;
struct worker *w = (struct worker *) arg;
unsigned long ops = w->ops;
struct epoll_event ev;
uint64_t val;
int to = nonblocking? 0 : -1;
int efd = multiq ? w->epollfd : epollfd;
pthread_mutex_lock(&thread_lock);
threads_starting--;
if (!threads_starting)
pthread_cond_signal(&thread_parent);
pthread_cond_wait(&thread_worker, &thread_lock);
pthread_mutex_unlock(&thread_lock);
do {
/*
* Block undefinitely waiting for the IN event.
* In order to stress the epoll_wait(2) syscall,
* call it event per event, instead of a larger
* batch (max)limit.
*/
do {
ret = epoll_wait(efd, &ev, 1, to);
} while (ret < 0 && errno == EINTR);
if (ret < 0)
err(EXIT_FAILURE, "epoll_wait");
fd = ev.data.fd;
do {
r = read(fd, &val, sizeof(val));
} while (!done && (r < 0 && errno == EAGAIN));
if (et) {
ev.events = EPOLLIN | EPOLLET;
ret = epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ev);
}
if (oneshot) {
/* rearm the file descriptor with a new event mask */
ev.events |= EPOLLIN | EPOLLONESHOT;
ret = epoll_ctl(efd, EPOLL_CTL_MOD, fd, &ev);
}
ops++;
} while (!done);
if (multiq)
close(w->epollfd);
w->ops = ops;
return NULL;
}
static void nest_epollfd(struct worker *w)
{
unsigned int i;
struct epoll_event ev;
int efd = multiq ? w->epollfd : epollfd;
if (nested > EPOLL_MAXNESTS)
nested = EPOLL_MAXNESTS;
epollfdp = calloc(nested, sizeof(*epollfdp));
if (!epollfdp)
err(EXIT_FAILURE, "calloc");
for (i = 0; i < nested; i++) {
epollfdp[i] = epoll_create(1);
if (epollfdp[i] < 0)
err(EXIT_FAILURE, "epoll_create");
}
ev.events = EPOLLHUP; /* anything */
ev.data.u64 = i; /* any number */
for (i = nested - 1; i; i--) {
if (epoll_ctl(epollfdp[i - 1], EPOLL_CTL_ADD,
epollfdp[i], &ev) < 0)
err(EXIT_FAILURE, "epoll_ctl");
}
if (epoll_ctl(efd, EPOLL_CTL_ADD, *epollfdp, &ev) < 0)
err(EXIT_FAILURE, "epoll_ctl");
}
static void toggle_done(int sig __maybe_unused,
siginfo_t *info __maybe_unused,
void *uc __maybe_unused)
{
/* inform all threads that we're done for the day */
done = true;
gettimeofday(&bench__end, NULL);
timersub(&bench__end, &bench__start, &bench__runtime);
}
static void print_summary(void)
{
unsigned long avg = avg_stats(&throughput_stats);
double stddev = stddev_stats(&throughput_stats);
printf("\nAveraged %ld operations/sec (+- %.2f%%), total secs = %d\n",
avg, rel_stddev_stats(stddev, avg),
(int)bench__runtime.tv_sec);
}
static int do_threads(struct worker *worker, struct perf_cpu_map *cpu)
{
pthread_attr_t thread_attr, *attrp = NULL;
cpu_set_t cpuset;
unsigned int i, j;
int ret = 0, events = EPOLLIN;
if (oneshot)
events |= EPOLLONESHOT;
if (et)
events |= EPOLLET;
printinfo("starting worker/consumer %sthreads%s\n",
noaffinity ? "":"CPU affinity ",
nonblocking ? " (nonblocking)":"");
if (!noaffinity)
pthread_attr_init(&thread_attr);
for (i = 0; i < nthreads; i++) {
struct worker *w = &worker[i];
if (multiq) {
w->epollfd = epoll_create(1);
if (w->epollfd < 0)
err(EXIT_FAILURE, "epoll_create");
if (nested)
nest_epollfd(w);
}
w->tid = i;
w->fdmap = calloc(nfds, sizeof(int));
if (!w->fdmap)
return 1;
for (j = 0; j < nfds; j++) {
int efd = multiq ? w->epollfd : epollfd;
struct epoll_event ev;
w->fdmap[j] = eventfd(0, EFD_NONBLOCK);
if (w->fdmap[j] < 0)
err(EXIT_FAILURE, "eventfd");
ev.data.fd = w->fdmap[j];
ev.events = events;
ret = epoll_ctl(efd, EPOLL_CTL_ADD,
w->fdmap[j], &ev);
if (ret < 0)
err(EXIT_FAILURE, "epoll_ctl");
}
if (!noaffinity) {
CPU_ZERO(&cpuset);
CPU_SET(cpu->map[i % cpu->nr], &cpuset);
ret = pthread_attr_setaffinity_np(&thread_attr, sizeof(cpu_set_t), &cpuset);
if (ret)
err(EXIT_FAILURE, "pthread_attr_setaffinity_np");
attrp = &thread_attr;
}
ret = pthread_create(&w->thread, attrp, workerfn,
(void *)(struct worker *) w);
if (ret)
err(EXIT_FAILURE, "pthread_create");
}
if (!noaffinity)
pthread_attr_destroy(&thread_attr);
return ret;
}
static void *writerfn(void *p)
{
struct worker *worker = p;
size_t i, j, iter;
const uint64_t val = 1;
ssize_t sz;
struct timespec ts = { .tv_sec = 0,
.tv_nsec = 500 };
printinfo("starting writer-thread: doing %s writes ...\n",
randomize? "random":"lineal");
for (iter = 0; !wdone; iter++) {
if (randomize) {
shuffle((void *)worker, nthreads, sizeof(*worker));
}
for (i = 0; i < nthreads; i++) {
struct worker *w = &worker[i];
if (randomize) {
shuffle((void *)w->fdmap, nfds, sizeof(int));
}
for (j = 0; j < nfds; j++) {
do {
sz = write(w->fdmap[j], &val, sizeof(val));
} while (!wdone && (sz < 0 && errno == EAGAIN));
}
}
nanosleep(&ts, NULL);
}
printinfo("exiting writer-thread (total full-loops: %zd)\n", iter);
return NULL;
}
static int cmpworker(const void *p1, const void *p2)
{
struct worker *w1 = (struct worker *) p1;
struct worker *w2 = (struct worker *) p2;
return w1->tid > w2->tid;
}
int bench_epoll_wait(int argc, const char **argv)
{
int ret = 0;
struct sigaction act;
unsigned int i;
struct worker *worker = NULL;
struct perf_cpu_map *cpu;
pthread_t wthread;
struct rlimit rl, prevrl;
argc = parse_options(argc, argv, options, bench_epoll_wait_usage, 0);
if (argc) {
usage_with_options(bench_epoll_wait_usage, options);
exit(EXIT_FAILURE);
}
memset(&act, 0, sizeof(act));
sigfillset(&act.sa_mask);
act.sa_sigaction = toggle_done;
sigaction(SIGINT, &act, NULL);
cpu = perf_cpu_map__new(NULL);
if (!cpu)
goto errmem;
/* a single, main epoll instance */
if (!multiq) {
epollfd = epoll_create(1);
if (epollfd < 0)
err(EXIT_FAILURE, "epoll_create");
/*
* Deal with nested epolls, if any.
*/
if (nested)
nest_epollfd(NULL);
}
printinfo("Using %s queue model\n", multiq ? "multi" : "single");
printinfo("Nesting level(s): %d\n", nested);
/* default to the number of CPUs and leave one for the writer pthread */
if (!nthreads)
nthreads = cpu->nr - 1;
worker = calloc(nthreads, sizeof(*worker));
if (!worker) {
goto errmem;
}
if (getrlimit(RLIMIT_NOFILE, &prevrl))
err(EXIT_FAILURE, "getrlimit");
rl.rlim_cur = rl.rlim_max = nfds * nthreads * 2 + 50;
printinfo("Setting RLIMIT_NOFILE rlimit from %" PRIu64 " to: %" PRIu64 "\n",
(uint64_t)prevrl.rlim_max, (uint64_t)rl.rlim_max);
if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
err(EXIT_FAILURE, "setrlimit");
printf("Run summary [PID %d]: %d threads monitoring%s on "
"%d file-descriptors for %d secs.\n\n",
getpid(), nthreads, oneshot ? " (EPOLLONESHOT semantics)": "", nfds, nsecs);
init_stats(&throughput_stats);
pthread_mutex_init(&thread_lock, NULL);
pthread_cond_init(&thread_parent, NULL);
pthread_cond_init(&thread_worker, NULL);
threads_starting = nthreads;
gettimeofday(&bench__start, NULL);
do_threads(worker, cpu);
pthread_mutex_lock(&thread_lock);
while (threads_starting)
pthread_cond_wait(&thread_parent, &thread_lock);
pthread_cond_broadcast(&thread_worker);
pthread_mutex_unlock(&thread_lock);
/*
* At this point the workers should be blocked waiting for read events
* to become ready. Launch the writer which will constantly be writing
* to each thread's fdmap.
*/
ret = pthread_create(&wthread, NULL, writerfn,
(void *)(struct worker *) worker);
if (ret)
err(EXIT_FAILURE, "pthread_create");
sleep(nsecs);
toggle_done(0, NULL, NULL);
printinfo("main thread: toggling done\n");
sleep(1); /* meh */
wdone = true;
ret = pthread_join(wthread, NULL);
if (ret)
err(EXIT_FAILURE, "pthread_join");
/* cleanup & report results */
pthread_cond_destroy(&thread_parent);
pthread_cond_destroy(&thread_worker);
pthread_mutex_destroy(&thread_lock);
/* sort the array back before reporting */
if (randomize)
qsort(worker, nthreads, sizeof(struct worker), cmpworker);
for (i = 0; i < nthreads; i++) {
unsigned long t = bench__runtime.tv_sec > 0 ?
worker[i].ops / bench__runtime.tv_sec : 0;
update_stats(&throughput_stats, t);
if (nfds == 1)
printf("[thread %2d] fdmap: %p [ %04ld ops/sec ]\n",
worker[i].tid, &worker[i].fdmap[0], t);
else
printf("[thread %2d] fdmap: %p ... %p [ %04ld ops/sec ]\n",
worker[i].tid, &worker[i].fdmap[0],
&worker[i].fdmap[nfds-1], t);
}
print_summary();
close(epollfd);
return ret;
errmem:
err(EXIT_FAILURE, "calloc");
}
#endif // HAVE_EVENTFD_SUPPORT
|
the_stack_data/206394335.c | /* Exercise 5-2 */
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int fd = open("test", O_WRONLY | O_APPEND);
if (lseek(fd, 0, SEEK_SET) == -1) {
perror("seek error");
exit(EXIT_FAILURE);
}
if (write(fd, "hello", 5) == -1) {
perror("write error");
exit(EXIT_FAILURE);
}
close(fd);
exit(EXIT_SUCCESS);
}
|
the_stack_data/167331064.c | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct binary_node {
int x, y;
struct binary_node* left;
struct binary_node* right;
} binary_node;
void free_binary_node(binary_node* t) {
if (t != 0) {
free_binary_node(t->left);
free_binary_node(t->right);
free(t);
}
}
bool point_lt(int x1, int y1, int x2, int y2) {
if ((x1 < x2) || (x1 == x2 && y1 <= y2)) {
return true;
}
return false;
}
bool point_gt(int x1, int y1, int x2, int y2) {
if ((x1 > x2) || (x1 == x2 && y1 >= y2)) {
return true;
}
return false;
}
void insert(binary_node** tree, int x, int y) {
if (*tree == 0) {
*tree = (binary_node*) malloc(sizeof(binary_node));
(*tree)->x = x;
(*tree)->y = y;
(*tree)->left = 0;
(*tree)->right = 0;
}
else if (point_lt(x, y, (*tree)->x, (*tree)->y)) {
insert(&(*tree)->left, x, y);
}
else if (point_gt(x, y, (*tree)->x, (*tree)->y)) {
insert(&(*tree)->right, x, y);
}
}
bool search(binary_node** tree, int x, int y) {
if ((*tree)->x == x && (*tree)->y == y) {
return true;
}
else if (point_lt(x, y, (*tree)->x, (*tree)->y) && (*tree)->left != 0) {
return search(&(*tree)->left, x, y);
}
else if (point_gt(x, y, (*tree)->x, (*tree)->y) && (*tree)->right != 0) {
return search(&(*tree)->right, x, y);
}
else {
return false;
}
}
int main(int argc, char** argv) {
FILE* input = fopen("3-1.txt", "r");
if (!input) {
perror("Error opening input file!");
exit(EXIT_FAILURE);
}
binary_node *tree = 0;
int x = 0, y = 0;
insert(&tree, x, y);
int total_presents_delivered = 1;
char line_buffer[512];
while (fgets(line_buffer, sizeof line_buffer, input) != NULL) {
char* buf = line_buffer;
while(*buf) {
switch (*buf) {
case '<':
x--;
break;
case '>':
x++;
break;
case '^':
y--;
break;
case 'v':
y++;
break;
}
if (!search(&tree, x, y)) {
insert(&tree, x, y);
total_presents_delivered++;
}
++buf;
}
}
free_binary_node(tree);
if (ferror(input)) {
perror("Error reading input line");
fprintf(stderr, "fgets() failed in file %s at line %d\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
printf("Santa delivered %d presents\n", total_presents_delivered);
}
|
the_stack_data/430755.c | /*
FRAME_LCD.C
Tile Source File.
Info:
Form : All tiles as one unit.
Format : Gameboy 4 color.
Counter : None.
Tile size : 8 x 8
Tiles : 0 to 8
This file was generated by GBTD v0.5
*/
/* Start of tile array. */
const unsigned char frame_lcd[] =
{
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1F,
0x00,0x1F,0x00,0x18,0x00,0x18,0x00,0x18,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,
0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF8,
0x00,0xF8,0x00,0x18,0x00,0x18,0x00,0x18,
0x00,0x18,0x00,0x18,0x00,0x18,0x00,0x18,
0x00,0x18,0x00,0x18,0x00,0x18,0x00,0x18,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x18,0x00,0x18,0x00,0x18,0x00,0x18,
0x00,0x18,0x00,0x18,0x00,0x18,0x00,0x18,
0x00,0x18,0x00,0x18,0x00,0x18,0x00,0x1F,
0x00,0x1F,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,
0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x18,0x00,0x18,0x00,0x18,0x00,0xF8,
0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00
};
/* End of FRAME_LCD.C */
|
the_stack_data/39931.c | #include <stdio.h>
int main(void) {
int x = 100;
printf("dec = %d, oct = %o, hex = %x\n", x, x, x);
printf("dec = %d, oct = %#o, hex = %#x\n", x, x, x);
return 0;
} |
the_stack_data/96173.c | //Matrix multiplication in C language
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
}
|
the_stack_data/1100255.c | #include <stdio.h>
#include <time.h>
#include <stdlib.h>
void construirLabirinto(int** lab,int n){
int i,j;
char colors[] = {'a', 'v','r','l'};
int pattern_p =0;
srand(time(NULL));
for(i=0;i<n;i++){
for(j=0;j<n;j++){
lab[i][j] = rand()%2;
}
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(lab[i][j]==1){
int color = rand()%4;
lab[i][j] = colors[color];
}
}
}
}
void gerarCoordIniciais(int** lab,int* x,int* y,int* x1,int* y1,int n){
// printf("\ngerarCoordIniciais");
srand(time(NULL));
*x = rand()%n;
*y = rand()%n;
while(lab[*y][*x]==0){
*x = rand()%n;
*y = rand()%n;
}
lab[*y][*x] = 88;
*x1 = rand()%n;
*y1 = rand()%n;
while(lab[*y1][*x1]==0 || (*x1 == *x && *y1 == *y)){
*x1 = rand()%n;
*y1 = rand()%n;
}
}
void salvarCoordIniciais(int* x,int* y,int* x1,int* y1,int n){
//
FILE* file = fopen("labirinto.dat","w");
printf("\nCoordIniciais: \nJ&M: %i %i",*y,*x);
printf("\nSaida: %i %i\n",*y1,*x1);
fprintf(file,"%i",n);
fputs("\n",file);
fprintf(file,"%i",*x);
fputs(" ",file);
fprintf(file,"%i",*y);
fputs("\n",file);
fprintf(file,"%i",*x1);
fputs(" ",file);
fprintf(file,"%i",*y1);
fputs("\n",file);
fclose(file);
}
void gerarPadrao(char pattern[]){
srand(time(NULL));
char colors[] = {'a','v','r','l'};
int i;
for(i=0;i<4;i++){
int color = rand()%4;
pattern[i] = colors[color];
}
}
void salvarPadrao(){
FILE* file = fopen("labirinto.dat","a");
char pattern[4];
gerarPadrao(pattern);
printf("Padrao: %s\n",pattern);
int i;
for(i=0;i<5;i++){
fprintf(file,"%c",pattern[i]);
}
fclose(file);
}
void salvarLabirinto(int** lab,int n){
FILE* file = fopen("labirinto.dat","a");
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
fprintf(file,"%i",lab[i][j]);
fputs(" ",file);
}
fputs("\n",file);
}
fclose(file);
}
int main(){
int n;
printf("Digite o tamanho do labirinto: ");
scanf("%i",&n);
int i,j;
int** lab = malloc(n*sizeof(int*));
for(i=0;i<=n;i++){
lab[i] = malloc(sizeof(int));
}
int x,y,x1,y1;
construirLabirinto(lab,n);
gerarCoordIniciais(lab,&x,&y,&x1,&y1,n);
salvarCoordIniciais(&x,&y,&x1,&y1,n);
salvarLabirinto(lab,n);
salvarPadrao();
// system("cls");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(i==y1 && j==x1){
printf("S ");
}else if(lab[i][j]==0){
printf("%i ",lab[i][j]);
}else{
printf("%c ",lab[i][j]);
}
}
printf("\n");
}
return 0;
}
|
the_stack_data/62637780.c | #include <stdio.h>
#include <stdbool.h>
struct _node {
int next: 24;
bool visit;
} map[100000];
int main()
{
int word1, word2, N;
int addr, c, next;
scanf("%d %d %d", &word1, &word2, &N);
for (int i = 0; i < N; ++i) {
scanf("%d %c %d", &addr, &c, &next);
map[addr].next = next;
}
for (addr = word1; addr != -1; addr = map[addr].next)
map[addr].visit = true;
for (addr = word2; addr != -1 && !map[addr].visit; addr = map[addr].next);
printf(addr == -1 ? "%d\n" : "%05d\n", addr);
}
|
the_stack_data/220456752.c | void main()
{
int i = 1, и = -1;
int ident = 32767, идентификатор = -32767;
char en_symbol = 'Z', ру_символ = 'Я';
float pi = 3.14;
struct res
{
int x;
int y;
} hd = { 1280, 720 };
int arr[4] = { 0, 1, 2, 3 };
printid(i);
printid(i);
printid(и);
printid(и);
printf("\n");
printid(ident);
printid(идентификатор);
printid(en_symbol);
printid(ру_символ);
printid(pi);
printid(hd);
printid(arr);
}
|
the_stack_data/86075975.c | /*
* Copyright (c) 1998 Martin Husemann. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* 4. Altered versions must be plainly marked as such, and must not be
* misrepresented as being the original software and/or documentation.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*---------------------------------------------------------------------------
*
* ELSA MicroLink MC/all card specific routines
* --------------------------------------------
*
* $Id: i4b_elsa_mcall.c,v 1.1 1998/12/27 21:46:45 phk Exp $
*
* last edit-date: [Tue Dec 1 07:45:53 1998]
*
* -mh started support for ELSA MC/all
*
*---------------------------------------------------------------------------*/
#ifdef __FreeBSD__
#include "isic.h"
#include "opt_i4b.h"
#else
#define NISIC 1
#endif
#if NISIC > 0 && defined(ELSA_MCALL)
#include <sys/param.h>
#if defined(__FreeBSD__) && __FreeBSD__ >= 3
#include <sys/ioccom.h>
#else
#include <sys/ioctl.h>
#endif
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#ifdef __FreeBSD__
#include <machine/clock.h>
#include <i386/isa/isa_device.h>
#else
#include <machine/bus.h>
#include <sys/device.h>
#endif
#include <sys/socket.h>
#include <net/if.h>
#ifdef __FreeBSD__
#include <machine/i4b_debug.h>
#include <machine/i4b_ioctl.h>
#else
#include <i4b/i4b_debug.h>
#include <i4b/i4b_ioctl.h>
#include <dev/pcmcia/pcmciareg.h>
#include <dev/pcmcia/pcmciavar.h>
#endif
#include <i4b/layer1/i4b_l1.h>
#include <i4b/layer1/i4b_isac.h>
#include <i4b/layer1/i4b_hscx.h>
#include <i4b/layer1/i4b_ipac.h>
#include <i4b/layer1/pcmcia_isic.h>
#ifndef __FreeBSD__
/* PCMCIA support routines */
static u_int8_t elsa_mcall_read_reg __P((struct isic_softc *sc, int what, bus_size_t offs));
static void elsa_mcall_write_reg __P((struct isic_softc *sc, int what, bus_size_t offs, u_int8_t data));
static void elsa_mcall_read_fifo __P((struct isic_softc *sc, int what, void *buf, size_t size));
static void elsa_mcall_write_fifo __P((struct isic_softc *sc, int what, const void *data, size_t size));
#endif
/*---------------------------------------------------------------------------*
* read fifo routines
*---------------------------------------------------------------------------*/
#ifdef __FreeBSD__
static int PCMCIA_IO_BASE = 0; /* ap: XXX hack */
static void
elsa_mcall_read_fifo(void *buf, const void *base, size_t len)
{
}
#else
static void
elsa_mcall_read_fifo(struct isic_softc *sc, int what, void *buf, size_t size)
{
/*
bus_space_tag_t t = sc->sc_maps[0].t;
bus_space_handle_t h = sc->sc_maps[0].h;
*/
}
#endif
/*---------------------------------------------------------------------------*
* write fifo routines
*---------------------------------------------------------------------------*/
#ifdef __FreeBSD__
static void
elsa_mcall_write_fifo(void *base, const void *buf, size_t len)
{
}
#else
static void
elsa_mcall_write_fifo(struct isic_softc *sc, int what, const void *buf, size_t size)
{
/*
bus_space_tag_t t = sc->sc_maps[0].t;
bus_space_handle_t h = sc->sc_maps[0].h;
*/
}
#endif
/*---------------------------------------------------------------------------*
* write register routines
*---------------------------------------------------------------------------*/
#ifdef __FreeBSD__
static void
elsa_mcall_write_reg(u_char *base, u_int offset, u_int v)
{
}
#else
static void
elsa_mcall_write_reg(struct isic_softc *sc, int what, bus_size_t offs, u_int8_t data)
{
/*
bus_space_tag_t t = sc->sc_maps[0].t;
bus_space_handle_t h = sc->sc_maps[0].h;
*/
}
#endif
/*---------------------------------------------------------------------------*
* read register routines
*---------------------------------------------------------------------------*/
#ifdef __FreeBSD__
static u_char
elsa_mcall_read_reg(u_char *base, u_int offset)
{
return 0;
}
#else
static u_int8_t
elsa_mcall_read_reg(struct isic_softc *sc, int what, bus_size_t offs)
{
/*
bus_space_tag_t t = sc->sc_maps[0].t;
bus_space_handle_t h = sc->sc_maps[0].h;
*/
return 0;
}
#endif
#ifdef __FreeBSD__
#else
/*
* XXX - one time only! Some of this has to go into an enable
* function, with apropriate counterpart in disable, so a card
* could be removed an inserted again. But never mind for now,
* this won't work anyway for several reasons (both in NetBSD
* and in I4B).
*/
int
isic_attach_elsamcall(struct pcmcia_isic_softc *psc, struct pcmcia_config_entry *cfe, struct pcmcia_attach_args *pa)
{
struct isic_softc *sc = &psc->sc_isic;
bus_space_tag_t t;
bus_space_handle_t h;
/* Validate config info */
if (cfe->num_memspace != 0)
printf(": unexpected number of memory spaces %d should be 0\n",
cfe->num_memspace);
if (cfe->num_iospace != 1)
printf(": unexpected number of memory spaces %d should be 1\n",
cfe->num_iospace);
/* Allocate pcmcia space */
if (pcmcia_io_alloc(pa->pf, 0, cfe->iospace[0].length,
cfe->iospace[0].length, &psc->sc_pcioh))
printf(": can't allocate i/o space\n");
/* map them */
if (pcmcia_io_map(pa->pf, ((cfe->flags & PCMCIA_CFE_IO16) ?
PCMCIA_WIDTH_IO16 : PCMCIA_WIDTH_IO8), 0,
cfe->iospace[0].length, &psc->sc_pcioh, &psc->sc_io_window)) {
printf(": can't map i/o space\n");
return 0;
}
/* setup card type */
sc->sc_cardtyp = CARD_TYPEP_ELSAMLMCALL;
/* Setup bus space maps */
sc->sc_num_mappings = 1;
MALLOC_MAPS(sc);
/* Copy our handles/tags to the MI maps */
sc->sc_maps[0].t = psc->sc_pcioh.iot;
sc->sc_maps[0].h = psc->sc_pcioh.ioh;
sc->sc_maps[0].offset = 0;
sc->sc_maps[0].size = 0; /* not our mapping */
t = sc->sc_maps[0].t;
h = sc->sc_maps[0].h;
sc->clearirq = NULL;
sc->readreg = elsa_mcall_read_reg;
sc->writereg = elsa_mcall_write_reg;
sc->readfifo = elsa_mcall_read_fifo;
sc->writefifo = elsa_mcall_write_fifo;
/* setup IOM bus type */
sc->sc_bustyp = BUS_TYPE_IOM2;
sc->sc_ipac = 1;
sc->sc_bfifolen = IPAC_BFIFO_LEN;
return 1;
}
#endif
#endif /* NISIC > 0 */
|
the_stack_data/69579.c | #include <stdio.h>
int main()
{
// Addition
/* Declare three integer variables */
int x, y, z;
printf("enter two whole numbers, separated by a space: ");
/* Read two values from the keyboard */
scanf("%d %d",&x,&y);
/* add the two values together and pass the result to z */
z = x + y;
printf("%d + %d = %d\n", x,y,z);
// Multiplication
/* multiply x by 10 and then assign the result to x */
x = x * 10;
printf("The result of x is: %d\n ", x);
return 0;
}
|
the_stack_data/108902.c | #include <stdio.h>
#include <string.h>
#define MAXLEN 3000
#define MAX 200
struct occurance_t
{
long hash;
int count;
};
long hash(char*);
int main()
{
char input[MAXLEN];
int CurrentWord, LastMost=0, CurrentMost, i, count;
struct occurance_t word[MAXLEN];
for(i=0; strcmp(input, "vsmisal")!=0; i++)
{
scanf("%s", input);
if(i==0)
{
if(strcmp(input, "vsmisal")==0)
{
return 0;
}
}
CurrentWord = hash(input);
for (count = 0; count < MAXLEN; count++)
{
if(word[count].hash == CurrentWord)
{
word[count].count++;
break;
}
else
{
if(word[count].hash == 0)
{
word[count].hash = CurrentWord;
word[count].count = 1;
break;
}
}
}
}
for(count = 0; count<i; count++)
{
if(word[count].count > LastMost)
{
LastMost = word[count].count;
CurrentMost = count;
}
}
printf("%d %ld\n", word[CurrentMost].count, word[CurrentMost].hash);
return 0;
}
long hash(char *input)
{
long sum = 42;
int length = strlen(input);
for (int count=0; count<length; count++)
{
if(input[count]!= '\n')
{
sum += input[count]*(count+1);
}
}
return sum;
} |
the_stack_data/20450403.c | // gcc -std=c99 -Wall -lm -fopenmp -o go A1_5.c
#include <stdio.h>
#include <omp.h>
#include <stdlib.h>
void display(int, int *);
void swap(int *, int *);
unsigned long long tick(void)
{
unsigned long long d;
__asm__ __volatile__("rdtsc": "=A"(d));
return d;
}
int main(int argc, char *argv[])
{
int n = 10;
int* v1 = (int *)malloc(n);
int* v2 = (int *)malloc(n);
for (int i = 0; i < n; ++i)
{
v1[i] = rand() % 25; //RAND_MAX;
v2[i] = v1[i];
}
display(n, v1);
display(n, v2);
// unsigned long long start = tick();
// for (int i = n - 1; i > 0; --i)
// {
// int imax = i;
// for (int j = 0; j < i; ++j)
// {
// if (*(v1 + j) > *(v1 + imax))
// imax = j;
// }
// if (imax != i)
// swap(v1 + imax, v1 + i);
// }
// double t_org = (double)(clock() - start);
// #pragma omp for
// for (int i = n - 1; i > 0; --i)
// {
// int imax = i;
// // parallelize this for loop
// #pragma omp critical
// for (int j = 0; j < i; ++j)
// {
// if (*(v2 + j) > *(v2 + imax))
// imax = j;
// }
// if (imax != i)
// swap(v2 + imax, v2 + i);
// }
// double t_omp = (double)(clock() - start - t_org);
// printf("\n ==== ORIGIN ====\n");
// display(n, v1);
// printf("\n ==== OPENMP ====\n");
// display(n, v2);
// printf("Time-origin: %.2f\nTime-openmp: %.2f\n", t_org, t_omp);
free(v1);
free(v2);
return 0;
}
void display(int n, int *v)
{
for (int i = 0; i < n; ++i)
printf("%d\t", v[i]);
printf("\n");
}
void swap(int *x, int *y)
{
int z = *x;
*x = *y;
*y = z;
} |
the_stack_data/286925.c |
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern void __VERIFIER_assume(int);
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
extern int __VERIFIER_nondet_int(void);
int N;
int main()
{
N = __VERIFIER_nondet_int();
if(N <= 0) return 1;
int i;
int sum[1];
int a[N];
sum[0] = 0;
for(i=0; i<N; i++)
{
a[i] = 4;
}
for(i=0; i<N; i++)
{
if(a[i] == 4) {
sum[0] = sum[0] + a[i];
} else {
sum[0] = sum[0] * a[i];
}
}
__VERIFIER_assert(sum[0] == 4*N);
return 1;
}
|
the_stack_data/111079170.c | #include <stdio.h>
int main(void){
int c;
do {
int no;
printf("input a number: "); scanf("%d", &no);
if (no%2)
printf("奇数\n");
else
printf("ou数\n");
printf("要重复一次吗?【0-yes,9-no】"); scanf("%d", &c);
} while (c == 0);
return 0;
}
|
the_stack_data/61074079.c | #include<stdio.h>
#include<math.h>
float f (float x)
{
return (x*x*x-4*x-9);
}
void main()
{
float x,a,b,f1,f2,f3,e=0.00005;
printf("Output \n");
printf("Supply the values of a & b : \n");
scanf("%f %f",&a,&b);
f1=f(a);
f2=f(b);
do
{
x=((a*f2)-(b*f1))/(f2-f1);
f3=f(x);
if(f3<0)
a=x;
else
b=x;
}
while(fabs(f(a)-f(b))>e);
printf("The root = %f",x);
}
|
the_stack_data/147406.c | # include <stdio.h>
# include <string.h>
# include <openssl/err.h>
# include <openssl/evp.h>
static void hexdump(FILE *f, const char *title, const unsigned char *s, int l)
{
int n = 0;
fprintf(f, "%s", title);
for (; n < l; ++n) {
if ((n % 16) == 0)
fprintf(f, "\n%04x", n);
fprintf(f, " %02x", s[n]);
}
fprintf(f, "\n");
}
int main(void)
{
#ifdef EVP_MD_CTRL_TLSTREE
#ifdef EVP_CTRL_TLS1_2_TLSTREE
const unsigned char mac_secret[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
};
const unsigned char enc_key[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const unsigned char full_iv[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
unsigned char seq0[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const unsigned char rec0_header[] = {
0x17, 0x03, 0x03, 0x00, 0x0F
};
const unsigned char data0[15] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
const unsigned char mac0_etl[16] = {
0x75, 0x53, 0x09, 0xCB, 0xC7, 0x3B, 0xB9, 0x49, 0xC5, 0x0E, 0xBB, 0x86, 0x16, 0x0A, 0x0F, 0xEE
};
const unsigned char enc0_etl[31] = {
0xf3, 0x17, 0xa7, 0x1d, 0x3a, 0xce, 0x43, 0x3b, 0x01, 0xd4, 0xe7, 0xd4, 0xef, 0x61, 0xae, 0x00,
0xd5, 0x3b, 0x41, 0x52, 0x7a, 0x26, 0x1e, 0xdf, 0xc2, 0xba, 0x78, 0x57, 0xc1, 0x93, 0x2d
};
unsigned char data0_processed[31];
unsigned char mac0[16];
unsigned char seq63[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F,
};
const unsigned char rec63_header[] = {
0x17, 0x03, 0x03, 0x10, 0x00
};
unsigned char data63[4096];
const unsigned char mac63_etl[16] = {
0x0A, 0x3B, 0xFD, 0x43, 0x0F, 0xCD, 0xD8, 0xD8, 0x5C, 0x96, 0x46, 0x86, 0x81, 0x78, 0x4F, 0x7D
};
const unsigned char enc63_etl_head[32] = {
0x6A, 0x18, 0x38, 0xB0, 0xA0, 0xD5, 0xA0, 0x4D, 0x1F, 0x29, 0x64, 0x89, 0x6D, 0x08, 0x5F, 0xB7,
0xDA, 0x84, 0xD7, 0x76, 0xC3, 0x9F, 0x5C, 0xDC, 0x37, 0x20, 0xB7, 0xB5, 0x59, 0xEF, 0x13, 0x9D
};
const unsigned char enc63_etl_tail[48] = {
0x0A, 0x81, 0x29, 0x9B, 0x35, 0x98, 0x19, 0x5D, 0xD4, 0x51, 0x68, 0xA6, 0x38, 0x50, 0xA7, 0x6E,
0x1A, 0x4F, 0x1E, 0x6D, 0xD5, 0xEF, 0x72, 0x59, 0x3F, 0xAE, 0x76, 0x55, 0x71, 0xEC, 0x37, 0xE7,
0x17, 0xF5, 0xB8, 0x62, 0x85, 0xBB, 0x5B, 0xFD, 0x83, 0xB6, 0x6A, 0xB7, 0x63, 0x86, 0x52, 0x08
};
unsigned char data63_processed[4096+16];
unsigned char mac63[16];
EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
EVP_CIPHER_CTX *enc = NULL;
const EVP_MD *md;
const EVP_CIPHER *ciph;
EVP_PKEY *mac_key;
size_t mac_len;
int i;
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
memset(data63, 0, 4096);
md = EVP_get_digestbynid(NID_grasshopper_mac);
EVP_DigestInit_ex(mdctx, md, NULL);
mac_key = EVP_PKEY_new_mac_key(NID_grasshopper_mac, NULL, mac_secret, 32);
EVP_DigestSignInit(mdctx, NULL, md, NULL, mac_key);
EVP_PKEY_free(mac_key);
EVP_MD_CTX_ctrl(mdctx, EVP_MD_CTRL_TLSTREE, 0, seq0);
EVP_DigestSignUpdate(mdctx, seq0, 8);
EVP_DigestSignUpdate(mdctx, rec0_header, 5);
EVP_DigestSignUpdate(mdctx, data0, 15);
EVP_DigestSignFinal(mdctx, mac0, &mac_len);
EVP_MD_CTX_free(mdctx);
hexdump(stderr, "MAC0 result", mac0, mac_len);
if (memcmp(mac0, mac0_etl, 16) != 0) {
fprintf(stderr, "MAC0 mismatch");
exit(1);
}
ciph = EVP_get_cipherbynid(NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm);
enc = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(enc, ciph, NULL, enc_key, full_iv);
for (i = 7; i >= 0; i--) {
++seq0[i];
if (seq0[i] != 0)
break;
}
EVP_CIPHER_CTX_ctrl(enc, EVP_CTRL_TLS1_2_TLSTREE, 0, seq0);
EVP_Cipher(enc, data0_processed, data0, sizeof(data0));
EVP_Cipher(enc, data0_processed+sizeof(data0), mac0, 16);
hexdump(stderr, "ENC0 result", data0_processed, 31);
if (memcmp(enc0_etl, data0_processed, sizeof(data0_processed)) != 0) {
fprintf(stderr, "ENC0 mismatch");
exit(1);
}
mdctx = EVP_MD_CTX_new();
EVP_DigestInit_ex(mdctx, md, NULL);
mac_key = EVP_PKEY_new_mac_key(NID_grasshopper_mac, NULL, mac_secret, 32);
EVP_DigestSignInit(mdctx, NULL, md, NULL, mac_key);
EVP_PKEY_free(mac_key);
EVP_MD_CTX_ctrl(mdctx, EVP_MD_CTRL_TLSTREE, 0, seq63);
EVP_DigestSignUpdate(mdctx, seq63, 8);
EVP_DigestSignUpdate(mdctx, rec63_header, 5);
EVP_DigestSignUpdate(mdctx, data63, 4096);
EVP_DigestSignFinal(mdctx, mac63, &mac_len);
EVP_MD_CTX_free(mdctx);
hexdump(stderr, "MAC63 result", mac63, mac_len);
if (memcmp(mac63, mac63_etl, 16) != 0) {
fprintf(stderr, "MAC63 mismatch");
exit(1);
}
for (i = 7; i >= 0; i--) {
++seq63[i];
if (seq63[i] != 0)
break;
}
EVP_CIPHER_CTX_ctrl(enc, EVP_CTRL_TLS1_2_TLSTREE, 0, seq63);
EVP_Cipher(enc, data63_processed, data63, sizeof(data63));
EVP_Cipher(enc, data63_processed+sizeof(data63), mac63, 16);
hexdump(stderr, "ENC63 result: head", data63_processed, 32);
if (memcmp(enc63_etl_head, data63_processed, sizeof(enc63_etl_head)) != 0) {
fprintf(stderr, "ENC63 mismatch: head");
exit(1);
}
hexdump(stderr, "ENC63 result: tail", data63_processed+4096+16-48, 48);
if (memcmp(enc63_etl_tail, data63_processed+4096+16-48, sizeof(enc63_etl_tail)) != 0) {
fprintf(stderr, "ENC63 mismatch: tail");
exit(1);
}
#endif
#endif
return 0;
}
|
the_stack_data/26700943.c | /* Copyright (c) 1985-2012, B-Core (UK) Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
FILE *Btmp;
FILE *dotcfile;
int eof_flag;
int c;
char argv3;
char opfile [ 100 ];
char cmd [ 150 ];
#define maxline 10000
char line_arr [ maxline + 1 ];
#define ansiC_header "/* ANSIC header */\n"
#define ansiC_footer "/* end ANSIC header */\n"
#define non_ansiC_header "/* non-ANSIC header */\n"
#define non_ansiC_footer "/* end non-ANSIC header */\n"
void
print_ansiC_op ()
{
int found;
/***
print to ansiC_header
***/
found = 0;
while ( ! found && ! eof_flag ) {
if ( fgets ( line_arr, maxline, dotcfile ) == NULL ) {
eof_flag = 1;
}
if ( ! eof_flag ) {
if ( strcmp ( line_arr, ansiC_header ) == 0 ) {
found = 1;
if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
else {
fputs ( line_arr, Btmp );
}
}
}
/***
print to ansiC_footer
***/
if ( ! eof_flag ) {
found = 0;
while ( ! found ) {
fgets ( line_arr, maxline, dotcfile );
if ( strcmp ( line_arr, ansiC_footer ) == 0 ) {
found = 1;
if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
else {
fputs ( line_arr, Btmp );
}
}
}
/***
remove non-ansiC signature
***/
if ( ! eof_flag ) {
found = 0;
while ( ! found ) {
fgets ( line_arr, maxline, dotcfile );
if ( strcmp ( line_arr, non_ansiC_header ) == 0 ) {
found = 1;
if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
else if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
found = 0;
while ( ! found ) {
fgets ( line_arr, maxline, dotcfile );
if ( strcmp ( line_arr, non_ansiC_footer ) == 0 ) {
found = 1;
if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
else if ( argv3 == '1' ) {
if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
}
c = getc ( dotcfile );
if ( c != '\n' ) {
ungetc ( c, dotcfile );
}
}
}
void
print_non_ansiC_op ()
{
int found;
/***
print to ansiC_header
***/
found = 0;
while ( ! found && ! eof_flag ) {
if ( fgets ( line_arr, maxline, dotcfile ) == NULL ) {
eof_flag = 1;
}
if ( ! eof_flag ) {
if ( strcmp ( line_arr, ansiC_header ) == 0 ) {
found = 1;
if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
else {
fputs ( line_arr, Btmp );
}
}
}
/***
remove to non-ansiC_header
***/
if ( ! eof_flag ) {
found = 0;
while ( ! found ) {
fgets ( line_arr, maxline, dotcfile );
if ( strcmp ( line_arr, non_ansiC_header ) == 0 ) {
found = 1;
if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
else if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
}
/***
print to non_ansiC_footer
***/
if ( ! eof_flag ) {
found = 0;
while ( ! found ) {
fgets ( line_arr, maxline, dotcfile );
if ( strcmp ( line_arr, non_ansiC_footer ) == 0 ) {
found = 1;
if ( argv3 == '1' ) {
fputs ( "\n", Btmp );
}
}
else {
fputs ( line_arr, Btmp );
}
}
c = getc ( dotcfile );
if ( c != '\n' ) {
ungetc ( c, dotcfile );
}
}
}
int
main(argc,argv)
int argc;
char *argv[];
{
strcpy ( opfile, argv [ 1 ] );
strcat ( opfile, ".c" );
argv3 = argv [ 3 ] [ 0 ];
if ( ( Btmp = fopen ( ".Btmp", "w" ) ) == NULL ) {
printf( "\n Can't open .Btmp for writing " );
exit ( 1 );
}
if ( ( dotcfile = fopen ( opfile, "r" ) ) == NULL ) {
printf( "\n Can't open %s for reading\n\n", opfile );
exit ( 1 );
}
eof_flag = 0;
if ( argv [ 2 ] [ 0 ] == '1' ) {
while ( ! eof_flag ) {
print_non_ansiC_op ();
}
}
else {
while ( ! eof_flag ) {
print_ansiC_op ();
}
}
fclose ( Btmp );
fclose ( dotcfile );
strcat ( cmd, "cp .Btmp " );
strcat ( cmd, opfile );
strcat ( cmd, " ; rm -f .Btmp" );
system ( cmd );
return 0;
}
|
the_stack_data/182954312.c | #include <stdio.h> // Libreria estandard.
#include <string.h> // Libreria de manejo de cadenas de caracteres.
#include <stdlib.h>
#include <time.h> // Libreria de random.
#define MAX 50 // Arreglos.
//prototipos
void presentacion(void);
int dificultad(void);
int funcion_ale(void);
char* palabra_basicas(void);
char* palabra_dificil(void);
void guion(char palabra2[MAX],int longitud);
//palabra:String
//letra:Char
//main:void ->int
//el main tendremos dos palabras de tipo array en donde una es la palabra descubierta(palabraD) y la otra es lo mismo que la primera palabra,
//pero en vez de haber letras hay guiones(ppantalla).el main nos pedira una letra que la ingresaremos por teclado,si la letra
//esta en palabraD ,modificaremos ppantalla,si no lo esta nos resta una vida.Si la vida llega a cero el programa se termina y nos mostrara la
//palabra completa,en caso contrario de que ingrese todas las letras correctamente el usuario ganara y se le muestra por pantalla un mensaje
//de felicitaciones.
int main(void){
presentacion();
char *r;
int dif=dificultad(); //guardamos el resultado de dificultad() en una variable de tipo entero.
if (dif == 1){ //si la variable dif es 1 entonces que guarde una palabra de la funcion palabra_basicas en el puntero r.
r=palabra_basicas();
}
else{ //sino que guarde una palabra de la funcion palabra_dificil() en el puntero r.
r=palabra_dificil();
}
char palabraD[MAX]="";
strcat(palabraD,r);
char ppantalla[MAX]=""; //ppantalla es la palabra a descubrir.
int longitud1=strlen(palabraD);
guion(ppantalla,longitud1);
int i;
char letra;//es la variable donde se va a guardar lo ingresado por teclado.
int vida = 5; //la cantidad de vida que tenemos al empezar.
printf(" %s",ppantalla);
while (vida > 0){
int bandera = 0;//inicializacion de la bandera.
printf("\ningrese una letra:"); //pedimos que ingrese una letra.
scanf(" %c",&letra);
for(i = 0; i < MAX ; i++){
if(palabraD[i] == letra){
ppantalla[i]=letra; //agregar la letra en ppantalla en el indice que corresponde.
bandera = 1; // la bandera ahora es igual a 1.
printf(" %s",ppantalla); //nos muestra por pantalla como esta actualmente ppantalla.
}//FIN DEL IF
}//FIN DEL FOR
if ((strcmp(palabraD,ppantalla)) == 0){ //comparamos si palabraD es igual a ppantalla.
printf("\nFelicitaciones!!,la palabra esta completa");//si es igual muestro por pantalla la felicitacion.
break; //ya que se completo la palabra hacemos un break para terminar con el ciclo while.
}
if (bandera == 1){ // si la bander es igual a 1 nos aclara en pantalla que la letra esta en la palabra.
printf("\nla letra esta en la palabra");
}
else{//si no pasa ninguna de las otras condiciones que nos reste una vida.
vida--;
printf("\nla letra no esta en la palabra");
printf("\nustede tiene %d vidas",vida);
}
}//FIN DEL WHILE
if (vida == 0){ //si la vida es igual a cero termina el programa el usuario pierde y nos muestra la palabra .
printf("\nse le acabo las oportunidades de acertar,la palabra era %s",palabraD);
}
return 0;
}
//presentacio: Void -> Void
//lo primero que hace presentacion es imprimir en pantalla el nombre del proyecto,luego le pide al usuario que ingrese su nombre
//y luego le da la bienvenida,por ultimo muestra los modos de juegos que son dos el modo facil y el modo dificil.
void presentacion(void){
char nombre[MAX];
printf("\n\tJuego del ahorcado - Proyecto 02, Programacion II.\n");
printf("\tPor favor, ingrese su nombre:\t");
scanf("%[^\n]",nombre);
printf("\tSaludos %s. Bienvenido al juego del ahorcado.\n",nombre);
printf("\tElegir una de estas opciones:\t\n");
printf("\t\t 1. Nivel Basico.");
printf("\t\t 2. Nivel Avanzado.\n");
}
//dificultad: Void -> Int
//dificultad pide por teclado al usuario que ingrese 1 o 2 ,si es igual a 1 es la dificultad facil y imprime la ayuda correspondiente
//a esta dificultad y me devuelve 1,si es igual a 2 imprime por pantalla que se a elegido la dificultad dificil y devuelve 2.
int dificultad(void){
int ingreso;
printf("\tingreso:\t");
scanf("%d",&ingreso);
if (ingreso == 1){
printf("\tHaz elegido la dificultad: Basica.\n");
printf("\tte damos una ayuda:");
printf("\n\t- Comienza usando vocales.");
printf("\n\t- Recuerda todo el abecedario:");
printf("\n\tA,B,C,D,E,F,G,H,I,J,K,L,M,N,Ñ,O,P,Q,R,S,T,U,V,W,X,Y,Z.\n");
return 1;
}
if (ingreso == 2){
printf("\tHaz elegido la dificultad: Avanzado.\n");
return 2;
}
else{
return 0;
}
}
//funcion_ale: void -> Int
//funcion_ale lo que hace es generar un numero aleatorio del 1 al 6 .
int funcion_ale(void){
int numeroAl;
srand(time(NULL));
numeroAl= 1 + rand() % ((6 + 1) - 1);
return numeroAl;
}
//palabras_basicas: Void -> Char*
//lo que hace la funcion palabra_basica es devolvernos una palabra aleatoria que esto se consigue con un numero aleatorio
//dado de la funcion funcion_ale.
char* palabra_basicas(void){
int numeroAle=funcion_ale();
char *p;
switch (numeroAle){
case 1:
p="perro";
break;
case 2:
p="patricio";
break;
case 3:
p="maiz";
break;
case 4:
p="nuez";
break;
case 5:
p="dory";
break;
default:
p="revista";
break;
}
return p;
}
//palabras_dificil: Void -> Char*
//lo que hace la funcion palabra_dificil es devolvernos una palabra aleatoria que esto se consigue con un numero aleatorio
//dado de la funcion funcion_ale.
char* palabra_dificil(void){
int numeroAlea=funcion_ale();
char *t;
switch (numeroAlea){
case 1:
t="paralelepipedo";
break;
case 2:
t="filantropo";
break;
case 3:
t="misantropia";
break;
case 4:
t="fisioterapeuta";
break;
case 5:
t="Ventriculo";
break;
default:
t="hipotalamo";
break;
}
return t;
}
//guion: String -> Int -> void
//la funcion guion toma una string y una longitud expresado en un entero.
// palabra1 es vacio(""),lo que hace la funcion es concatenar un guion en
//palabra1 y lo guarda esto en su argumento.Para poder concatenar los guiones haremos un for, mientras que un entero i sea
//diferente de la longitud se agregara un guion a palabra1.
//ejemplo:
//entrada:"",4 guarda en memoria a palabra1 como: "----"
void guion(char palabra1[MAX],int longitud){
int i;
for(i=0;i != longitud ;i++){
strcat(palabra1,"-");
}
}
|
the_stack_data/45451378.c | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
// Funcções auxiliares:
void display();
int leitura();
void square();
int main(void)
{
int valor;
system("cls");
setlocale(LC_ALL, "portuguese");
for (display(); valor = leitura(); display())
{
square(valor);
}
printf("\n\n\n");
system("pause");
return 0;
} // end main
void display()
{
printf("\n\tDigite Zero para Sair! ");
printf("\n\tOu Informe um numero inteiro para calcular o seu quadrado: ");
} // end displa
int leitura()
{
int t; // numero digitado pelo usuario para calcular seu quadrado
scanf("%d", &t);
return t;
} // end leitura
void square(int numero)
{
printf("\n\tO Quadrado do numero digitado eh: %d\n", numero * numero); // imprime o quadrado do numero
} // end square |
the_stack_data/145955.c | #include <stdio.h>
int input(char *s,int length);
int main()
{
char buffer[32];
char *b = buffer;
size_t bufsize = 32;
size_t characters;
printf("Type something: ");
characters = getline(&b,&bufsize,stdin);
printf("%zu characters were read.\n",characters);
printf("You typed: '%s'\n",buffer);
return(0);
}
|
the_stack_data/178264483.c | #include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int main(){
int A[10] = {1, 7, 10, 12, 12, 12, 15, 15};
int length = 8;
for(int i = 0; i < length-1; i++){
int count = 1;
if(A[i] != -1){
for(int j = i+1; j < length; j++){
if(A[i] == A[j]){
count++;
A[j] = -1;
}
}
}
if(count > 1)
printf("%d is appearing %d times.\n", A[i], count);
}
return 0;
}
|
the_stack_data/1174780.c | #include <stdint.h>
//
// AUTOGENERATED BY BUILD
// DO NOT MODIFY - CHANGES WILL BE OVERWRITTEN
//
uint32_t RESOURCE_ID_IMAGE_MENU_ICON = 1;
uint32_t RESOURCE_ID_IMAGE_LOGO_SPLASH = 2;
uint32_t RESOURCE_ID_IMAGE_TILE_SPLASH = 3;
uint32_t RESOURCE_ID_MONO_FONT_14 = 4;
|
the_stack_data/623794.c | // RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-apple-darwin -target-feature +sse2 -emit-llvm -ffp-exception-behavior=strict -o - -Wall -Werror | FileCheck %s
#include <immintrin.h>
__m128d test_mm_cmpeq_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpeq_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmp.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"oeq", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpeq_pd(A, B);
}
__m128d test_mm_cmpge_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpge_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmps.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"ole", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpge_pd(A, B);
}
__m128d test_mm_cmpgt_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpgt_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmps.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"olt", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpgt_pd(A, B);
}
__m128d test_mm_cmple_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmple_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmps.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"ole", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmple_pd(A, B);
}
__m128d test_mm_cmplt_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmplt_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmps.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"olt", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmplt_pd(A, B);
}
__m128d test_mm_cmpneq_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpneq_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmp.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"une", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpneq_pd(A, B);
}
__m128d test_mm_cmpnge_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpnge_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmps.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"ugt", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpnge_pd(A, B);
}
__m128d test_mm_cmpngt_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpngt_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmps.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"uge", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpngt_pd(A, B);
}
__m128d test_mm_cmpnle_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpnle_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmps.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"ugt", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpnle_pd(A, B);
}
__m128d test_mm_cmpnlt_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpnlt_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmps.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"uge", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpnlt_pd(A, B);
}
__m128d test_mm_cmpord_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpord_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmp.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"ord", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpord_pd(A, B);
}
__m128d test_mm_cmpunord_pd(__m128d A, __m128d B) {
// CHECK-LABEL: test_mm_cmpunord_pd
// CHECK: [[CMP:%.*]] = call <2 x i1> @llvm.experimental.constrained.fcmp.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, metadata !"uno", metadata !"fpexcept.strict")
// CHECK-NEXT: [[SEXT:%.*]] = sext <2 x i1> [[CMP]] to <2 x i64>
// CHECK-NEXT: [[BC:%.*]] = bitcast <2 x i64> [[SEXT]] to <2 x double>
// CHECK-NEXT: ret <2 x double> [[BC]]
return _mm_cmpunord_pd(A, B);
}
|
the_stack_data/220455989.c | /* pr20976.c -- test forced common allocation
Copyright (C) 2016-2020 Free Software Foundation, Inc.
Written by Cary Coutant <[email protected]>
This file is part of gold.
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, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA.
This test checks that forced common allocation (-d) with -r
produces the correct result when the .bss section contains
other allocated data besides common symbols. */
int a = 0;
int b;
int main(void)
{
a = 1;
return b;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.