file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/110247.c
|
int main() {
int a = 3;
return a;
}
|
the_stack_data/137501.c
|
#include <stdio.h>
#include <string.h>
main()
{
char string[40],string1[40];
fgets (string, 40, stdin);
fgets (string1, 40, stdin);
if(strcmp(string,"aplauda suas maos\n")==0)
printf("bata palmas");
if(strcmp(string,"it has beaten palms\n")==0)
printf("clap your hands");
if(strcmp(string,"bata palmas\n")==0)
printf("bata palmas");
if(strcmp(string,"clap your hands\n")==0)
printf("clap your hands");
printf("\n");
if(strcmp(string1,"aplauda suas maos\n")==0)
printf("bata palmas");
if(strcmp(string1,"it has beaten palms\n")==0)
printf("clap your hands");
if(strcmp(string1,"bata palmas\n")==0)
printf("bata palmas");
if(strcmp(string1,"clap your hands\n")==0)
printf("clap your hands");
printf("\n");
return 0;
}
|
the_stack_data/478058.c
|
#include <stdio.h>
#include <unistd.h>
int main() {
int c = 5;
pid_t pid_fils = fork();
c += 5;
if (pid_fils == 0) {
c += 5;
} else {
pid_t pid2 = fork();
if (pid2 != 0) {
c += 10;
} else {
c += 5;
}
}
printf("PID %d: c=%d\n", getpid(), c);
}
|
the_stack_data/103264223.c
|
/*
* organizingLottery.c
*
* Created on: Apr 16, 2019
* Author: Abdelrahman
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum type{Start, Point, End};
typedef unsigned int uint;
typedef struct Segments{
long int coordinate;
int type;
long int order;
}Segment;
void mergeSort(Segment *ptr, uint coordinate, uint end);
void merge(Segment *ptr, uint coordinate, uint middle, uint end);
long int* pointsCovers(Segment *ptrSegments, uint n, uint m, Segment *ptrPoints);
int main(){
uint n = 0;
uint m = 0;
Segment *ptrSegments = NULL;
Segment *ptrPoints = NULL;
long int *ptrResult = NULL;
fflush(stdin);
scanf("%u",&n);
n *= 2;
fflush(stdin);
scanf("%u",&m);
ptrSegments = (Segment *) malloc(n * sizeof(Segment));
ptrPoints = (Segment *) malloc(m * sizeof(Segment));
for(uint i = 0; i < n; i++){
fflush(stdin);
scanf("%ld", &(ptrSegments + i)->coordinate);
if(i%2 == 0){
(ptrSegments + i)->type = Start;
}
else{
(ptrSegments + i)->type = End;
}
}
for(uint i = 0; i < m; i++){
fflush(stdin);
scanf("%ld", &(ptrPoints + i)->coordinate);
(ptrPoints + i)->type = Point;
(ptrPoints + i)->order = i;
}
ptrResult = pointsCovers(ptrSegments, n, m, ptrPoints);
for(uint i = 0; i < m; i++){
printf("%ld ",*(ptrResult+i));
fflush(stdout);
}
return 0;
}
void mergeSort(Segment *ptr, uint coordinate, uint end){
if(coordinate < end){
uint middle = coordinate + (end - coordinate)/2;
mergeSort(ptr, coordinate, middle);
mergeSort(ptr, middle+1, end);
merge(ptr, coordinate, middle, end);
}
}
void merge(Segment *ptr, uint coordinate, uint middle, uint end){
uint i, j, k;
Segment *ptrLeft = 0;
Segment *ptrRight = 0;
uint leftSize = middle - coordinate + 1;
uint rightSize = end - middle;
/*Create Temporary Arrays*/
ptrLeft = (Segment *) malloc(leftSize * sizeof(Segment));
ptrRight = (Segment *) malloc(rightSize * sizeof(Segment));
/*Copy Data to Temporary Arrays*/
for(i = 0; i < leftSize; i++){
*(ptrLeft+i) = *(ptr+coordinate+i);
}
for(j = 0; j < rightSize; j++){
*(ptrRight+j) = *(ptr+middle+j+1);
}
/*Merge the temporary arrays*/
i = 0; j = 0; k = coordinate;
while((i < leftSize) && (j < rightSize)){
if((ptrLeft+i)->coordinate <= (ptrRight+j)->coordinate){
if((ptrLeft+i)->coordinate == (ptrRight+j)->coordinate){
if((ptrLeft+i)->type <= (ptrRight+j)->type){
*(ptr+k) = *(ptrLeft+i); /*Pick the left element if it's smaller*/
i++; /*Move the pointer to the next element in the left array*/
}
else{
*(ptr+k) = *(ptrRight+j); /*Pick the right element if it's smaller*/
j++; /*Move the pointer to the next element in the right array*/
}
}
else{
*(ptr+k) = *(ptrLeft+i); /*Pick the left element if it's smaller*/
i++; /*Move the pointer to the next element in the left array*/
}
}
else{
*(ptr+k) = *(ptrRight+j); /*Pick the right element if it's smaller*/
j++; /*Move the pointer to the next element in the right array*/
}
k++; /*Move the pointer to the next element in the merged array*/
}
/*Copy the remaining elements*/
while(i < leftSize){
*(ptr+k) = *(ptrLeft+i);
i++;
k++;
}
while(j < rightSize){
*(ptr+k) = *(ptrRight+j);
j++;
k++;
}
}
long int* pointsCovers(Segment *ptrSegments, uint n, uint m, Segment *ptrPoints){
int count = 0;
long int *ptrResult = (long int *) malloc(m * sizeof(long int));
Segment *ptrPairs = (Segment *) malloc((m+n) * sizeof(Segment));
for(uint i = 0; i < n; i++){
*(ptrPairs+i) = *(ptrSegments+i);
}
for(uint i = 0, j = n; i < m; i++, j++){
*(ptrPairs+j) = *(ptrPoints+i);
}
mergeSort(ptrPairs, 0, (m + n)-1);
for(uint i = 0; i < (m+n); i++){
if((*(ptrPairs+i)).type == Start){
count++;
}
else if((*(ptrPairs+i)).type == End){
count--;
}
else if((*(ptrPairs+i)).type == Point){
*(ptrResult+(*(ptrPairs+i)).order) = count;
}
}
return ptrResult;
}
|
the_stack_data/14200098.c
|
int IStart, IEnd, JStart, JEnd;
void foo(double (* restrict U)[100]) {
int I, J;
for (int I = IStart; I < IEnd; ++I) {
for (J = JStart; J < JEnd; ++J)
U[I][J] = U[I][J] + 1;
}
}
|
the_stack_data/178805.c
|
#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
#include <string.h>
int bottom, top;
int run(int y) {
// confuse stack
char *s = (char *)alloca(100);
memset(s, 1, 100);
s[y] = y;
s[y / 2] = y * 2;
volatile int x = s[y];
top = (int)alloca(4);
if (x <= 2) return x;
jmp_buf buf;
printf("setjmp of %d\n", x);
if (setjmp(buf) == 0) {
printf("going\n");
x += run(x / 2);
longjmp(buf, 1);
}
printf("back\n");
return x / 2;
}
int main(int argc, char **argv) {
int sum = 0;
for (int i = 0; i < argc * 2; i++) {
bottom = (int)alloca(4);
sum += run(10);
// scorch the earth
if (bottom < top) {
memset((void *)bottom, 1, top - bottom);
} else {
memset((void *)top, 1, bottom - top);
}
}
printf("%d\n", sum);
return sum;
}
|
the_stack_data/136689.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strncat.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aahsan +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/15 22:10:12 by aahsan #+# #+# */
/* Updated: 2021/08/16 11:41:14 by aahsan ### ########.fr */
/* */
/* ************************************************************************** */
char *ft_strncat(char *dest, char *src, unsigned int nb)
{
char *store;
store = dest;
while (*dest++)
;
dest--;
while (*src && nb != 0)
{
*dest++ = *src++;
nb--;
}
*dest = '\0';
return (store);
}
|
the_stack_data/36075684.c
|
int add (int x, int y) {
return x + y;
}
|
the_stack_data/14201310.c
|
#include <stdlib.h>
#include <errno.h>
int __ptsname_r(int, char *, size_t);
char *ptsname(int fd)
{
static char buf[9 + sizeof(int)*3 + 1];
int err = __ptsname_r(fd, buf, sizeof buf);
if (err) {
errno = err;
return 0;
}
return buf;
}
|
the_stack_data/49836.c
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
int result;
opterr = 0;
while ((result = getopt(argc, argv, "ab:c::")) != -1) {
switch (result) {
case 'a':
printf("option=a, optopt=%c, optarg=%s\n", optopt, optarg);
break;
case 'b': //b
printf("option=b, optopt=%c, optarg=%s\n", optopt, optarg);
break;
case 'c': //c
printf("option=c, optopt=%c, optarg=%s\n", optopt, optarg);
break;
case '?':
printf("result=?, optopt=%c, optarg=%s\n", optopt, optarg);
break;
default:
printf("default, result=%c\n", result);
break;
}
printf("argv[%d]=%s\n", optind, argv[optind]);
}
printf("result=-1, optind=%d\n", optind);
for (result = optind; result < argc; result++) { //
printf("-----argv[%d]=%s\n", result, argv[result]);
}
for (result = 1; result < argc; result++) { //
printf("at the end-----argv[%d]=%s\n", result, argv[result]);
}
return 0;
}
|
the_stack_data/1170352.c
|
#include <stdio.h>
#include <stdlib.h>
int max_consecutive_ones(int *arr, int size) {
int max_ones = 0;
int curr_ones = 0;
int i = 0;
while (i < size) {
if (arr[i] == 1) {
curr_ones += 1;
}
else {
if (curr_ones > max_ones) {
max_ones = curr_ones;
}
curr_ones = 0;
}
i += 1;
}
if (curr_ones > max_ones) {
return curr_ones;
}
else {
return max_ones;
}
}
int main(int argc, char **argv) {
fprintf(stdout, "%s\n", argv[1]);
int arr[] = {1, 1, 0, 1, 1, 1};
int size = 6;
int max_ones = max_consecutive_ones(arr, size);
printf("%i\n", max_ones);
return 0;
}
// Credit: Shayna Sragovicz 2021
|
the_stack_data/440652.c
|
#include <stdio.h>
#define MAXLINE 1024
int getmyline(char line[], int maxline);
void copy(char to[], char from[]);
int main()
{
char line[MAXLINE];
char longest[MAXLINE][MAXLINE];
int offset = 0;
while(getmyline(line, 40) > 0)
{
copy(longest[offset], line);
offset++;
}
for (int i=0; i<=offset;i++){
printf("%s\n", longest[i]);
}
return 0;
}
int getmyline(char s[], int lim)
{
int c,i;
for(i = 0; i< lim-1 && (c = getchar()) != EOF && c != '\n'; i++)
{
s[i] = c;
}
if(c == '\n'){
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
void copy(char to[], char from[])
{
int i = 0;
while((to[i] = from[i]) != '\0'){
i++;
}
}
|
the_stack_data/7951501.c
|
#include <stdio.h>
int main(void) {
int i = 0;
float a[100];
while(scanf("%f", &a[i++]), i < 100);
for (i = 0; i < 100; i++) if (a[i] <= 10) printf("A[%d] = %.2f\n", i, a[i]);
return 0;
}
|
the_stack_data/7950689.c
|
#include <stdio.h>
ssize_t flen(FILE *f)
{
ssize_t len;
ssize_t pos = ftell(f);
fseek(f, 0, SEEK_END);
len = ftell(f);
fseek(f, pos, SEEK_SET);
return len;
}
|
the_stack_data/190767011.c
|
#include "syscall.h"
int main(){
CreateDirectory("dossier_temp");
ChangeDirectoryPath("dossier_temp");
ListDirectory(".");
ChangeDirectoryPath("..");
Remove("dossier_temp");
ListDirectory(".");
return 0;
}
|
the_stack_data/388359.c
|
// omp_target_disassociate_ptr should always fail if the hold reference count is
// non-zero, regardless of the dynamic reference count. When the latter is
// finite, the implementation happens to choose to report the hold diagnostic.
// RUN: %libomptarget-compile-generic -fopenmp-extensions
// RUN: %not %libomptarget-run-generic 0 2>&1 | %fcheck-generic
// RUN: %not %libomptarget-run-generic 1 2>&1 | %fcheck-generic
// RUN: %not %libomptarget-run-generic inf 2>&1 | %fcheck-generic
// RUN: %libomptarget-compile-generic -fopenmp-extensions -DHOLD_MORE
// RUN: %not %libomptarget-run-generic 0 2>&1 | %fcheck-generic
// RUN: %not %libomptarget-run-generic 1 2>&1 | %fcheck-generic
// RUN: %not %libomptarget-run-generic inf 2>&1 | %fcheck-generic
#include <omp.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>
int main(int argc, char *argv[]) {
// Parse command line.
int DynRef;
if (argc != 2) {
fprintf(stderr, "bad arguments\n");
return 1;
}
if (0 == strcmp(argv[1], "inf"))
DynRef = INT_MAX;
else
DynRef = atoi(argv[1]);
// Allocate and set dynamic reference count as specified.
int DevNum = omp_get_default_device();
int X;
void *XDev = omp_target_alloc(sizeof X, DevNum);
if (!XDev) {
fprintf(stderr, "omp_target_alloc failed\n");
return 1;
}
if (DynRef == INT_MAX) {
if (omp_target_associate_ptr(&X, &XDev, sizeof X, 0, DevNum)) {
fprintf(stderr, "omp_target_associate_ptr failed\n");
return 1;
}
} else {
for (int I = 0; I < DynRef; ++I) {
#pragma omp target enter data map(alloc: X)
}
}
// Disassociate while hold reference count > 0.
int Status = 0;
#pragma omp target data map(ompx_hold,alloc: X)
#if HOLD_MORE
#pragma omp target data map(ompx_hold,alloc: X)
#pragma omp target data map(ompx_hold,alloc: X)
#endif
{
// CHECK: Libomptarget error: Trying to disassociate a pointer with a
// CHECK-SAME: non-zero hold reference count
// CHECK-NEXT: omp_target_disassociate_ptr failed
if (omp_target_disassociate_ptr(&X, DevNum)) {
fprintf(stderr, "omp_target_disassociate_ptr failed\n");
Status = 1;
}
}
return Status;
}
|
the_stack_data/21274.c
|
#include <stdlib.h>
#include <menu.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
#define CTRLD 4
char *choices[] = {
"Choice 1",
"Choice 2",
"Choice 3",
"Choice 4",
"Choice 5",
"Choice 6",
"Choice 7",
"Exit",
};
int main()
{ ITEM **my_items;
int c;
MENU *my_menu;
int n_choices, i;
ITEM *cur_item;
/* Initialize curses */
initscr();
start_color();
cbreak();
noecho();
keypad(stdscr, TRUE);
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_MAGENTA, COLOR_BLACK);
/* Initialize items */
n_choices = ARRAY_SIZE(choices);
my_items = (ITEM **)calloc(n_choices + 1, sizeof(ITEM *));
for(i = 0; i < n_choices; ++i)
my_items[i] = new_item(choices[i], choices[i]);
my_items[n_choices] = (ITEM *)NULL;
item_opts_off(my_items[3], O_SELECTABLE);
item_opts_off(my_items[6], O_SELECTABLE);
/* Create menu */
my_menu = new_menu((ITEM **)my_items);
/* Set fore ground and back ground of the menu */
set_menu_fore(my_menu, COLOR_PAIR(1) | A_REVERSE);
set_menu_back(my_menu, COLOR_PAIR(2));
set_menu_grey(my_menu, COLOR_PAIR(3));
/* Post the menu */
mvprintw(LINES - 3, 0, "Press <ENTER> to see the option selected");
mvprintw(LINES - 2, 0, "Up and Down arrow keys to naviage (F1 to Exit)");
post_menu(my_menu);
refresh();
while((c = getch()) != KEY_F(1))
{ switch(c)
{ case KEY_DOWN:
menu_driver(my_menu, REQ_DOWN_ITEM);
break;
case KEY_UP:
menu_driver(my_menu, REQ_UP_ITEM);
break;
case 10: /* Enter */
move(20, 0);
clrtoeol();
mvprintw(20, 0, "Item selected is : %s",
item_name(current_item(my_menu)));
pos_menu_cursor(my_menu);
break;
}
}
unpost_menu(my_menu);
for(i = 0; i < n_choices; ++i)
free_item(my_items[i]);
free_menu(my_menu);
endwin();
}
|
the_stack_data/148577312.c
|
/***********************************************************
toposort.c -- トポロジカル・ソーティング
使用例: toposort <toposort.dat
***********************************************************/
#include <stdio.h>
#include <stdlib.h>
#define NMAX 100 /* 点の数の上限 */
char adjacent[NMAX + 1][NMAX + 1]; /* 隣接行列 */
char visited[NMAX + 1]; /* 訪れたか */
int n; /* 点の数 */
void readgraph(void) /* データ入力 */
{
int i, j;
if (scanf("%d%*[^\n]", &n) != 1 || n > NMAX) {
n = 0; return;
}
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++) adjacent[i][j] = 0;
while (scanf("%d%d%*[^\n]", &i, &j) == 2)
adjacent[i][j] = 1;
printf("隣接行列:\n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) printf(" %d", adjacent[i][j]);
printf("\n");
}
}
enum {NEVER, JUST, ONCE};
void visit(int i)
{
int j;
visited[i] = JUST;
for (j = 1; j <= n; j++) {
if (! adjacent[j][i]) continue;
if (visited[j] == NEVER) visit(j);
else if (visited[j] == JUST) {
printf("\nサイクルあり!n"); exit(1);
}
}
visited[i] = ONCE; printf(" %d", i);
}
int main(void)
{
int i;
readgraph(); /* データ {\tt n}, {\tt adjacent[1..n][1..n]} を読む */
for (i = 1; i <= n; i++) visited[i] = NEVER;
printf("トポロジカル・ソーティングの結果:\n");
for (i = 1; i <= n; i++)
if (visited[i] == NEVER) visit(i);
printf("\n");
return 0;
}
|
the_stack_data/234519412.c
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 10, b = 20;
double c = 2.4, d = 3.6;
int sum1 = a + b;
double sum2 = c + d;
printf("%d + %d = %d\n", a, b, sum1);
printf("%lf + %lf = %lf\n", c, d, sum2);
return EXIT_SUCCESS;
}
|
the_stack_data/225141939.c
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// delay
//
void delay ( int nDelaySeconds )
{
time_t tStart, tNow;
double fdElapsedSeconds;
time(&tStart); /* get current time; same as: timer = time(NULL) */
do{
time( &tNow );
fdElapsedSeconds = difftime( tNow, tStart );
printf("elapsed secs = %.f", fdElapsedSeconds );
} while ( fdElapsedSeconds < nDelaySeconds );
}
main( int argc, char *argv[] ){
int nDelay = 0;
if ( argc < 2 ){
printf("usage: %s [delay in seconds]\n",argv[0]);
exit(EXIT_FAILURE);
}
nDelay = atoi(argv[1]);
printf("delaying %d secs\n", nDelay );
delay(nDelay);
printf("end\n");
}
|
the_stack_data/13309.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include <assert.h>
#include <inttypes.h>
#define FAILURE -1
#define SUCCESS 0
uint64_t nCk(int n, int k){
uint64_t res = 1;
if(n < k || n < 0 || k < 0)
return 0;
if(2 * k > n)
k = n - k;
if(n > 75 || k > 20)
return 0;
for(int j = 1; j <= k; ++j){
res *= n--;
res /= j;
}
return res;
}
int resolv_number(int nr, int n, int k, int *p){
uint64_t sum, temp;
int j, z;
if(nCk(n, k) < nr)
return FAILURE;
for(sum = 0, z = 1, j = 1; j <= k; j++){
while((sum + (temp = nCk(n - z, k - j))) < nr){
sum += temp;
z++;
}
if(sum + temp == nr){
/* Finish! The remaining drawings are set to highest values */
for(*p++ = z, j++; j <= k; j++){
*p++ = n - (k - j);
}
}else{
/* sum + temp > nr */
*p++ = z++;
}
}
return SUCCESS;
}
uint64_t resolv_comb(int n, int k, int *p){
uint64_t temp, sum;
int j, t, z;
for(j = 0, sum = 1, z = 0; j < k; j++){
z++;
t = *(p + j);
while(z < t){
sum += nCk(n - z, k - j - 1);
z++;
}
printf("%d. Zahl = %d, sum = %" PRIu64 " z = %d\n", j + 1, t, sum, z);
}
return sum;
}
int main(int argc, char **argv){
int n = 49, k = 6, t;
uint64_t nr, z, z1, z2;
int d1_vec[5], d2_vec[1];
int d1, d2, j;
while(1){
printf("Bitte Wert fuer Ziehung eingeben: ");
scanf("%d", &nr);
d1 = (nr - 1) / (j = nCk(10, 1)) + 1;
d2 = nr % j;
if(d2 == 0)
d2 = j;
d2--;
t = d2 == 0 ? 0 : 1;
printf("j = %d, d1 = %d, d2 = %d, t = %d\n", j, d1, d2, t);
if(resolv_number(d1, n, k, d1_vec) == FAILURE){
printf("Fehler in resolv_number!\n");
exit(1);
}
/* if(resolv_number(d2, 10, 1, d2_vec) == FAILURE){
printf("Fehler in resolv_number2!\n");
exit(1);
} */
printf("Die Zahlen der %" PRIu64 ". Kombination lauten: ", nr);
for(int i = 0; i < k; i++){
printf("%d, ", d1_vec[i]);
}
printf("\b\b\t / %d\n", d2);
z1 = resolv_comb(n, k, d1_vec);
z2 = resolv_comb(10, 1, &d2);
z = j * (z1 - 1) + z2 + t;
if(z == nr){
printf("Okay: z = %" PRIu64 ", nr = %" PRIu64 " !\n", z, nr);
}else{
printf("Something went wrong: z = %d, nr = %d!\n", z, nr);
printf("z1 = %" PRIu64 ", z2 = %" PRIu64 ", j = %d, t = %d!\n", z1, z2, j, t);
printf("Difference: %d!\n", z - nr);
}
}
/* while(1){
printf("Bitte Wert fuer n eingeben: ");
scanf("%d", &n);
printf("Bitte Wert fuer k eingeben: ");
scanf("%d", &k);
printf("%d ueber %d ist %" PRIu64 "!\n", n, k, nCk(n, k));
}
*/
}
|
the_stack_data/97011702.c
|
/* Taxonomy Classification: 0050000000000000000300 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 5 unsigned int
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 0 constant
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 0 none
* LOOP STRUCTURE 0 no
* LOOP COMPLEXITY 0 N/A
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 3 4096 bytes
* CONTINUOUS/DISCRETE 0 discrete
* SIGNEDNESS 0 no
*/
/*
Copyright 2004 M.I.T.
Permission is hereby granted, without written agreement or royalty fee, to use,
copy, modify, and distribute this software and its documentation for any
purpose, provided that the above copyright notice and the following three
paragraphs appear in all copies of this software.
IN NO EVENT SHALL M.I.T. BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE
AND ITS DOCUMENTATION, EVEN IF M.I.T. HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMANGE.
M.I.T. SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND M.I.T. HAS NO OBLIGATION TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
int main(int argc, char *argv[])
{
unsigned int buf[10];
/* BAD */
buf[4105] = 55;
return 0;
}
|
the_stack_data/3261992.c
|
// KASAN: use-after-free Read in l2cap_chan_put
// https://syzkaller.appspot.com/bug?id=3dc0a659c7ec0011789f
// status:0
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <linux/capability.h>
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 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;
}
const int kInitNetNsFd = 239;
#define MAX_FDS 30
static long syz_init_net_socket(volatile long domain, volatile long type,
volatile long proto)
{
int netns = open("/proc/self/ns/net", O_RDONLY);
if (netns == -1)
return netns;
if (setns(kInitNetNsFd, 0))
return -1;
int sock = syscall(__NR_socket, domain, type, proto);
int err = errno;
if (setns(netns, 0))
exit(1);
close(netns);
errno = err;
return sock;
}
#define BTPROTO_HCI 1
#define ACL_LINK 1
#define SCAN_PAGE 2
typedef struct {
uint8_t b[6];
} __attribute__((packed)) bdaddr_t;
#define HCI_COMMAND_PKT 1
#define HCI_EVENT_PKT 4
#define HCI_VENDOR_PKT 0xff
struct hci_command_hdr {
uint16_t opcode;
uint8_t plen;
} __attribute__((packed));
struct hci_event_hdr {
uint8_t evt;
uint8_t plen;
} __attribute__((packed));
#define HCI_EV_CONN_COMPLETE 0x03
struct hci_ev_conn_complete {
uint8_t status;
uint16_t handle;
bdaddr_t bdaddr;
uint8_t link_type;
uint8_t encr_mode;
} __attribute__((packed));
#define HCI_EV_CONN_REQUEST 0x04
struct hci_ev_conn_request {
bdaddr_t bdaddr;
uint8_t dev_class[3];
uint8_t link_type;
} __attribute__((packed));
#define HCI_EV_REMOTE_FEATURES 0x0b
struct hci_ev_remote_features {
uint8_t status;
uint16_t handle;
uint8_t features[8];
} __attribute__((packed));
#define HCI_EV_CMD_COMPLETE 0x0e
struct hci_ev_cmd_complete {
uint8_t ncmd;
uint16_t opcode;
} __attribute__((packed));
#define HCI_OP_WRITE_SCAN_ENABLE 0x0c1a
#define HCI_OP_READ_BUFFER_SIZE 0x1005
struct hci_rp_read_buffer_size {
uint8_t status;
uint16_t acl_mtu;
uint8_t sco_mtu;
uint16_t acl_max_pkt;
uint16_t sco_max_pkt;
} __attribute__((packed));
#define HCI_OP_READ_BD_ADDR 0x1009
struct hci_rp_read_bd_addr {
uint8_t status;
bdaddr_t bdaddr;
} __attribute__((packed));
#define HCI_EV_LE_META 0x3e
struct hci_ev_le_meta {
uint8_t subevent;
} __attribute__((packed));
#define HCI_EV_LE_CONN_COMPLETE 0x01
struct hci_ev_le_conn_complete {
uint8_t status;
uint16_t handle;
uint8_t role;
uint8_t bdaddr_type;
bdaddr_t bdaddr;
uint16_t interval;
uint16_t latency;
uint16_t supervision_timeout;
uint8_t clk_accurancy;
} __attribute__((packed));
struct hci_dev_req {
uint16_t dev_id;
uint32_t dev_opt;
};
struct vhci_vendor_pkt {
uint8_t type;
uint8_t opcode;
uint16_t id;
};
#define HCIDEVUP _IOW('H', 201, int)
#define HCISETSCAN _IOW('H', 221, int)
static int vhci_fd = -1;
static void hci_send_event_packet(int fd, uint8_t evt, void* data,
size_t data_len)
{
struct iovec iv[3];
struct hci_event_hdr hdr;
hdr.evt = evt;
hdr.plen = data_len;
uint8_t type = HCI_EVENT_PKT;
iv[0].iov_base = &type;
iv[0].iov_len = sizeof(type);
iv[1].iov_base = &hdr;
iv[1].iov_len = sizeof(hdr);
iv[2].iov_base = data;
iv[2].iov_len = data_len;
if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0)
exit(1);
}
static void hci_send_event_cmd_complete(int fd, uint16_t opcode, void* data,
size_t data_len)
{
struct iovec iv[4];
struct hci_event_hdr hdr;
hdr.evt = HCI_EV_CMD_COMPLETE;
hdr.plen = sizeof(struct hci_ev_cmd_complete) + data_len;
struct hci_ev_cmd_complete evt_hdr;
evt_hdr.ncmd = 1;
evt_hdr.opcode = opcode;
uint8_t type = HCI_EVENT_PKT;
iv[0].iov_base = &type;
iv[0].iov_len = sizeof(type);
iv[1].iov_base = &hdr;
iv[1].iov_len = sizeof(hdr);
iv[2].iov_base = &evt_hdr;
iv[2].iov_len = sizeof(evt_hdr);
iv[3].iov_base = data;
iv[3].iov_len = data_len;
if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0)
exit(1);
}
static bool process_command_pkt(int fd, char* buf, ssize_t buf_size)
{
struct hci_command_hdr* hdr = (struct hci_command_hdr*)buf;
if (buf_size < (ssize_t)sizeof(struct hci_command_hdr) ||
hdr->plen != buf_size - sizeof(struct hci_command_hdr)) {
exit(1);
}
switch (hdr->opcode) {
case HCI_OP_WRITE_SCAN_ENABLE: {
uint8_t status = 0;
hci_send_event_cmd_complete(fd, hdr->opcode, &status, sizeof(status));
return true;
}
case HCI_OP_READ_BD_ADDR: {
struct hci_rp_read_bd_addr rp = {0};
rp.status = 0;
memset(&rp.bdaddr, 0xaa, 6);
hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp));
return false;
}
case HCI_OP_READ_BUFFER_SIZE: {
struct hci_rp_read_buffer_size rp = {0};
rp.status = 0;
rp.acl_mtu = 1021;
rp.sco_mtu = 96;
rp.acl_max_pkt = 4;
rp.sco_max_pkt = 6;
hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp));
return false;
}
}
char dummy[0xf9] = {0};
hci_send_event_cmd_complete(fd, hdr->opcode, dummy, sizeof(dummy));
return false;
}
static void* event_thread(void* arg)
{
while (1) {
char buf[1024] = {0};
ssize_t buf_size = read(vhci_fd, buf, sizeof(buf));
if (buf_size < 0)
exit(1);
if (buf_size > 0 && buf[0] == HCI_COMMAND_PKT) {
if (process_command_pkt(vhci_fd, buf + 1, buf_size - 1))
break;
}
}
return NULL;
}
#define HCI_HANDLE_1 200
#define HCI_HANDLE_2 201
static void initialize_vhci()
{
int hci_sock = syz_init_net_socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
if (hci_sock < 0)
exit(1);
vhci_fd = open("/dev/vhci", O_RDWR);
if (vhci_fd == -1)
exit(1);
const int kVhciFd = 241;
if (dup2(vhci_fd, kVhciFd) < 0)
exit(1);
close(vhci_fd);
vhci_fd = kVhciFd;
struct vhci_vendor_pkt vendor_pkt;
if (read(vhci_fd, &vendor_pkt, sizeof(vendor_pkt)) != sizeof(vendor_pkt))
exit(1);
if (vendor_pkt.type != HCI_VENDOR_PKT)
exit(1);
pthread_t th;
if (pthread_create(&th, NULL, event_thread, NULL))
exit(1);
if (ioctl(hci_sock, HCIDEVUP, vendor_pkt.id) && errno != EALREADY)
exit(1);
struct hci_dev_req dr = {0};
dr.dev_id = vendor_pkt.id;
dr.dev_opt = SCAN_PAGE;
if (ioctl(hci_sock, HCISETSCAN, &dr))
exit(1);
struct hci_ev_conn_request request;
memset(&request, 0, sizeof(request));
memset(&request.bdaddr, 0xaa, 6);
*(uint8_t*)&request.bdaddr.b[5] = 0x10;
request.link_type = ACL_LINK;
hci_send_event_packet(vhci_fd, HCI_EV_CONN_REQUEST, &request,
sizeof(request));
struct hci_ev_conn_complete complete;
memset(&complete, 0, sizeof(complete));
complete.status = 0;
complete.handle = HCI_HANDLE_1;
memset(&complete.bdaddr, 0xaa, 6);
*(uint8_t*)&complete.bdaddr.b[5] = 0x10;
complete.link_type = ACL_LINK;
complete.encr_mode = 0;
hci_send_event_packet(vhci_fd, HCI_EV_CONN_COMPLETE, &complete,
sizeof(complete));
struct hci_ev_remote_features features;
memset(&features, 0, sizeof(features));
features.status = 0;
features.handle = HCI_HANDLE_1;
hci_send_event_packet(vhci_fd, HCI_EV_REMOTE_FEATURES, &features,
sizeof(features));
struct {
struct hci_ev_le_meta le_meta;
struct hci_ev_le_conn_complete le_conn;
} le_conn;
memset(&le_conn, 0, sizeof(le_conn));
le_conn.le_meta.subevent = HCI_EV_LE_CONN_COMPLETE;
memset(&le_conn.le_conn.bdaddr, 0xaa, 6);
*(uint8_t*)&le_conn.le_conn.bdaddr.b[5] = 0x11;
le_conn.le_conn.role = 1;
le_conn.le_conn.handle = HCI_HANDLE_2;
hci_send_event_packet(vhci_fd, HCI_EV_LE_META, &le_conn, sizeof(le_conn));
pthread_join(th, NULL);
close(hci_sock);
}
static long syz_emit_vhci(volatile long a0, volatile long a1)
{
if (vhci_fd < 0)
return (uintptr_t)-1;
char* data = (char*)a0;
uint32_t length = a1;
return write(vhci_fd, data, length);
}
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);
setpgrp();
setsid();
int netns = open("/proc/self/ns/net", O_RDONLY);
if (netns == -1)
exit(1);
if (dup2(netns, kInitNetNsFd) < 0)
exit(1);
close(netns);
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 (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)) {
}
initialize_vhci();
loop();
exit(1);
}
static void kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
int i;
for (i = 0; i < 100; i++) {
if (waitpid(-1, status, WNOHANG | __WALL) == pid)
return;
usleep(1000);
}
DIR* dir = opendir("/sys/fs/fuse/connections");
if (dir) {
for (;;) {
struct dirent* ent = readdir(dir);
if (!ent)
break;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char abort[300];
snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort",
ent->d_name);
int fd = open(abort, O_WRONLY);
if (fd == -1) {
continue;
}
if (write(fd, abort, 1) < 0) {
}
close(fd);
}
closedir(dir);
} else {
}
while (waitpid(-1, status, __WALL) != pid) {
}
}
static void setup_test()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
write_file("/proc/self/oom_score_adj", "1000");
}
static void close_fds()
{
int fd;
for (fd = 3; fd < MAX_FDS; fd++)
close(fd);
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
int iter;
for (iter = 0;; iter++) {
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
setup_test();
execute_one();
close_fds();
exit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
break;
sleep_ms(1);
if (current_time_ms() - start < 5 * 1000)
continue;
kill_and_wait(pid, &status);
break;
}
}
}
void execute_one(void)
{
syz_init_net_socket(0x1f, 3, 0);
memcpy((void*)0x20000180, "\x02\xc8\x00\x04\x00\x00\x00\x02", 8);
syz_emit_vhci(0x20000180, 9);
}
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/68886909.c
|
#include <stdio.h>
#include <stdlib.h>
/**
* item: a piece of data to be added to the queue
*/
struct item {
int data;
struct item *next;
};
typedef struct item Item;
Item *first = NULL;
Item *last = NULL;
/**
* createItem: creates a new Item
* @param val the value to be assigned to the Item
* @return a pointer to that Item
*/
Item* createItem(int val) {
Item *item = malloc(sizeof(Item));
item->data = val;
return item;
}
/**
* enqueue: inserts an Item into the queue
* @param newItem a pointer to a new Item
* @return void
*/
void enqueue(Item *newItem) {
if (!newItem) {
printf("[ERR] Invalid item.\n");
return;
}
if (!first) {
first = newItem;
last = newItem;
} else {
last->next = newItem;
last = newItem;
}
}
/**
* dequeue: removes the first in item from the queue
* @return void
*/
void dequeue() {
if (!first) {
printf("Empty queue\n");
return;
}
Item *temp = first;
first = first->next;
free(temp);
}
/**
* display: recursively prints the queue
* @param first the pointer to the first Item in the queue
*/
void display(Item *first) {
if (!first) {
return;
} else {
printf("%2d ", first->data);
display(first->next);
}
}
int main() {
return 0;
}
|
the_stack_data/12081.c
|
#include <stdio.h>
#include <stdlib.h>
int compare (const void * a, const void * b)
{
return ( (*(int**)a)[1] - (*(int**)b)[1]);
}
int securitiesBuying(int z,int security_value[], int N)
{
int no_of_stocks=0;
// participants code here
int* sec[N];
int secStore[N][2];
int n;
for(n=0;n<N; n++) {
secStore[n][0] = n + 1;
secStore[n][1] = security_value[n];
sec[n] = secStore[n];
}
qsort(sec, N, sizeof(int*), compare);
for(n=0; n < N; n++){
int prod = sec[n][0] * sec[n][1];
if(prod > z){
no_of_stocks += z / sec[n][1];
break;
}
else{
no_of_stocks += sec[n][0];
z-= prod;
}
}
return no_of_stocks;
}
int main(void) {
int z;
scanf("%d",&z);
int input,security_value[50],size=0;
while(scanf("%d",&input)==1)
{
security_value[size++]=input;
}
int no_of_stocks_purchased = securitiesBuying(z,security_value, size);
printf("%d",no_of_stocks_purchased);
return 0;
}
|
the_stack_data/362168.c
|
extern int xxx;
int
main ()
{
return xxx;
}
|
the_stack_data/64807.c
|
// RUN: %clam --turn-undef-nondet --lower-unsigned-icmp --inline --devirt-functions=types --externalize-addr-taken-functions --crab-narrowing-iterations=2 --crab-widening-delay=2 --crab-widening-jump-set=0 --crab-check=assert --crab-stats --crab-dom=boxes --crab-track=sing-mem --crab-singleton-aliases --crab-print-invariants=false --crab-sanity-checks "%s" 2>&1 | OutputCheck -l debug %s
// RUN: %clam --turn-undef-nondet --lower-unsigned-icmp --inline --devirt-functions=types --externalize-addr-taken-functions --crab-narrowing-iterations=2 --crab-widening-delay=2 --crab-widening-jump-set=0 --crab-check=assert --crab-stats --crab-dom=boxes --crab-track=sing-mem --crab-print-invariants=false --crab-sanity-checks "%s" 2>&1 | OutputCheck -l debug %s
// CHECK: ^29 Number of total safe checks$
// CHECK: ^ 0 Number of total error checks$
// CHECK: ^ 1 Number of total warning checks$
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern char __VERIFIER_nondet_char(void);
extern int __VERIFIER_nondet_int(void);
extern long __VERIFIER_nondet_long(void);
extern void *__VERIFIER_nondet_pointer(void);
int KbFilter_PnP(int DeviceObject , int Irp );
int IofCallDriver(int DeviceObject , int Irp );
int KeSetEvent(int Event , int Increment , int Wait );
int KeWaitForSingleObject(int Object , int WaitReason , int WaitMode , int Alertable ,
int Timeout );
int KbFilter_Complete(int DeviceObject , int Irp , int Context );
int KbFilter_CreateClose(int DeviceObject , int Irp );
int KbFilter_DispatchPassThrough(int DeviceObject , int Irp );
int KbFilter_Power(int DeviceObject , int Irp );
int PoCallDriver(int DeviceObject , int Irp );
int KbFilter_InternIoCtl(int DeviceObject , int Irp );
void errorFn(void) ;
void IofCompleteRequest(int Irp , int PriorityBoost );
extern int __VERIFIER_nondet_int();
int KernelMode ;
int Executive ;
int DevicePowerState ;
int s ;
int UNLOADED ;
int NP ;
int DC ;
int SKIP1 ;
int SKIP2 ;
int MPR1 ;
int MPR3 ;
int IPC ;
int pended ;
int compFptr ;
int compRegistered ;
int lowerDriverReturn ;
int setEventCalled ;
int customIrp ;
int myStatus ;
void stub_driver_init(void)
{
{
s = NP;
pended = 0;
compFptr = 0;
compRegistered = 0;
lowerDriverReturn = 0;
setEventCalled = 0;
customIrp = 0;
return;
}
}
void _BLAST_init(void)
{
{
UNLOADED = 0;
NP = 1;
DC = 2;
SKIP1 = 3;
SKIP2 = 4;
MPR1 = 5;
MPR3 = 6;
IPC = 7;
s = UNLOADED;
pended = 0;
compFptr = 0;
compRegistered = 0;
lowerDriverReturn = 0;
setEventCalled = 0;
customIrp = 0;
return;
}
}
int KbFilter_PnP(int DeviceObject , int Irp )
{ int devExt ;
int irpStack ;
int status ;
int event = __VERIFIER_nondet_int() ;
int DeviceObject__DeviceExtension = __VERIFIER_nondet_int() ;
int Irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int() ;
int irpStack__MinorFunction = __VERIFIER_nondet_int() ;
int devExt__TopOfStack = __VERIFIER_nondet_int() ;
int devExt__Started ;
int devExt__Removed ;
int devExt__SurpriseRemoved ;
int Irp__IoStatus__Status ;
int Irp__IoStatus__Information ;
int Irp__CurrentLocation = __VERIFIER_nondet_int() ;
int irpSp ;
int nextIrpSp ;
int nextIrpSp__Control ;
int irpSp___0 ;
int irpSp__Context ;
int irpSp__Control ;
long __cil_tmp23 ;
{
status = 0;
devExt = DeviceObject__DeviceExtension;
irpStack = Irp__Tail__Overlay__CurrentStackLocation;
if (irpStack__MinorFunction == 0) {
goto switch_0_0;
} else {
if (irpStack__MinorFunction == 23) {
goto switch_0_23;
} else {
if (irpStack__MinorFunction == 2) {
goto switch_0_2;
} else {
if (irpStack__MinorFunction == 1) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 5) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 3) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 6) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 13) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 4) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 7) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 8) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 9) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 12) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 10) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 11) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 15) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 16) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 17) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 18) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 19) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 20) {
goto switch_0_1;
} else {
goto switch_0_1;
if (0) {
switch_0_0:
irpSp = Irp__Tail__Overlay__CurrentStackLocation;
nextIrpSp = Irp__Tail__Overlay__CurrentStackLocation - 1;
nextIrpSp__Control = 0;
if (s != NP) {
{
errorFn();
}
} else {
if (compRegistered != 0) {
{
errorFn();
}
} else {
compRegistered = 1;
}
}
{
irpSp___0 = Irp__Tail__Overlay__CurrentStackLocation - 1;
irpSp__Context = event;
irpSp__Control = 224;
status = IofCallDriver(devExt__TopOfStack,
Irp);
}
{
__cil_tmp23 = (long )status;
if (__cil_tmp23 == 259) {
{
KeWaitForSingleObject(event, Executive,
KernelMode,
0, 0);
}
}
}
if (status >= 0) {
if (myStatus >= 0) {
devExt__Started = 1;
devExt__Removed = 0;
devExt__SurpriseRemoved = 0;
}
}
{
Irp__IoStatus__Status = status;
myStatus = status;
Irp__IoStatus__Information = 0;
IofCompleteRequest(Irp, 0);
}
goto switch_0_break;
switch_0_23:
devExt__SurpriseRemoved = 1;
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
status = IofCallDriver(devExt__TopOfStack,
Irp);
}
goto switch_0_break;
switch_0_2:
devExt__Removed = 1;
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
IofCallDriver(devExt__TopOfStack, Irp);
status = 0;
}
goto switch_0_break;
switch_0_1: ;
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
status = IofCallDriver(devExt__TopOfStack,
Irp);
}
goto switch_0_break;
} else {
switch_0_break: ;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return (status);
}
}
int main(void)
{ int status ;
int irp = __VERIFIER_nondet_int() ;
int pirp ;
int pirp__IoStatus__Status ;
int irp_choice = __VERIFIER_nondet_int() ;
int devobj = __VERIFIER_nondet_int() ;
int __cil_tmp8 ;
KernelMode = 0;
Executive = 0;
DevicePowerState = 1;
s = 0;
UNLOADED = 0;
NP = 0;
DC = 0;
SKIP1 = 0;
SKIP2 = 0 ;
MPR1 = 0;
MPR3 = 0;
IPC = 0;
pended = 0;
compFptr = 0;
compRegistered = 0;
lowerDriverReturn = 0;
setEventCalled = 0;
customIrp = 0;
myStatus = 0;
{
{
status = 0;
pirp = irp;
_BLAST_init();
}
if (status >= 0) {
s = NP;
customIrp = 0;
setEventCalled = customIrp;
lowerDriverReturn = setEventCalled;
compRegistered = lowerDriverReturn;
pended = compRegistered;
pirp__IoStatus__Status = 0;
myStatus = 0;
if (irp_choice == 0) {
pirp__IoStatus__Status = -1073741637;
myStatus = -1073741637;
}
{
stub_driver_init();
}
{
if (status < 0) {
return (-1);
}
}
int tmp_ndt_1;
tmp_ndt_1 = __VERIFIER_nondet_int();
if (tmp_ndt_1 == 0) {
goto switch_1_0;
} else {
int tmp_ndt_2;
tmp_ndt_2 = __VERIFIER_nondet_int();
if (tmp_ndt_2 == 1) {
goto switch_1_1;
} else {
int tmp_ndt_3;
tmp_ndt_3 = __VERIFIER_nondet_int();
if (tmp_ndt_3 == 3) {
goto switch_1_3;
} else {
int tmp_ndt_4;
tmp_ndt_4 = __VERIFIER_nondet_int();
if (tmp_ndt_4 == 4) {
goto switch_1_4;
} else {
int tmp_ndt_5;
tmp_ndt_5 = __VERIFIER_nondet_int();
if (tmp_ndt_5 == 8) {
goto switch_1_8;
} else {
goto switch_1_default;
if (0) {
switch_1_0:
{
status = KbFilter_CreateClose(devobj, pirp);
}
goto switch_1_break;
switch_1_1:
{
status = KbFilter_CreateClose(devobj, pirp);
}
goto switch_1_break;
switch_1_3:
{
status = KbFilter_PnP(devobj, pirp);
}
goto switch_1_break;
switch_1_4:
{
status = KbFilter_Power(devobj, pirp);
}
goto switch_1_break;
switch_1_8:
{
status = KbFilter_InternIoCtl(devobj, pirp);
}
goto switch_1_break;
switch_1_default: ;
return (-1);
} else {
switch_1_break: ;
}
}
}
}
}
}
}
if (pended == 1) {
if (s == NP) {
s = NP;
} else {
goto _L___2;
}
} else {
_L___2:
if (pended == 1) {
if (s == MPR3) {
s = MPR3;
} else {
goto _L___1;
}
} else {
_L___1:
if (s != UNLOADED) {
if (status != -1) {
if (s != SKIP2) {
if (s != IPC) {
if (s == DC) {
goto _L___0;
}
} else {
goto _L___0;
}
} else {
_L___0:
if (pended == 1) {
if (status != 259) {
{
errorFn();
}
}
} else {
if (s == DC) {
if (status == 259) {
}
} else {
if (status != lowerDriverReturn) {
errorFn();
}
else{
}
}
}
}
}
}
}
}
return (status);
}
}
void stubMoreProcessingRequired(void)
{
{
if (s == NP) {
s = MPR1;
} else {
{
errorFn();
}
}
return;
}
}
int IofCallDriver(int DeviceObject , int Irp )
{
int returnVal2 ;
int compRetStatus ;
int lcontext = __VERIFIER_nondet_int() ;
long long __cil_tmp7 ;
{
if (compRegistered) {
{
compRetStatus = KbFilter_Complete(DeviceObject, Irp, lcontext);
}
{
__cil_tmp7 = (long long )compRetStatus;
if (__cil_tmp7 == -1073741802) {
{
stubMoreProcessingRequired();
}
}
}
}
int tmp_ndt_6;
tmp_ndt_6 = __VERIFIER_nondet_int();
if (tmp_ndt_6 == 0) {
goto switch_2_0;
} else {
int tmp_ndt_7;
tmp_ndt_7 = __VERIFIER_nondet_int();
if (tmp_ndt_7 == 1) {
goto switch_2_1;
} else {
goto switch_2_default;
if (0) {
switch_2_0:
returnVal2 = 0;
goto switch_2_break;
switch_2_1:
returnVal2 = -1073741823;
goto switch_2_break;
switch_2_default:
returnVal2 = 259;
goto switch_2_break;
} else {
switch_2_break: ;
}
}
}
if (s == NP) {
s = IPC;
lowerDriverReturn = returnVal2;
} else {
if (s == MPR1) {
if (returnVal2 == 259) {
s = MPR3;
lowerDriverReturn = returnVal2;
} else {
s = NP;
lowerDriverReturn = returnVal2;
}
} else {
if (s == SKIP1) {
s = SKIP2;
lowerDriverReturn = returnVal2;
} else {
{
errorFn();
}
}
}
}
return (returnVal2);
}
}
void IofCompleteRequest(int Irp , int PriorityBoost )
{
{
if (s == NP) {
s = DC;
} else {
{
errorFn();
}
}
return;
}
}
int KeSetEvent(int Event , int Increment , int Wait )
{ int l = __VERIFIER_nondet_int() ;
{
setEventCalled = 1;
return (l);
}
}
int KeWaitForSingleObject(int Object , int WaitReason , int WaitMode , int Alertable ,
int Timeout )
{
{
if (s == MPR3) {
if (setEventCalled == 1) {
s = NP;
setEventCalled = 0;
} else {
goto _L;
}
} else {
_L:
if (customIrp == 1) {
s = NP;
customIrp = 0;
} else {
if (s == MPR3) {
{
errorFn();
}
}
}
}
int tmp_ndt_8;
tmp_ndt_8 = __VERIFIER_nondet_int();
if (tmp_ndt_8 == 0) {
goto switch_3_0;
} else {
goto switch_3_default;
if (0) {
switch_3_0:
return (0);
switch_3_default: ;
return (-1073741823);
} else {
}
}
}
}
int KbFilter_Complete(int DeviceObject , int Irp , int Context )
{ int event ;
{
{
event = Context;
KeSetEvent(event, 0, 0);
}
return (-1073741802);
}
}
int KbFilter_CreateClose(int DeviceObject , int Irp )
{ int irpStack__MajorFunction = __VERIFIER_nondet_int() ;
int devExt__UpperConnectData__ClassService = __VERIFIER_nondet_int() ;
int Irp__IoStatus__Status ;
int status ;
int tmp ;
{
status = myStatus;
if (irpStack__MajorFunction == 0) {
goto switch_4_0;
} else {
if (irpStack__MajorFunction == 2) {
goto switch_4_2;
} else {
if (0) {
switch_4_0: ;
if (devExt__UpperConnectData__ClassService == 0) {
status = -1073741436;
}
goto switch_4_break;
switch_4_2: ;
goto switch_4_break;
} else {
switch_4_break: ;
}
}
}
{
Irp__IoStatus__Status = status;
myStatus = status;
tmp = KbFilter_DispatchPassThrough(DeviceObject, Irp);
}
return (tmp);
}
}
int KbFilter_DispatchPassThrough(int DeviceObject , int Irp )
{ int Irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int() ;
int Irp__CurrentLocation = __VERIFIER_nondet_int() ;
int DeviceObject__DeviceExtension__TopOfStack = __VERIFIER_nondet_int() ;
int irpStack ;
int tmp ;
{
irpStack = Irp__Tail__Overlay__CurrentStackLocation;
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
tmp = IofCallDriver(DeviceObject__DeviceExtension__TopOfStack, Irp);
}
return (tmp);
}
}
int KbFilter_Power(int DeviceObject , int Irp )
{ int irpStack__MinorFunction = __VERIFIER_nondet_int() ;
int devExt__DeviceState ;
int powerState__DeviceState = __VERIFIER_nondet_int() ;
int Irp__CurrentLocation = __VERIFIER_nondet_int() ;
int Irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int() ;
int devExt__TopOfStack = __VERIFIER_nondet_int() ;
int powerType = __VERIFIER_nondet_int() ;
int tmp ;
{
if (irpStack__MinorFunction == 2) {
goto switch_5_2;
} else {
if (irpStack__MinorFunction == 1) {
goto switch_5_1;
} else {
if (irpStack__MinorFunction == 0) {
goto switch_5_0;
} else {
if (irpStack__MinorFunction == 3) {
goto switch_5_3;
} else {
goto switch_5_default;
if (0) {
switch_5_2: ;
if (powerType == DevicePowerState) {
devExt__DeviceState = powerState__DeviceState;
}
switch_5_1: ;
switch_5_0: ;
switch_5_3: ;
switch_5_default: ;
goto switch_5_break;
} else {
switch_5_break: ;
}
}
}
}
}
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
tmp = PoCallDriver(devExt__TopOfStack, Irp);
}
return (tmp);
}
}
int PoCallDriver(int DeviceObject , int Irp )
{
int compRetStatus ;
int returnVal ;
int lcontext = __VERIFIER_nondet_int() ;
unsigned long __cil_tmp7 ;
long __cil_tmp8 ;
{
if (compRegistered) {
{
compRetStatus = KbFilter_Complete(DeviceObject, Irp, lcontext);
}
{
__cil_tmp7 = (unsigned long )compRetStatus;
if (__cil_tmp7 == -1073741802) {
{
stubMoreProcessingRequired();
}
}
}
}
int tmp_ndt_9;
tmp_ndt_9 = __VERIFIER_nondet_int();
if (tmp_ndt_9 == 0) {
goto switch_6_0;
} else {
int tmp_ndt_10;
tmp_ndt_10 = __VERIFIER_nondet_int();
if (tmp_ndt_10 == 1) {
goto switch_6_1;
} else {
goto switch_6_default;
if (0) {
switch_6_0:
returnVal = 0;
goto switch_6_break;
switch_6_1:
returnVal = -1073741823;
goto switch_6_break;
switch_6_default:
returnVal = 259;
goto switch_6_break;
} else {
switch_6_break: ;
}
}
}
if (s == NP) {
s = IPC;
lowerDriverReturn = returnVal;
} else {
if (s == MPR1) {
{
__cil_tmp8 = (long )returnVal;
if (__cil_tmp8 == 259L) {
s = MPR3;
lowerDriverReturn = returnVal;
} else {
s = NP;
lowerDriverReturn = returnVal;
}
}
} else {
if (s == SKIP1) {
s = SKIP2;
lowerDriverReturn = returnVal;
} else {
{
errorFn();
}
}
}
}
return (returnVal);
}
}
int KbFilter_InternIoCtl(int DeviceObject , int Irp )
{ int Irp__IoStatus__Information ;
int irpStack__Parameters__DeviceIoControl__IoControlCode = __VERIFIER_nondet_int() ;
int devExt__UpperConnectData__ClassService = __VERIFIER_nondet_int() ;
int irpStack__Parameters__DeviceIoControl__InputBufferLength = __VERIFIER_nondet_int() ;
int sizeof__CONNECT_DATA = __VERIFIER_nondet_int() ;
int irpStack__Parameters__DeviceIoControl__Type3InputBuffer = __VERIFIER_nondet_int() ;
int sizeof__INTERNAL_I8042_HOOK_KEYBOARD = __VERIFIER_nondet_int() ;
int hookKeyboard__InitializationRoutine = __VERIFIER_nondet_int() ;
int hookKeyboard__IsrRoutine = __VERIFIER_nondet_int() ;
int Irp__IoStatus__Status ;
int hookKeyboard ;
int connectData ;
int status ;
int tmp ;
int __cil_tmp17 ;
int __cil_tmp18 ;
int __cil_tmp19 ;
int __cil_tmp20 = __VERIFIER_nondet_int() ;
int __cil_tmp21 ;
int __cil_tmp22 ;
int __cil_tmp23 ;
int __cil_tmp24 = __VERIFIER_nondet_int() ;
int __cil_tmp25 ;
int __cil_tmp26 ;
int __cil_tmp27 ;
int __cil_tmp28 = __VERIFIER_nondet_int() ;
int __cil_tmp29 = __VERIFIER_nondet_int() ;
int __cil_tmp30 ;
int __cil_tmp31 ;
int __cil_tmp32 = __VERIFIER_nondet_int() ;
int __cil_tmp33 ;
int __cil_tmp34 ;
int __cil_tmp35 = __VERIFIER_nondet_int() ;
int __cil_tmp36 ;
int __cil_tmp37 ;
int __cil_tmp38 = __VERIFIER_nondet_int() ;
int __cil_tmp39 ;
int __cil_tmp40 ;
int __cil_tmp41 = __VERIFIER_nondet_int() ;
int __cil_tmp42 ;
int __cil_tmp43 ;
int __cil_tmp44 = __VERIFIER_nondet_int() ;
int __cil_tmp45 ;
{
status = 0;
Irp__IoStatus__Information = 0;
{
//__cil_tmp17 = 128 << 2;
//__cil_tmp18 = 11 << 16;
//__cil_tmp19 = __cil_tmp18 | __cil_tmp17;
//__cil_tmp20 = __cil_tmp19 | 3;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp20) {
goto switch_7_exp_0;
} else {
{
//__cil_tmp21 = 256 << 2;
//__cil_tmp22 = 11 << 16;
//__cil_tmp23 = __cil_tmp22 | __cil_tmp21;
//__cil_tmp24 = __cil_tmp23 | 3;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp24) {
goto switch_7_exp_1;
} else {
{
//__cil_tmp25 = 4080 << 2;
//__cil_tmp26 = 11 << 16;
//__cil_tmp27 = __cil_tmp26 | __cil_tmp25;
//__cil_tmp28 = __cil_tmp27 | 3;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp28) {
goto switch_7_exp_2;
} else {
{
//__cil_tmp29 = 11 << 16;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp29) {
goto switch_7_exp_3;
} else {
{
//__cil_tmp30 = 32 << 2;
//__cil_tmp31 = 11 << 16;
//__cil_tmp32 = __cil_tmp31 | __cil_tmp30;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp32) {
goto switch_7_exp_4;
} else {
{
//__cil_tmp33 = 16 << 2;
//__cil_tmp34 = 11 << 16;
//__cil_tmp35 = __cil_tmp34 | __cil_tmp33;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp35) {
goto switch_7_exp_5;
} else {
{
//__cil_tmp36 = 2 << 2;
// __cil_tmp37 = 11 << 16;
//__cil_tmp38 = __cil_tmp37 | __cil_tmp36;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp38) {
goto switch_7_exp_6;
} else {
{
// __cil_tmp39 = 8 << 2;
// __cil_tmp40 = 11 << 16;
// __cil_tmp41 = __cil_tmp40 | __cil_tmp39;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp41) {
goto switch_7_exp_7;
} else {
{
// __cil_tmp42 = 1 << 2;
// __cil_tmp43 = 11 << 16;
// __cil_tmp44 = __cil_tmp43 | __cil_tmp42;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp44) {
goto switch_7_exp_8;
} else {
if (0) {
switch_7_exp_0: ;
if (devExt__UpperConnectData__ClassService != 0) {
status = -1073741757;
goto switch_7_break;
} else {
if (irpStack__Parameters__DeviceIoControl__InputBufferLength < sizeof__CONNECT_DATA) {
status = -1073741811;
goto switch_7_break;
}
}
connectData = irpStack__Parameters__DeviceIoControl__Type3InputBuffer;
goto switch_7_break;
switch_7_exp_1:
status = -1073741822;
goto switch_7_break;
switch_7_exp_2: ;
if (irpStack__Parameters__DeviceIoControl__InputBufferLength < sizeof__INTERNAL_I8042_HOOK_KEYBOARD) {
status = -1073741811;
goto switch_7_break;
}
hookKeyboard = irpStack__Parameters__DeviceIoControl__Type3InputBuffer;
if (hookKeyboard__InitializationRoutine) {
}
if (hookKeyboard__IsrRoutine) {
}
status = 0;
goto switch_7_break;
switch_7_exp_3: ;
switch_7_exp_4: ;
switch_7_exp_5: ;
switch_7_exp_6: ;
switch_7_exp_7: ;
switch_7_exp_8: ;
goto switch_7_break;
} else {
switch_7_break: ;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
{
if (status < 0) {
{
Irp__IoStatus__Status = status;
myStatus = status;
IofCompleteRequest(Irp, 0);
}
return (status);
}
}
{
tmp = KbFilter_DispatchPassThrough(DeviceObject, Irp);
}
return (tmp);
}
}
void errorFn(void)
{
{
ERROR: __VERIFIER_error();
return;
}
}
|
the_stack_data/90765624.c
|
void foo(int N, double *A) {
int J = N;
for (int I = 0; I < N; ++I) {
++J;
A[I] = I + J;
}
}
//CHECK: openmp_3.c:3:3: remark: parallel execution of loop is possible
//CHECK: for (int I = 0; I < N; ++I) {
//CHECK: ^
//CHECK: openmp_3.c:3:3: warning: unable to create parallel directive
//CHECK: openmp_3.c:3:12: note: loop has multiple inducition variables
//CHECK: for (int I = 0; I < N; ++I) {
//CHECK: ^
//CHECK: openmp_3.c:2:7: note: loop has multiple inducition variables
//CHECK: int J = N;
//CHECK: ^
//CHECK: 1 warning generated.
|
the_stack_data/48575527.c
|
#include <stdio.h>
int main() {
unsigned long long n, l;
scanf("%llu %llu", &n, &l);
printf("%llu\n", (n * l));
return 0;
}
|
the_stack_data/168891907.c
|
/*
@Filename:quadratuc.c
@Author:Kishan Adhikari
@Created Date:2021/07/22
Write a program to read the values of coefficients a, b and c of a quadratic equation
ax2+bx+c=0 and find roots of the equation.
roots of quadratic equation=-b (+/-)sqrt(b2-4ac)/(2a)
Discriminant=b2-4ac
when Discriminant >0; real roots exists
when Discriminant<0; imaginary root exists
*/
#include <stdio.h>
#include <math.h>
int main()
{
int a, b, c;
float root1, root2, real, img;
printf("Enter value of a,b,c: \n");
scanf("%d %d %d", &a, &b, &c);
float Discriminant = (b * b - 4 * a * c);
if (Discriminant >= 0)
{
root1 = (-b + sqrt(Discriminant)) / (2 * a);
root2 = (-b - sqrt(Discriminant)) / (2 * a);
printf("Roots of quadratic equation are: %.2f, %.2f \n", root1, root2);
}
else
{
real = -b / (2 * a); //real part of root
img = (sqrt(-Discriminant)) / (2 * a); //since discriminant is already negative we use - sign to make it positive
printf("Roots of quadratic equation are:%.2f+%.2fi , %.2f-%.2fi\n", real, img, real, img);
}
return 0;
}
|
the_stack_data/1054316.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define L_SIZE 10
#define B_SIZE 15
void sum(char *s1, char *s2, char *s3);
int main()
{
char ar1[L_SIZE]="String 1";
char ar2[L_SIZE]="String 2";
char ar3[B_SIZE];
void (*pf)(char *, char *, char *);
pf=sum;
pf(ar1,ar2,ar3);
printf("Result = %s\n",ar3);
printf("Hello world!\n");
return 0;
}
void sum(char *s1, char *s2, char *s3)
{
if(B_SIZE>strlen(s1))
strcpy(s3, s1);
//else exit(1);
//if((B_SIZE-strlen(s3))>strlen(s2))
strncat(s3,s2, B_SIZE-strlen(s3)-1);
}
|
the_stack_data/29850.c
|
/* Exercise 1 - Calculations
Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */
#include <stdio.h>
int main() {
int sub1,sub2,total;
float avg;
printf("enter sub 1:");
scanf("%d",&sub1);
printf("enter sub 2:");
scanf("%d",&sub2);
total=sub1+sub2;
avg=total/2;
printf("avg is %f\n",avg);
return 0;
}
|
the_stack_data/86012.c
|
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2017 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
/*
* This test verifies that Pin correctly emulates the error returns from the
* various signal related system calls.
*/
#include <stdio.h>
#include <errno.h>
#include <signal.h>
int main()
{
struct sigaction act;
sigset_t set;
stack_t stack;
errno = 0;
if (sigaction(0x12345678, &act, 0) != -1 || errno != EINVAL)
{
fprintf(stderr, "sigaction: Expected EINVAL, but got %d\n", errno);
return 1;
}
errno = 0;
if (sigprocmask(0x12345678, &set, 0) != -1 || errno != EINVAL)
{
fprintf(stderr, "sigprocmask: Expected EINVAL, but got %d\n", errno);
return 1;
}
errno = 0;
stack.ss_sp = 0;
stack.ss_size = 0;
stack.ss_flags = 0x12345678;
if (sigaltstack(&stack, 0) != -1 || (errno != EINVAL && errno != ENOMEM))
{
fprintf(stderr, "sigaltstack: Expected EINVAL or ENOMEM, but got %d\n", errno);
return 1;
}
return 0;
}
|
the_stack_data/165764479.c
|
//
// getip.c
// LearnSocket
//
// Created by Zhang Yuanming on 3/8/18.
// Copyright © 2018 HansonStudio. All rights reserved.
//
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <errno.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
// 获取本机IP地址
int getlocalip(char *ip)
{
char host[100] = {0};
if (gethostname(host, sizeof(host)) < 0) {
return -1;
}
printf("hostname %s\n", host);
struct hostent *hp;
if ((hp = gethostbyname(host)) == NULL)
{
return -1;
}
strcpy(ip, inet_ntoa(*(struct in_addr*)hp->h_addr));
return 0;
}
// gcc -Wall -g main.c -o main
int main(int argc, const char * argv[])
{
char ip[1024] = {0};
getlocalip(ip);
printf("%s\n", ip);
}
|
the_stack_data/168893454.c
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n1,n2;
printf("Digite um valor para n1:");
scanf("%d",&n1);
printf("\n Digite outro valor para n2:");
scanf("%d",&n2);
if(n1>n2){
while(n1 != n2){
printf(" %d,",n2);
n2++;}
printf("%d",n1);
}
if(n1<n2){
while(n1!= n2){
printf("%d,",n1);
n1++;
}printf("%d",n2);
}
return 0;
}
|
the_stack_data/789155.c
|
/* Test that #pragma GCC visibility works. */
/* { dg-do compile } */
/* { dg-require-visibility "" } */
/* { dg-final { scan-hidden "foo" } } */
#pragma GCC visibility push(hidden)
void foo();
#pragma GCC visibility pop
void foo() { }
|
the_stack_data/41212.c
|
#include <stdio.h>
#include <stdlib.h>
/*21. Napište funkci, která vezme dvě pole o délce n a třetí pole o délce 2*n a vloží za sebou tato dvě pole do toho třetího.*/
void nacteni(int a[], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Enter %d. element of area: ", i + 1);
scanf("%d", &a[i]);
}
}
void slouceni_poli(int a[], int b[], int c[], int n)
{
for(int i=0; i < n; i++)
{
c[i] = a[i];
}
for(int i=n; i < n*2; i++)
{
c[i] = b[i - n];
}
}
void vypis(int p[], int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", p[i]);
}
printf("\n");
}
int main()
{
int n;
printf("Enter a number n: ");
scanf("%d", &n);
int a[n], b[n], c[n*2];
nacteni(a, n);
nacteni(b, n);
slouceni_poli(a, b, c, n);
vypis(c, n*2);
return 0;
}
|
the_stack_data/66554.c
|
int suma_cifre(int nr) {
int s=0;
if (nr<0) nr*=-1;
while (nr) {
s+=nr%10;
nr/=10;
}
return s;
}
/**
* Citeste n numere si determina cea mai mare valoare a sumei cifrelor numerelor citite
* param n: numarul de numere care vor fi citite
* retrurn: cea mai mare valoare a sumei cifrelor numerelor citite
*/
int prelucrare_numere(int n){
int max=0,aux;
for (int i=0; i<n; i++) {
scanf("%d",&aux);
aux=suma_cifre(aux);
if (aux>max)
max=aux;
}
return max;
}
int main(){
int n;
scanf("%d",&n);
printf("%d\n", prelucrare_numere(n));
return 0;
}
|
the_stack_data/78790.c
|
#include <sys/types.h>
#include <stdint.h>
#include <stddef.h>
#include "wctype.h"
#undef KEY
#if defined(__i386)
# define KEY '_','_','i','3','8','6'
#elif defined(__x86_64)
# define KEY '_','_','x','8','6','_','6','4'
#elif defined(__ppc__)
# define KEY '_','_','p','p','c','_','_'
#elif defined(__ppc64__)
# define KEY '_','_','p','p','c','6','4','_','_'
#elif defined(__aarch64__)
# define KEY '_','_','a','a','r','c','h','6','4','_','_'
#elif defined(__ARM_ARCH_7A__)
# define KEY '_','_','A','R','M','_','A','R','C','H','_','7','A','_','_'
#elif defined(__ARM_ARCH_7S__)
# define KEY '_','_','A','R','M','_','A','R','C','H','_','7','S','_','_'
#endif
#define SIZE (sizeof(wctype_t))
char info_size[] = {'I', 'N', 'F', 'O', ':', 's','i','z','e','[',
('0' + ((SIZE / 10000)%10)),
('0' + ((SIZE / 1000)%10)),
('0' + ((SIZE / 100)%10)),
('0' + ((SIZE / 10)%10)),
('0' + (SIZE % 10)),
']',
#ifdef KEY
' ','k','e','y','[', KEY, ']',
#endif
'\0'};
#ifdef __CLASSIC_C__
int main(argc, argv) int argc; char *argv[];
#else
int main(int argc, char *argv[])
#endif
{
int require = 0;
require += info_size[argc];
(void)argv;
return require;
}
|
the_stack_data/140764896.c
|
/*程序5.6:用一级指针访问一维数组*/
#include<stdio.h>
int main( )
{
int a[5]={10,15,20,25,30}; //数组初始化
int i,*p=a; //整型指针变量初始化等于a
p[0]=-p[0]; //修改数组首元素的值,即a[0]=-10;
p[1]=p[2]+p[3]; //修改数组第2个元素的值,即a[1]=a[2]+a[3];
printf("print out address and value of each element by using pointer:\n");
for (i=0;i<5;i++) //利用指针输出数组每个元素的地址及元素值
printf("&a[%d]=%x, a[%d]=%d\n",i,p+i,i,*(p+i));
printf("print out address and value of each element by using array:\n");
for (i=0;i<5;i++) //利用一维数组输出数组每个元素的地址及元素值
printf("&a[%d]=%x, a[%d]=%d\n",i,&a[i],i,a[i]);
scanf("%d");
return 0;
}
|
the_stack_data/537485.c
|
/* $OpenBSD: strlcpy.c,v 1.8 2003/06/17 21:56:24 millert Exp $ */
/*
* Copyright (c) 1998 Todd C. Miller <[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.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char *rcsid = "$OpenBSD: strlcpy.c,v 1.8 2003/06/17 21:56:24 millert Exp $";
#endif /* LIBC_SCCS and not lint */
#include <sys/types.h>
#include <string.h>
/*
* Copy src to string dst of size siz. At most siz-1 characters
* will be copied. Always NUL terminates (unless siz == 0).
* Returns strlen(src); if retval >= siz, truncation occurred.
*/
size_t
strlcpy(char *dst, const char *src, size_t siz)
{
register char *d = dst;
register const char *s = src;
register size_t n = siz;
/* Copy as many bytes as will fit */
if (n != 0 && --n != 0) {
do {
if ((*d++ = *s++) == 0)
break;
} while (--n != 0);
}
/* Not enough room in dst, add NUL and traverse rest of src */
if (n == 0) {
if (siz != 0)
*d = '\0'; /* NUL-terminate dst */
while (*s++)
;
}
return(s - src - 1); /* count does not include NUL */
}
|
the_stack_data/154829744.c
|
#include <stdio.h>
int main(void) {
float a, b, c;
printf("a: ");
scanf ("%f", &a);
printf("b: ");
scanf ("%f", &b);
printf("c: ");
scanf ("%f", &c);
/* Completar */
printf("Nao é possível formar um triângulo\n");
printf ("O triângulo é equilátero\n");
printf ("O triângulo é isóceles\n");
printf ("O triângulo é escaleno\n");
}
|
the_stack_data/118863.c
|
#include <yaml.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <assert.h>
#define BUFFER_SIZE 65536
#define MAX_DOCUMENTS 16
int copy_document(yaml_document_t *document_to, yaml_document_t *document_from)
{
yaml_node_t *node;
yaml_node_item_t *item;
yaml_node_pair_t *pair;
if (!yaml_document_initialize(document_to, document_from->version_directive,
document_from->tag_directives.start,
document_from->tag_directives.end,
document_from->start_implicit, document_from->end_implicit))
return 0;
for (node = document_from->nodes.start;
node < document_from->nodes.top; node ++) {
switch (node->type) {
case YAML_SCALAR_NODE:
if (!yaml_document_add_scalar(document_to, node->tag,
node->data.scalar.value, node->data.scalar.length,
node->data.scalar.style)) goto error;
break;
case YAML_SEQUENCE_NODE:
if (!yaml_document_add_sequence(document_to, node->tag,
node->data.sequence.style)) goto error;
break;
case YAML_MAPPING_NODE:
if (!yaml_document_add_mapping(document_to, node->tag,
node->data.mapping.style)) goto error;
break;
default:
assert(0);
break;
}
}
for (node = document_from->nodes.start;
node < document_from->nodes.top; node ++) {
switch (node->type) {
case YAML_SEQUENCE_NODE:
for (item = node->data.sequence.items.start;
item < node->data.sequence.items.top; item ++) {
if (!yaml_document_append_sequence_item(document_to,
node - document_from->nodes.start + 1,
*item)) goto error;
}
break;
case YAML_MAPPING_NODE:
for (pair = node->data.mapping.pairs.start;
pair < node->data.mapping.pairs.top; pair ++) {
if (!yaml_document_append_mapping_pair(document_to,
node - document_from->nodes.start + 1,
pair->key, pair->value)) goto error;
}
break;
default:
break;
}
}
return 1;
error:
yaml_document_delete(document_to);
return 0;
}
int compare_nodes(yaml_document_t *document1, int index1,
yaml_document_t *document2, int index2, int level)
{
if (level++ > 1000) return 0;
yaml_node_t *node1 = yaml_document_get_node(document1, index1);
yaml_node_t *node2 = yaml_document_get_node(document2, index2);
int k;
assert(node1);
assert(node2);
if (node1->type != node2->type)
return 0;
if (strcmp((char *)node1->tag, (char *)node2->tag) != 0) return 0;
switch (node1->type) {
case YAML_SCALAR_NODE:
if (node1->data.scalar.length != node2->data.scalar.length)
return 0;
if (strncmp((char *)node1->data.scalar.value, (char *)node2->data.scalar.value,
node1->data.scalar.length) != 0) return 0;
break;
case YAML_SEQUENCE_NODE:
if ((node1->data.sequence.items.top - node1->data.sequence.items.start) !=
(node2->data.sequence.items.top - node2->data.sequence.items.start))
return 0;
for (k = 0; k < (node1->data.sequence.items.top - node1->data.sequence.items.start); k ++) {
if (!compare_nodes(document1, node1->data.sequence.items.start[k],
document2, node2->data.sequence.items.start[k], level)) return 0;
}
break;
case YAML_MAPPING_NODE:
if ((node1->data.mapping.pairs.top - node1->data.mapping.pairs.start) !=
(node2->data.mapping.pairs.top - node2->data.mapping.pairs.start))
return 0;
for (k = 0; k < (node1->data.mapping.pairs.top - node1->data.mapping.pairs.start); k ++) {
if (!compare_nodes(document1, node1->data.mapping.pairs.start[k].key,
document2, node2->data.mapping.pairs.start[k].key, level)) return 0;
if (!compare_nodes(document1, node1->data.mapping.pairs.start[k].value,
document2, node2->data.mapping.pairs.start[k].value, level)) return 0;
}
break;
default:
assert(0);
break;
}
return 1;
}
int compare_documents(yaml_document_t *document1, yaml_document_t *document2)
{
int k;
if ((document1->version_directive && !document2->version_directive)
|| (!document1->version_directive && document2->version_directive)
|| (document1->version_directive && document2->version_directive
&& (document1->version_directive->major != document2->version_directive->major
|| document1->version_directive->minor != document2->version_directive->minor)))
return 0;
if ((document1->tag_directives.end - document1->tag_directives.start) !=
(document2->tag_directives.end - document2->tag_directives.start))
return 0;
for (k = 0; k < (document1->tag_directives.end - document1->tag_directives.start); k ++) {
if ((strcmp((char *)document1->tag_directives.start[k].handle,
(char *)document2->tag_directives.start[k].handle) != 0)
|| (strcmp((char *)document1->tag_directives.start[k].prefix,
(char *)document2->tag_directives.start[k].prefix) != 0))
return 0;
}
if ((document1->nodes.top - document1->nodes.start) !=
(document2->nodes.top - document2->nodes.start))
return 0;
if (document1->nodes.top != document1->nodes.start) {
if (!compare_nodes(document1, 1, document2, 1, 0))
return 0;
}
return 1;
}
int print_output(char *name, unsigned char *buffer, size_t size, int count)
{
FILE *file;
char data[BUFFER_SIZE];
size_t data_size = 1;
size_t total_size = 0;
if (count >= 0) {
printf("FAILED (at the document #%d)\nSOURCE:\n", count+1);
}
file = fopen(name, "rb");
assert(file);
while (data_size > 0) {
data_size = fread(data, 1, BUFFER_SIZE, file);
assert(!ferror(file));
if (!data_size) break;
assert(fwrite(data, 1, data_size, stdout) == data_size);
total_size += data_size;
if (feof(file)) break;
}
fclose(file);
printf("#### (length: %zd)\n", total_size);
printf("OUTPUT:\n%s#### (length: %zd)\n", buffer, size);
return 0;
}
int
main(int argc, char *argv[])
{
int number;
int canonical = 0;
int unicode = 0;
number = 1;
while (number < argc) {
if (strcmp(argv[number], "-c") == 0) {
canonical = 1;
}
else if (strcmp(argv[number], "-u") == 0) {
unicode = 1;
}
else if (argv[number][0] == '-') {
printf("Unknown option: '%s'\n", argv[number]);
return 0;
}
if (argv[number][0] == '-') {
if (number < argc-1) {
memmove(argv+number, argv+number+1, (argc-number-1)*sizeof(char *));
}
argc --;
}
else {
number ++;
}
}
if (argc < 2) {
printf("Usage: %s [-c] [-u] file1.yaml ...\n", argv[0]);
return 0;
}
for (number = 1; number < argc; number ++)
{
FILE *file;
yaml_parser_t parser;
yaml_emitter_t emitter;
yaml_document_t document;
unsigned char buffer[BUFFER_SIZE+1];
size_t written = 0;
yaml_document_t documents[MAX_DOCUMENTS];
size_t document_number = 0;
int done = 0;
int count = 0;
int error = 0;
int k;
memset(buffer, 0, BUFFER_SIZE+1);
memset(documents, 0, MAX_DOCUMENTS*sizeof(yaml_document_t));
printf("[%d] Loading, dumping, and loading again '%s': ", number, argv[number]);
fflush(stdout);
file = fopen(argv[number], "rb");
assert(file);
assert(yaml_parser_initialize(&parser));
yaml_parser_set_input_file(&parser, file);
assert(yaml_emitter_initialize(&emitter));
if (canonical) {
yaml_emitter_set_canonical(&emitter, 1);
}
if (unicode) {
yaml_emitter_set_unicode(&emitter, 1);
}
yaml_emitter_set_output_string(&emitter, buffer, BUFFER_SIZE, &written);
yaml_emitter_open(&emitter);
while (!done)
{
if (!yaml_parser_load(&parser, &document)) {
error = 1;
break;
}
done = (!yaml_document_get_root_node(&document));
if (!done) {
assert(document_number < MAX_DOCUMENTS);
assert(copy_document(&(documents[document_number++]), &document));
assert(yaml_emitter_dump(&emitter, &document) ||
(yaml_emitter_flush(&emitter) && print_output(argv[number], buffer, written, count)));
count ++;
}
else {
yaml_document_delete(&document);
}
}
yaml_parser_delete(&parser);
assert(!fclose(file));
yaml_emitter_close(&emitter);
yaml_emitter_delete(&emitter);
if (!error)
{
count = done = 0;
assert(yaml_parser_initialize(&parser));
yaml_parser_set_input_string(&parser, buffer, written);
while (!done)
{
assert(yaml_parser_load(&parser, &document) || print_output(argv[number], buffer, written, count));
done = (!yaml_document_get_root_node(&document));
if (!done) {
assert(compare_documents(documents+count, &document) || print_output(argv[number], buffer, written, count));
count ++;
}
yaml_document_delete(&document);
}
yaml_parser_delete(&parser);
}
for (k = 0; k < document_number; k ++) {
yaml_document_delete(documents+k);
}
printf("PASSED (length: %zd)\n", written);
print_output(argv[number], buffer, written, -1);
}
return 0;
}
|
the_stack_data/3262749.c
|
/* This testcase is part of GDB, the GNU debugger.
Copyright 2014-2015 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
extern int shlib_1_func (void);
int
main ()
{
/* We need a reference to shlib_1_func to make sure its shlib is
not discarded from the link. This happens on windows. */
int x = shlib_1_func ();
return 0;
}
|
the_stack_data/6259.c
|
#include<stdio.h>
#include<stdlib.h>
typedef struct mynode
{
int data;
struct mynode* next;
}ListNode;
void addNode(ListNode** head,int data);
void addlast(ListNode** head,int data);
void traverse(ListNode* head);
int count(ListNode* head);
int main()
{
//Make a search and a count function
ListNode* head=NULL;
int i;
for(i=1;i<=10;i++)
//addNode(&head,i);
addlast(&head,i);
traverse(head);
printf("\nCount = %d",count(head));
return 0;
}
int count(ListNode* head)
{
int n=0;
while(head!=NULL)
{
n++;
head=head->next;
}
return n;
}
void addNode(ListNode** head,int data)
{
int left,right;
ListNode* temp=(ListNode*)malloc(sizeof(ListNode));
temp->next=*head;
temp->data=data;
*head=temp;
}
void addlast(ListNode** head,int data)
{
ListNode* p;
ListNode* temp=(ListNode*)malloc(sizeof(ListNode));
temp->next=NULL;
temp->data=data;
if(*head==NULL)
{
*head=temp;
return;
}
p=*head;
while (p->next!=NULL)
{
p=p->next;
}
p->next=temp;
}
void traverse(ListNode* head)
{
printf("\n");
while(head!=NULL)
{
printf("%d,",head->data);
head=head->next;
}
printf("\n");
}
|
the_stack_data/79418.c
|
extern void __VERIFIER_error();
#include <stdio.h>
#include <stdlib.h>
struct JoinPoint {
int a;
int b;
void *(*fp)(struct JoinPoint * );
};
void * func1(struct JoinPoint * jp){
struct JoinPoint * x = malloc(sizeof(struct JoinPoint));
x->a = 1;
x->b = 1;
return (void *) x;
}
void * func2(struct JoinPoint * jp) {
__VERIFIER_error();
return 0;
}
int main()
{
struct JoinPoint *jp = malloc(sizeof(struct JoinPoint));
jp->a = 0;
jp->b = 0;
jp->fp = &func1;
struct JoinPoint * y = (struct JoinPoint *) jp->fp(jp);
struct JoinPoint ** x = &y;
printf("%d, %d\n", (*x)->a, (*x)->b);
free(*x);
jp->fp = &func2;
y = (struct JoinPoint *) jp->fp(jp);
free(jp);
return 0;
}
|
the_stack_data/154826752.c
|
/* -*- mode: C; c-basic-offset: 3; -*- */
/*--------------------------------------------------------------------*/
/*--- Reading of ARM(32) EXIDX unwind information readexidx.c ---*/
/*--------------------------------------------------------------------*/
/*
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2014-2017 Mozilla Foundation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307, USA.
The GNU General Public License is contained in the file COPYING.
*/
/* libunwind - a platform-independent unwind library
Copyright 2011 Linaro Limited
This file is part of libunwind.
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. */
// Copyright (c) 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Derived originally from libunwind, with very extensive modifications.
/* Contributed by Julian Seward <[email protected]> */
// This file translates EXIDX unwind information into the same format
// that Valgrind uses for CFI information. Hence Valgrind's CFI
// unwinding abilities also become usable for EXIDX.
//
// See: "Exception Handling ABI for the ARM Architecture", ARM IHI 0038A
// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0038a/IHI0038A_ehabi.pdf
// EXIDX data is presented in two parts:
//
// * an index table. This contains two words per routine,
// the first of which identifies the routine, and the second
// of which is a reference to the unwind bytecode. If the
// bytecode is very compact -- 3 bytes or less -- it can be
// stored directly in the second word.
//
// * an area containing the unwind bytecodes.
//
// General flow is: ML_(read_exidx) iterates over all
// of the index table entries (pairs). For each entry, it:
//
// * calls ExtabEntryExtract to copy the bytecode out into
// an intermediate buffer.
// * uses ExtabEntryDecode to parse the intermediate
// buffer. Each bytecode instruction is bundled into a
// arm_ex_to_module::extab_data structure, and handed to ..
//
// * .. TranslateCmd, which generates the pseudo-CFI
// records that Valgrind stores.
// This file is derived from the following files in the Mozilla tree
// toolkit/crashreporter/google-breakpad:
// src/common/arm_ex_to_module.cc
// src/common/arm_ex_reader.cc
#if defined(VGA_arm)
#include "pub_core_basics.h"
#include "pub_core_libcbase.h"
#include "pub_core_libcprint.h"
#include "pub_core_libcassert.h"
#include "pub_core_options.h"
#include "priv_storage.h"
#include "priv_readexidx.h"
static void complain ( const HChar* str )
{
if (!VG_(clo_xml) && VG_(clo_verbosity) > 1)
VG_(message)(Vg_UserMsg,
" Warning: whilst reading EXIDX: %s\n", str);
}
/*------------------------------------------------------------*/
/*--- MemoryRange ---*/
/*------------------------------------------------------------*/
typedef struct { Addr start; SizeT len; } MemoryRange;
/* Initialise |mr| for [start .. start+len). Zero ranges are allowed,
but wraparounds are not. Returns True on success. */
static Bool MemoryRange__init ( /*OUT*/MemoryRange* mr,
const void* startV, SizeT len )
{
VG_(memset)(mr, 0, sizeof(*mr));
/* This relies on Addr being unsigned. */
Addr start = (Addr)startV;
if (len > 0 && start + len - 1 < start) {
return False;
}
mr->start = start;
mr->len = len;
return True;
}
static Bool MemoryRange__covers ( MemoryRange* mr,
const void* startV, SizeT len )
{
vg_assert(len > 0);
if (mr->len == 0) {
return False;
}
Addr start = (Addr)startV;
return start >= mr->start && start + len - 1 <= mr->start + mr->len - 1;
}
/*------------------------------------------------------------*/
/*--- (Pass 1 of 3) The EXIDX extractor ---*/
/*------------------------------------------------------------*/
#define ARM_EXIDX_CANT_UNWIND 0x00000001
#define ARM_EXIDX_COMPACT 0x80000000
#define ARM_EXTBL_OP_FINISH 0xb0
#define ARM_EXIDX_TABLE_LIMIT (255*4)
/* These are in the ARM-defined format, so their layout is important. */
typedef
struct { UInt addr; UInt data; }
ExidxEntry;
typedef
enum {
ExSuccess=1, // success
ExInBufOverflow, // out-of-range while reading .exidx
ExOutBufOverflow, // output buffer is too small
ExCantUnwind, // this function is marked CANT_UNWIND
ExCantRepresent, // entry valid, but we can't represent it
ExInvalid // entry is invalid
}
ExExtractResult;
/* Helper function for fishing bits out of the EXIDX representation. */
static const void* Prel31ToAddr(const void* addr)
{
UInt offset32 = *(const UInt*)addr;
// sign extend offset32[30:0] to 64 bits -- copy bit 30 to positions
// 63:31 inclusive.
ULong offset64 = offset32;
if (offset64 & (1ULL << 30))
offset64 |= 0xFFFFFFFF80000000ULL;
else
offset64 &= 0x000000007FFFFFFFULL;
return ((const UChar*)addr) + (UWord)offset64;
}
// Extract unwind bytecode for the function denoted by |entry| into |buf|,
// and return the number of bytes of |buf| written, along with a code
// indicating the outcome.
static
ExExtractResult ExtabEntryExtract ( MemoryRange* mr_exidx,
MemoryRange* mr_extab,
const ExidxEntry* entry,
UChar* buf, SizeT buf_size,
/*OUT*/SizeT* buf_used)
{
Bool ok;
MemoryRange mr_out;
ok = MemoryRange__init(&mr_out, buf, buf_size);
if (!ok) return ExOutBufOverflow;
*buf_used = 0;
# define PUT_BUF_U8(_byte) \
do { if (!MemoryRange__covers(&mr_out, &buf[*buf_used], 1)) \
return ExOutBufOverflow; \
buf[(*buf_used)++] = (_byte); } while (0)
# define GET_EX_U32(_lval, _addr, _mr) \
do { if (!MemoryRange__covers((_mr), (const void*)(_addr), 4)) \
return ExInBufOverflow; \
(_lval) = *(const UInt*)(_addr); } while (0)
# define GET_EXIDX_U32(_lval, _addr) \
GET_EX_U32(_lval, _addr, mr_exidx)
# define GET_EXTAB_U32(_lval, _addr) \
GET_EX_U32(_lval, _addr, mr_extab)
UInt data;
GET_EXIDX_U32(data, &entry->data);
// A function can be marked CANT_UNWIND if (eg) it is known to be
// at the bottom of the stack.
if (data == ARM_EXIDX_CANT_UNWIND)
return ExCantUnwind;
UInt pers; // personality number
UInt extra; // number of extra data words required
UInt extra_allowed; // number of extra data words allowed
const UInt* extbl_data; // the handler entry, if not inlined
if (data & ARM_EXIDX_COMPACT) {
// The handler table entry has been inlined into the index table entry.
// In this case it can only be an ARM-defined compact model, since
// bit 31 is 1. Only personalities 0, 1 and 2 are defined for the
// ARM compact model, but 1 and 2 are "Long format" and may require
// extra data words. Hence the allowable personalities here are:
// personality 0, in which case 'extra' has no meaning
// personality 1, with zero extra words
// personality 2, with zero extra words
extbl_data = NULL;
pers = (data >> 24) & 0x0F;
extra = (data >> 16) & 0xFF;
extra_allowed = 0;
}
else {
// The index table entry is a pointer to the handler entry. Note
// that Prel31ToAddr will read the given address, but we already
// range-checked above.
extbl_data = Prel31ToAddr(&entry->data);
GET_EXTAB_U32(data, extbl_data);
if (!(data & ARM_EXIDX_COMPACT)) {
// This denotes a "generic model" handler. That will involve
// executing arbitrary machine code, which is something we
// can't represent here; hence reject it.
return ExCantRepresent;
}
// So we have a compact model representation. Again, 3 possible
// personalities, but this time up to 255 allowable extra words.
pers = (data >> 24) & 0x0F;
extra = (data >> 16) & 0xFF;
extra_allowed = 255;
extbl_data++;
}
// Now look at the handler table entry. The first word is |data|
// and subsequent words start at |*extbl_data|. The number of
// extra words to use is |extra|, provided that the personality
// allows extra words. Even if it does, none may be available --
// extra_allowed is the maximum number of extra words allowed. */
if (pers == 0) {
// "Su16" in the documentation -- 3 unwinding insn bytes
// |extra| has no meaning here; instead that byte is an unwind-info byte
PUT_BUF_U8(data >> 16);
PUT_BUF_U8(data >> 8);
PUT_BUF_U8(data);
}
else if ((pers == 1 || pers == 2) && extra <= extra_allowed) {
// "Lu16" or "Lu32" respectively -- 2 unwinding insn bytes,
// and up to 255 extra words.
PUT_BUF_U8(data >> 8);
PUT_BUF_U8(data);
UInt j;
for (j = 0; j < extra; j++) {
GET_EXTAB_U32(data, extbl_data);
extbl_data++;
PUT_BUF_U8(data >> 24);
PUT_BUF_U8(data >> 16);
PUT_BUF_U8(data >> 8);
PUT_BUF_U8(data >> 0);
}
}
else {
// The entry is invalid.
return ExInvalid;
}
// Make sure the entry is terminated with "FINISH"
if (*buf_used > 0 && buf[(*buf_used) - 1] != ARM_EXTBL_OP_FINISH)
PUT_BUF_U8(ARM_EXTBL_OP_FINISH);
return ExSuccess;
# undef GET_EXTAB_U32
# undef GET_EXIDX_U32
# undef GET_U32
# undef PUT_BUF_U8
}
/*------------------------------------------------------------*/
/*--- (Pass 2 of 3) The EXIDX decoder ---*/
/*------------------------------------------------------------*/
/* This (ExtabData) is an intermediate structure, used to carry
information from the decoder (pass 2) to the summariser (pass 3).
I don't think its layout is important. */
typedef
enum {
ARM_EXIDX_CMD_FINISH=0x100,
ARM_EXIDX_CMD_SUB_FROM_VSP,
ARM_EXIDX_CMD_ADD_TO_VSP,
ARM_EXIDX_CMD_REG_POP,
ARM_EXIDX_CMD_REG_TO_SP,
ARM_EXIDX_CMD_VFP_POP,
ARM_EXIDX_CMD_WREG_POP,
ARM_EXIDX_CMD_WCGR_POP,
ARM_EXIDX_CMD_RESERVED,
ARM_EXIDX_CMD_REFUSED
}
ExtabCmd;
static const HChar* showExtabCmd ( ExtabCmd cmd ) {
switch (cmd) {
case ARM_EXIDX_CMD_FINISH: return "FINISH";
case ARM_EXIDX_CMD_SUB_FROM_VSP: return "SUB_FROM_VSP";
case ARM_EXIDX_CMD_ADD_TO_VSP: return "ADD_TO_VSP";
case ARM_EXIDX_CMD_REG_POP: return "REG_POP";
case ARM_EXIDX_CMD_REG_TO_SP: return "REG_TO_SP";
case ARM_EXIDX_CMD_VFP_POP: return "VFP_POP";
case ARM_EXIDX_CMD_WREG_POP: return "WREG_POP";
case ARM_EXIDX_CMD_WCGR_POP: return "WCGR_POP";
case ARM_EXIDX_CMD_RESERVED: return "RESERVED";
case ARM_EXIDX_CMD_REFUSED: return "REFUSED";
default: return "???";
}
}
typedef
struct { ExtabCmd cmd; UInt data; }
ExtabData;
static void ppExtabData ( const ExtabData* etd ) {
VG_(printf)("ExtabData{%-12s 0x%08x}", showExtabCmd(etd->cmd), etd->data);
}
enum extab_cmd_flags {
ARM_EXIDX_VFP_SHIFT_16 = 1 << 16,
ARM_EXIDX_VFP_FSTMD = 1 << 17, // distinguishes FSTMxxD from FSTMxxX
};
/* Forwards */
typedef struct _SummState SummState;
static Int TranslateCmd(/*MOD*/SummState* state, const ExtabData* edata);
// Take the unwind information extracted by ExtabEntryExtract
// and parse it into frame-unwind instructions. These are as
// specified in "Table 4, ARM-defined frame-unwinding instructions"
// in the specification document detailed in comments at the top
// of this file.
//
// This reads from |buf[0, +data_size)|. It checks for overruns of
// the input buffer and returns a negative value if that happens, or
// for any other failure cases. It returns zero in case of success.
// Whilst reading the input, it dumps the result in |*state|.
static
Int ExtabEntryDecode(/*OUT*/SummState* state, const UChar* buf, SizeT buf_size)
{
if (buf == NULL || buf_size == 0)
return -3;
MemoryRange mr_in;
Bool ok = MemoryRange__init(&mr_in, buf, buf_size);
if (!ok)
return -2;
# define GET_BUF_U8(_lval) \
do { if (!MemoryRange__covers(&mr_in, buf, 1)) \
return -4; \
(_lval) = *(buf++); } while (0)
const UChar* end = buf + buf_size;
while (buf < end) {
ExtabData edata;
VG_(bzero_inline)(&edata, sizeof(edata));
UChar op;
GET_BUF_U8(op);
if ((op & 0xc0) == 0x00) {
// vsp = vsp + (xxxxxx << 2) + 4
edata.cmd = ARM_EXIDX_CMD_ADD_TO_VSP;
edata.data = (((Int)op & 0x3f) << 2) + 4;
}
else if ((op & 0xc0) == 0x40) {
// vsp = vsp - (xxxxxx << 2) - 4
edata.cmd = ARM_EXIDX_CMD_SUB_FROM_VSP;
edata.data = (((Int)op & 0x3f) << 2) + 4;
}
else if ((op & 0xf0) == 0x80) {
UChar op2;
GET_BUF_U8(op2);
if (op == 0x80 && op2 == 0x00) {
// Refuse to unwind
edata.cmd = ARM_EXIDX_CMD_REFUSED;
} else {
// Pop up to 12 integer registers under masks {r15-r12},{r11-r4}
edata.cmd = ARM_EXIDX_CMD_REG_POP;
edata.data = ((op & 0xf) << 8) | op2;
edata.data = edata.data << 4;
}
}
else if ((op & 0xf0) == 0x90) {
if (op == 0x9d || op == 0x9f) {
// 9d: Reserved as prefix for ARM register to register moves
// 9f: Reserved as prefix for Intel Wireless MMX reg to reg moves
edata.cmd = ARM_EXIDX_CMD_RESERVED;
} else {
// Set vsp = r[nnnn]
edata.cmd = ARM_EXIDX_CMD_REG_TO_SP;
edata.data = op & 0x0f;
}
}
else if ((op & 0xf0) == 0xa0) {
// Pop r4 to r[4+nnn], or
// Pop r4 to r[4+nnn] and r14
Int nnn = (op & 0x07);
edata.data = (1 << (nnn + 1)) - 1;
edata.data = edata.data << 4;
if (op & 0x08) edata.data |= 1 << 14;
edata.cmd = ARM_EXIDX_CMD_REG_POP;
}
else if (op == ARM_EXTBL_OP_FINISH) {
// Finish
edata.cmd = ARM_EXIDX_CMD_FINISH;
buf = end;
}
else if (op == 0xb1) {
UChar op2;
GET_BUF_U8(op2);
if (op2 == 0 || (op2 & 0xf0)) {
// Spare
edata.cmd = ARM_EXIDX_CMD_RESERVED;
} else {
// Pop integer registers under mask {r3,r2,r1,r0}
edata.cmd = ARM_EXIDX_CMD_REG_POP;
edata.data = op2 & 0x0f;
}
}
else if (op == 0xb2) {
// vsp = vsp + 0x204 + (uleb128 << 2)
ULong offset = 0;
UChar byte, shift = 0;
do {
GET_BUF_U8(byte);
offset |= (byte & 0x7f) << shift;
shift += 7;
} while ((byte & 0x80) && buf < end);
edata.data = offset * 4 + 0x204;
edata.cmd = ARM_EXIDX_CMD_ADD_TO_VSP;
}
else if (op == 0xb3 || op == 0xc8 || op == 0xc9) {
// b3: Pop VFP regs D[ssss] to D[ssss+cccc], FSTMFDX-ishly
// c8: Pop VFP regs D[16+ssss] to D[16+ssss+cccc], FSTMFDD-ishly
// c9: Pop VFP regs D[ssss] to D[ssss+cccc], FSTMFDD-ishly
edata.cmd = ARM_EXIDX_CMD_VFP_POP;
GET_BUF_U8(edata.data);
if (op == 0xc8) edata.data |= ARM_EXIDX_VFP_SHIFT_16;
if (op != 0xb3) edata.data |= ARM_EXIDX_VFP_FSTMD;
}
else if ((op & 0xf8) == 0xb8 || (op & 0xf8) == 0xd0) {
// b8: Pop VFP regs D[8] to D[8+nnn], FSTMFDX-ishly
// d0: Pop VFP regs D[8] to D[8+nnn], FSTMFDD-ishly
edata.cmd = ARM_EXIDX_CMD_VFP_POP;
edata.data = 0x80 | (op & 0x07);
if ((op & 0xf8) == 0xd0) edata.data |= ARM_EXIDX_VFP_FSTMD;
}
else if (op >= 0xc0 && op <= 0xc5) {
// Intel Wireless MMX pop wR[10]-wr[10+nnn], nnn != 6,7
edata.cmd = ARM_EXIDX_CMD_WREG_POP;
edata.data = 0xa0 | (op & 0x07);
}
else if (op == 0xc6) {
// Intel Wireless MMX pop wR[ssss] to wR[ssss+cccc]
edata.cmd = ARM_EXIDX_CMD_WREG_POP;
GET_BUF_U8(edata.data);
}
else if (op == 0xc7) {
UChar op2;
GET_BUF_U8(op2);
if (op2 == 0 || (op2 & 0xf0)) {
// Spare
edata.cmd = ARM_EXIDX_CMD_RESERVED;
} else {
// Intel Wireless MMX pop wCGR registers under mask {wCGR3,2,1,0}
edata.cmd = ARM_EXIDX_CMD_WCGR_POP;
edata.data = op2 & 0x0f;
}
}
else {
// Spare
edata.cmd = ARM_EXIDX_CMD_RESERVED;
}
if (0)
VG_(printf)(" edata: cmd %08x data %08x\n",
(UInt)edata.cmd, edata.data);
Int ret = TranslateCmd ( state, &edata );
if (ret < 0) return ret;
}
return 0;
# undef GET_BUF_U8
}
/*------------------------------------------------------------*/
/*--- (Pass 3 of 3) The EXIDX summariser ---*/
/*------------------------------------------------------------*/
/* In this translation into DiCfSI_m, we're going to have the CFA play
the role of the VSP. That means that the VSP can be exactly any of
the CFA expressions, viz: {r7,r11,r12,r13) +/- offset.
All of this would be a lot simpler if the DiCfSI_m representation
was just a bit more expressive and orthogonal. But it isn't.
The central difficulty is that, although we can track changes
to the offset of VSP (via vsp_off), we can't deal with assignments
of an entirely new expression to it, because the existing
rules in |cfi| will almost certainly refer to the CFA, and so
changing it will make them invalid. Hence, below:
* for the case ARM_EXIDX_CMD_REG_TO_SP we simply disallow
assignment, and hence give up, if any rule refers to CFA
* for the case ARM_EXIDX_CMD_REG_POP, the SP (hence, VSP) is
updated by the pop, give up.
This is an ugly hack to work around not having a better (LUL-like)
expression representation. That said, these restrictions don't
appear to be a big problem in practice.
*/
struct _SummState {
// The DiCfSI_m under construction
DiCfSI_m cfi;
Int vsp_off;
// For generating CFI register expressions, if needed.
DebugInfo* di;
};
/* Generate a trivial CfiExpr, for the ARM(32) integer register
numbered |gprNo|. First ensure this DebugInfo has a cfsi_expr
array in which to park it. Returns -1 if |gprNo| cannot be
represented, otherwise returns a value >= 0. */
static
Int gen_CfiExpr_CfiReg_ARM_GPR ( /*MB_MOD*/DebugInfo* di, UInt gprNo )
{
CfiReg creg = Creg_INVALID;
switch (gprNo) {
case 13: creg = Creg_ARM_R13; break;
case 12: creg = Creg_ARM_R12; break;
case 15: creg = Creg_ARM_R15; break;
case 14: creg = Creg_ARM_R14; break;
case 7: creg = Creg_ARM_R7; break;
default: break;
}
if (creg == Creg_INVALID) {
return -1;
}
if (!di->cfsi_exprs) {
di->cfsi_exprs = VG_(newXA)( ML_(dinfo_zalloc), "di.gCCAG",
ML_(dinfo_free), sizeof(CfiExpr) );
}
Int res = ML_(CfiExpr_CfiReg)( di->cfsi_exprs, creg );
vg_assert(res >= 0);
return res;
}
/* Given a DiCfSI_m, find the _how/_off pair for the given ARM(32) GPR
number inside |cfsi_m|, or return NULL for both if that register
number is not represented. */
static
void maybeFindExprForRegno( /*OUT*/UChar** howPP, /*OUT*/Int** offPP,
DiCfSI_m* cfsi_m, Int regNo )
{
switch (regNo) {
case 15: *howPP = &cfsi_m->ra_how; *offPP = &cfsi_m->ra_off; return;
case 14: *howPP = &cfsi_m->r14_how; *offPP = &cfsi_m->r14_off; return;
case 13: *howPP = &cfsi_m->r13_how; *offPP = &cfsi_m->r13_off; return;
case 12: *howPP = &cfsi_m->r12_how; *offPP = &cfsi_m->r12_off; return;
case 11: *howPP = &cfsi_m->r11_how; *offPP = &cfsi_m->r11_off; return;
case 7: *howPP = &cfsi_m->r7_how; *offPP = &cfsi_m->r7_off; return;
default: break;
}
*howPP = NULL; *offPP = NULL;
}
/* Set cfi.cfa_{how,off} so as to be a copy of the expression denoted
by (how,off), if it is possible to do so. Returns True on
success. */
static
Bool setCFAfromCFIR( /*MOD*/DiCfSI_m* cfi, XArray*/*CfiExpr*/ cfsi_exprs,
UChar how, Int off )
{
switch (how) {
case CFIR_EXPR:
if (!cfsi_exprs) return False;
CfiExpr* e = (CfiExpr*)VG_(indexXA)(cfsi_exprs, off);
if (e->tag != Cex_CfiReg) return False;
if (e->Cex.CfiReg.reg == Creg_ARM_R7) {
cfi->cfa_how = CFIC_ARM_R7REL;
cfi->cfa_off = 0;
return True;
}
ML_(ppCfiExpr)(cfsi_exprs, off);
vg_assert(0);
default:
break;
}
VG_(printf)("setCFAfromCFIR: FAIL: how %d off %d\n", how, off);
vg_assert(0);
return False;
}
#define ARM_EXBUF_START(x) (((x) >> 4) & 0x0f)
#define ARM_EXBUF_COUNT(x) ((x) & 0x0f)
#define ARM_EXBUF_END(x) (ARM_EXBUF_START(x) + ARM_EXBUF_COUNT(x))
static Bool mentionsCFA ( DiCfSI_m* cfi )
{
# define MENTIONS_CFA(_how) ((_how) == CFIR_CFAREL || (_how) == CFIR_MEMCFAREL)
if (MENTIONS_CFA(cfi->ra_how)) return True;
if (MENTIONS_CFA(cfi->r14_how)) return True;
if (MENTIONS_CFA(cfi->r13_how)) return True;
if (MENTIONS_CFA(cfi->r12_how)) return True;
if (MENTIONS_CFA(cfi->r11_how)) return True;
if (MENTIONS_CFA(cfi->r7_how)) return True;
return False;
# undef MENTIONS_CFA
}
// Translate command from extab_data to command for Module.
static
Int TranslateCmd(/*MOD*/SummState* state, const ExtabData* edata)
{
/* Stay sane: check that the CFA has the expected form. */
vg_assert(state);
switch (state->cfi.cfa_how) {
case CFIC_ARM_R13REL: case CFIC_ARM_R12REL:
case CFIC_ARM_R11REL: case CFIC_ARM_R7REL: break;
default: vg_assert(0);
}
if (0) {
VG_(printf)(" TranslateCmd: ");
ppExtabData(edata);
VG_(printf)("\n");
}
Int ret = 0;
switch (edata->cmd) {
case ARM_EXIDX_CMD_FINISH:
/* Copy LR to PC if there isn't currently a rule for PC in force. */
if (state->cfi.ra_how == CFIR_UNKNOWN) {
if (state->cfi.r14_how == CFIR_UNKNOWN) {
state->cfi.ra_how = CFIR_EXPR;
state->cfi.ra_off = gen_CfiExpr_CfiReg_ARM_GPR(state->di, 14);
vg_assert(state->cfi.ra_off >= 0);
} else {
state->cfi.ra_how = state->cfi.r14_how;
state->cfi.ra_off = state->cfi.r14_off;
}
}
break;
case ARM_EXIDX_CMD_SUB_FROM_VSP:
state->vsp_off -= (Int)(edata->data);
break;
case ARM_EXIDX_CMD_ADD_TO_VSP:
state->vsp_off += (Int)(edata->data);
break;
case ARM_EXIDX_CMD_REG_POP: {
UInt i;
for (i = 0; i < 16; i++) {
if (edata->data & (1 << i)) {
// See if we're summarising for int register |i|. If so,
// describe how to pull it off the stack. The cast of |i| is
// a bit of a kludge but works because DW_REG_ARM_Rn has the
// value |n|, for 0 <= |n| <= 15 -- that is, for the ARM
// general-purpose registers.
UChar* rX_howP = NULL;
Int* rX_offP = NULL;
maybeFindExprForRegno(&rX_howP, &rX_offP, &state->cfi, i);
if (rX_howP) {
vg_assert(rX_offP);
/* rX_howP and rX_offP point at one of the rX fields
in |state->cfi|. Hence the following assignments
are really updating |state->cfi|. */
*rX_howP = CFIR_MEMCFAREL;
*rX_offP = state->vsp_off;
} else {
/* We're not tracking this register, so ignore it. */
vg_assert(!rX_offP);
}
state->vsp_off += 4;
}
}
/* Set cfa in case the SP got popped. */
if (edata->data & (1 << 13)) {
// vsp = curr_rules_.mR13expr;
//state->cfi.cfa_how =
//state->cfi.cfa_off =
//state->vsp_off = 0;
// If this happens, it would make the existing CFA references
// in the summary invalid. So give up instead.
goto cant_summarise;
}
break;
}
case ARM_EXIDX_CMD_REG_TO_SP: {
/* We're generating a new value for the CFA/VSP here. Hence,
if the summary already refers to the CFA at all, we can't
go any further, and have to abandon summarisation. */
if (mentionsCFA(&state->cfi))
goto cant_summarise;
vg_assert(edata->data < 16);
Int reg_no = edata->data;
// Same comment as above, re the casting of |reg_no|, applies.
UChar* rX_howP = NULL;
Int* rX_offP = NULL;
maybeFindExprForRegno(&rX_howP, &rX_offP, &state->cfi, reg_no);
if (rX_howP) {
vg_assert(rX_offP);
if (*rX_howP == CFIR_UNKNOWN) {
//curr_rules_.mR13expr = LExpr(LExpr::NODEREF, reg_no, 0);
Int expr_ix = gen_CfiExpr_CfiReg_ARM_GPR(state->di, reg_no);
if (expr_ix >= 0) {
state->cfi.r13_how = CFIR_EXPR;
state->cfi.r13_off = expr_ix;
} else {
goto cant_summarise;
}
} else {
//curr_rules_.mR13expr = *reg_exprP;
state->cfi.r13_how = *rX_howP;
state->cfi.r13_off = *rX_offP;
}
//vsp = curr_rules_.mR13expr;
Bool ok = setCFAfromCFIR( &state->cfi, state->di->cfsi_exprs,
state->cfi.r13_how, state->cfi.r13_off );
if (!ok) goto cant_summarise;
state->vsp_off = 0;
} else {
vg_assert(!rX_offP);
}
break;
}
case ARM_EXIDX_CMD_VFP_POP: {
/* Don't recover VFP registers, but be sure to adjust the stack
pointer. */
UInt i;
for (i = ARM_EXBUF_START(edata->data);
i <= ARM_EXBUF_END(edata->data); i++) {
state->vsp_off += 8;
}
if (!(edata->data & ARM_EXIDX_VFP_FSTMD)) {
state->vsp_off += 4;
}
break;
}
case ARM_EXIDX_CMD_WREG_POP: {
UInt i;
for (i = ARM_EXBUF_START(edata->data);
i <= ARM_EXBUF_END(edata->data); i++) {
state->vsp_off += 8;
}
break;
}
case ARM_EXIDX_CMD_WCGR_POP: {
UInt i;
// Pop wCGR registers under mask {wCGR3,2,1,0}, hence "i < 4"
for (i = 0; i < 4; i++) {
if (edata->data & (1 << i)) {
state->vsp_off += 4;
}
}
break;
}
case ARM_EXIDX_CMD_REFUSED:
case ARM_EXIDX_CMD_RESERVED:
ret = -1;
break;
}
return ret;
cant_summarise:
return -10;
}
/* Initialise the EXIDX summariser, by writing initial values in |state|. */
static
void AddStackFrame ( /*OUT*/SummState* state,
DebugInfo* di )
{
VG_(bzero_inline)(state, sizeof(*state));
state->vsp_off = 0;
state->di = di;
/* Initialise the DiCfSI_m that we are building. */
state->cfi.cfa_how = CFIC_ARM_R13REL;
state->cfi.cfa_off = 0;
state->cfi.ra_how = CFIR_UNKNOWN;
state->cfi.r14_how = CFIR_UNKNOWN;
state->cfi.r13_how = CFIR_UNKNOWN;
state->cfi.r12_how = CFIR_UNKNOWN;
state->cfi.r11_how = CFIR_UNKNOWN;
state->cfi.r7_how = CFIR_UNKNOWN;
}
static
void SubmitStackFrame( /*MOD*/DebugInfo* di,
SummState* state, Addr avma, SizeT len )
{
// JRS: I'm really not sure what this means, or if it is necessary
// return address always winds up in pc
//stack_frame_entry_->initial_rules[ustr__ZDra()] // ".ra"
// = stack_frame_entry_->initial_rules[ustr__pc()];
// maybe don't need to do anything here?
// the final value of vsp is the new value of sp.
switch (state->cfi.cfa_how) {
case CFIC_ARM_R13REL: case CFIC_ARM_R12REL:
case CFIC_ARM_R11REL: case CFIC_ARM_R7REL: break;
default: vg_assert(0);
}
state->cfi.r13_how = CFIR_CFAREL;
state->cfi.r13_off = state->vsp_off;
// Finally, add the completed RuleSet to the SecMap
if (len > 0) {
// Futz with the rules for r4 .. r11 in the same way as happens
// with the CFI summariser:
/* Mark callee-saved registers (r4 .. r11) as unchanged, if there is
no other information about them. FIXME: do this just once, at
the point where the ruleset is committed. */
if (state->cfi.r7_how == CFIR_UNKNOWN) {
state->cfi.r7_how = CFIR_SAME;
state->cfi.r7_off = 0;
}
if (state->cfi.r11_how == CFIR_UNKNOWN) {
state->cfi.r11_how = CFIR_SAME;
state->cfi.r11_off = 0;
}
if (state->cfi.r12_how == CFIR_UNKNOWN) {
state->cfi.r12_how = CFIR_SAME;
state->cfi.r12_off = 0;
}
if (state->cfi.r14_how == CFIR_UNKNOWN) {
state->cfi.r14_how = CFIR_SAME;
state->cfi.r14_off = 0;
}
// And add them
ML_(addDiCfSI)(di, avma, len, &state->cfi);
if (di->trace_cfi)
ML_(ppDiCfSI)(di->cfsi_exprs, avma, len, &state->cfi);
}
}
/*------------------------------------------------------------*/
/*--- Top level ---*/
/*------------------------------------------------------------*/
void ML_(read_exidx) ( /*MOD*/DebugInfo* di,
UChar* exidx_img, SizeT exidx_size,
UChar* extab_img, SizeT extab_size,
Addr text_last_svma,
PtrdiffT text_bias )
{
if (di->trace_cfi)
VG_(printf)("BEGIN ML_(read_exidx) exidx_img=[%p, +%lu) "
"extab_img=[%p, +%lu) text_last_svma=%lx text_bias=%lx\n",
exidx_img, exidx_size, extab_img, extab_size,
text_last_svma, (UWord)text_bias);
Bool ok;
MemoryRange mr_exidx, mr_extab;
ok = MemoryRange__init(&mr_exidx, exidx_img, exidx_size);
ok = ok && MemoryRange__init(&mr_extab, extab_img, extab_size);
if (!ok) {
complain(".exidx or .extab image area wraparound");
return;
}
const ExidxEntry* start_img = (const ExidxEntry*)exidx_img;
const ExidxEntry* end_img = (const ExidxEntry*)(exidx_img + exidx_size);
if (VG_(clo_verbosity) > 1)
VG_(message)(Vg_DebugMsg, " Reading EXIDX entries: %lu available\n",
exidx_size / sizeof(ExidxEntry) );
// Iterate over each of the EXIDX entries (pairs of 32-bit words).
// These occupy the entire .exidx section.
UWord n_attempted = 0, n_successful = 0;
const ExidxEntry* entry_img;
for (entry_img = start_img; entry_img < end_img; ++entry_img) {
n_attempted++;
// Figure out the code address range that this table entry_img is
// associated with.
Addr avma = (Addr)Prel31ToAddr(&entry_img->addr);
if (di->trace_cfi)
VG_(printf)("XXX1 entry: entry->addr 0x%x, avma 0x%lx\n",
entry_img->addr, avma);
Addr next_avma;
if (entry_img < end_img - 1) {
next_avma = (Addr)Prel31ToAddr(&(entry_img+1)->addr);
} else {
// This is the last EXIDX entry in the sequence, so we don't
// have an address for the start of the next function, to limit
// this one. Instead use the address of the last byte of the
// text section associated with this .exidx section, that we
// have been given. So as to avoid junking up the CFI unwind
// tables with absurdly large address ranges in the case where
// text_last_svma_ is wrong, only use the value if it is nonzero
// and within one page of |svma|. Otherwise assume a length of 1.
//
// In some cases, gcc has been observed to finish the exidx
// section with an entry of length 1 marked CANT_UNWIND,
// presumably exactly for the purpose of giving a definite
// length for the last real entry, without having to look at
// text segment boundaries.
Addr text_last_avma = text_last_svma + text_bias;
Bool plausible;
Addr maybe_next_avma = text_last_avma + 1;
if (maybe_next_avma > avma && maybe_next_avma - avma <= 4096) {
next_avma = maybe_next_avma;
plausible = True;
} else {
next_avma = avma + 1;
plausible = False;
}
if (!plausible && avma != text_last_avma + 1) {
HChar buf[100];
VG_(snprintf)(buf, sizeof(buf),
"Implausible EXIDX last entry size %lu"
"; using 1 instead.", text_last_avma - avma);
buf[sizeof(buf)-1] = 0;
complain(buf);
}
}
// Extract the unwind info into |buf|. This might fail for
// various reasons. It involves reading both the .exidx and
// .extab sections. All accesses to those sections are
// bounds-checked.
if (di->trace_cfi)
VG_(printf)("XXX1 entry is for AVMA 0x%lx 0x%lx\n",
avma, next_avma-1);
UChar buf[ARM_EXIDX_TABLE_LIMIT];
SizeT buf_used = 0;
ExExtractResult res
= ExtabEntryExtract(&mr_exidx, &mr_extab,
entry_img, buf, sizeof(buf), &buf_used);
if (res != ExSuccess) {
// Couldn't extract the unwind info, for some reason. Move on.
switch (res) {
case ExInBufOverflow:
complain("ExtabEntryExtract: .exidx/.extab section overrun");
break;
case ExOutBufOverflow:
complain("ExtabEntryExtract: bytecode buffer overflow");
break;
case ExCantUnwind:
// Some functions are marked CantUnwind by the compiler.
// Don't record these as attempted, since that's just
// confusing, and failure to summarise them is not the fault
// of this code.
n_attempted--;
if (0)
complain("ExtabEntryExtract: function is marked CANT_UNWIND");
break;
case ExCantRepresent:
complain("ExtabEntryExtract: bytecode can't be represented");
break;
case ExInvalid:
complain("ExtabEntryExtract: index table entry is invalid");
break;
default: {
HChar mbuf[100];
VG_(snprintf)(mbuf, sizeof(mbuf),
"ExtabEntryExtract: unknown error: %d", (Int)res);
buf[sizeof(mbuf)-1] = 0;
complain(mbuf);
break;
}
}
continue;
}
// Finally, work through the unwind instructions in |buf| and
// create CFI entries that Valgrind can use. This can also fail.
// First, initialise the summariser's running state, into which
// ExtabEntryDecode will write the CFI entries.
SummState state;
AddStackFrame( &state, di );
Int ret = ExtabEntryDecode( &state, buf, buf_used );
if (ret < 0) {
/* Failed summarisation. Ignore and move on. */
HChar mbuf[100];
VG_(snprintf)(mbuf, sizeof(mbuf),
"ExtabEntryDecode: failed with error code: %d", ret);
mbuf[sizeof(mbuf)-1] = 0;
complain(mbuf);
} else {
/* Successful summarisation. Add it to the collection. */
SubmitStackFrame( di, &state, avma, next_avma - avma );
n_successful++;
}
} /* iterating over .exidx */
if (VG_(clo_verbosity) > 1)
VG_(message)(Vg_DebugMsg,
" Reading EXIDX entries: %lu attempted, %lu successful\n",
n_attempted, n_successful);
}
#endif /* defined(VGA_arm) */
/*--------------------------------------------------------------------*/
/*--- end readexidx.c ---*/
/*--------------------------------------------------------------------*/
|
the_stack_data/62636433.c
|
/*
Database "wedding" contains tables:
church
people
wedding
*/
#ifndef WEDDING
#define WEDDING
struct T_church {
double church_id;
char name[51];
char organized_by[17];
double open_date;
char continuation_of[44];
};
struct T_people {
double people_id;
char name[16];
char country[17];
char is_male[2];
double age;
};
struct T_wedding {
double church_id; // --> church.church_id
double male_id; // --> people.people_id
double female_id; // --> people.people_id
double year;
};
struct T_church
church[] = {
{ 1, "Pure Church of Christ", "Wycam Clark", 1831, "Church of Christ" },
{ 2, "Independent Church", "– Hoton", 1832, "Church of Christ" },
{ 3, "Church of Christ", "Ezra Booth", 1836, "Church of the Latter Day Saints" },
{ 4, "Church of Christ (Parrishite)", "Warren Parrish", 1837, "Church of the Latter Day Saints" },
{ 5, "Alston Church", "Isaac Russell", 1839, "Church of Jesus Christ of Latter Day Saints" },
{ 6, "Church of Christ", "William Chubby", 1830, "Church of Jesus Christ of Latter Day Saints" },
{ 7, "Church of Jesus Christ, the Bride, the Lamb's Wife", "George M. Hinkle", 1840, "Church of Jesus Christ of Latter Day Saints" },
{ 8, "Church of Christ", "Hiram Page", 1842, "Church of Jesus Christ of Latter Day Saints" },
{ 9, "True Church of Jesus Christ of Latter Day Saints", "William Law", 1844, "Church of Jesus Christ of Latter Day Saints" }
};
struct T_people
people[] = {
{ 1, "Mike Weir", "Canada", "T", 34 },
{ 2, "Juli Hanson", "Sweden", "F", 32 },
{ 3, "Ricky Barnes", "United States", "T", 30 },
{ 4, "Summer Duval", "United States", "F", 30 },
{ 5, "Todd Hamilton", "United States", "T", 27 },
{ 6, "Annie Mediate", "United States", "F", 26 },
{ 7, "Lucas Glover", "United States", "T", 31 },
{ 8, "Joe O'Hair", "United States", "F", 31 },
{ 9, "Graeme McDowell", "Northern Ireland", "T", 34 },
{ 10, "Jamie Mickelson", "United States", "F", 36 },
{ 11, "Adam Scott", "Australia", "T", 26 },
{ 12, "Danny Toms", "United States", "F", 25 }
};
struct T_wedding
wedding[] = {
{ 1, 1, 2, 2014 },
{ 3, 3, 4, 2015 },
{ 5, 5, 6, 2016 },
{ 4, 7, 8, 2016 }
};
#endif
|
the_stack_data/51348.c
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char* now()
{
time_t t;
return asctime(localtime (&t));
}
/*
Master Control Program Utility.
Records guard patrol check-ins.
*/
int main()
{
char comment[80];
char cmd[120];
fgets(comment, 80, stdin);
sprintf(cmd,
"echo '%s %s' >> reports.log",
comment, now());
system(cmd);
return 0;
}
|
the_stack_data/117875.c
|
// WARNING in kernfs_get
// https://syzkaller.appspot.com/bug?id=b52dec65c1aaaec9b3893458b13a3304303de321
// status:open
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
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 kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
int i;
for (i = 0; i < 100; i++) {
if (waitpid(-1, status, WNOHANG | __WALL) == pid)
return;
usleep(1000);
}
DIR* dir = opendir("/sys/fs/fuse/connections");
if (dir) {
for (;;) {
struct dirent* ent = readdir(dir);
if (!ent)
break;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char abort[300];
snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort",
ent->d_name);
int fd = open(abort, O_WRONLY);
if (fd == -1) {
continue;
}
if (write(fd, abort, 1) < 0) {
}
close(fd);
}
closedir(dir);
} else {
}
while (waitpid(-1, status, __WALL) != pid) {
}
}
#define SYZ_HAVE_SETUP_TEST 1
static void setup_test()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
}
#define SYZ_HAVE_RESET_TEST 1
static void reset_test()
{
int fd;
for (fd = 3; fd < 30; fd++)
close(fd);
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
int iter;
for (iter = 0;; iter++) {
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
setup_test();
execute_one();
reset_test();
exit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
break;
sleep_ms(1);
if (current_time_ms() - start < 5 * 1000)
continue;
kill_and_wait(pid, &status);
break;
}
}
}
uint64_t r[1] = {0xffffffffffffffff};
void execute_one(void)
{
long res = 0;
memcpy((void*)0x20000000, "/dev/vhci", 10);
res = syscall(__NR_openat, 0xffffffffffffff9c, 0x20000000, 0x246, 0);
if (res != -1)
r[0] = res;
memcpy((void*)0x200000c0, "\xff\x80", 2);
syscall(__NR_write, r[0], 0x200000c0, 2);
}
int main(void)
{
syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0);
for (procid = 0; procid < 8; procid++) {
if (fork() == 0) {
loop();
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/779549.c
|
// REQUIRES: plugins, examples, asserts
// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend -emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext %s 2>&1 | FileCheck %s --check-prefix=YES
// YES: Clearing AST
// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend -emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns -plugin-arg-print-fns help %s 2>&1 | FileCheck %s --check-prefix=NO
// NO-NOT: Clearing AST
// NO: top-level-decl: "f"
void f() {}
|
the_stack_data/96148.c
|
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define BUF_SIZE 300
#define SERVER_PORT "9999"
#define BCAST_ADDRESS "255.255.255.255"
// read a string from stdin protecting buffer overflow
#define GETS(B,S) {fgets(B,S-2,stdin);B[strlen(B)-1]=0;}
int main(int argc, char **argv) {
struct sockaddr_storage serverAddr;
int sock, val, res, err;
unsigned int serverAddrLen;
char line[BUF_SIZE];
struct addrinfo req, *list;
bzero((char *)&req,sizeof(req));
req.ai_family = AF_INET; // there's no broadcast address in IPv6, so we request an IPv4 address
req.ai_socktype = SOCK_DGRAM;
err=getaddrinfo(BCAST_ADDRESS, SERVER_PORT , &req, &list);
if(err) {
printf("Failed to get broadcast address, error: %s\n",gai_strerror(err)); exit(1); }
serverAddrLen=list->ai_addrlen;
memcpy(&serverAddr,list->ai_addr,serverAddrLen); // store the broadcast address for later
freeaddrinfo(list);
bzero((char *)&req,sizeof(req));
req.ai_family = AF_INET;
req.ai_socktype = SOCK_DGRAM;
req.ai_flags = AI_PASSIVE; // local address
err=getaddrinfo(NULL, "0" , &req, &list); // Port 0 = auto assign
if(err) {
printf("Failed to get local address, error: %s\n",gai_strerror(err)); exit(1); }
sock=socket(list->ai_family,list->ai_socktype,list->ai_protocol);
if(sock==-1) {
perror("Failed to open socket"); freeaddrinfo(list); exit(1);}
// activate broadcast permission
val=1; setsockopt(sock,SOL_SOCKET, SO_BROADCAST, &val, sizeof(val));
if(bind(sock,(struct sockaddr *)list->ai_addr, list->ai_addrlen)==-1) {
perror("Bind failed");close(sock);freeaddrinfo(list);exit(1);}
freeaddrinfo(list);
while(1) {
printf("Request sentence to send (\"exit\" to quit): ");
GETS(line,BUF_SIZE);
if(!strcmp(line,"exit")) break;
sendto(sock,line,strlen(line),0,(struct sockaddr *)&serverAddr,serverAddrLen);
res=recvfrom(sock,line,BUF_SIZE,0,(struct sockaddr *)&serverAddr,&serverAddrLen);
line[res]=0; /* NULL terminate the string */
printf("Received reply: %s\n",line);
}
close(sock);
exit(0);
}
|
the_stack_data/220456769.c
|
#include <stdio.h>
main(){
int op;
float saldo, din;
do{
printf("------------------\n");
printf("Caixa Eletronico\n");
printf("------------------\n");
printf("1 - Depositar\n2 - Ver Saldo\n3 - Sacar\n4 - Sair");
printf("\nEscolha a opcao: ");
scanf("%d",&op);
if(op==1){
printf("Quanto deseja depositar? R$");
scanf("%f",&din);
saldo+=din;
}else if(op==2){
printf("Seu saldo: R$%.2f",saldo);
printf("\n");
}else if(op==3){
if(saldo<=0){
printf("Voce nao tem saldo suficiente...\n");
}else{
printf("Quanto deseja retirar? R$");
scanf("%f",&din);
saldo-=din;
} /*else if(op==4){
} else{
printf("Opcao invalida. Tente novamente...");
}*/
}
}while(op!=4);
printf("Volte sempre...\n");
}
|
the_stack_data/158571.c
|
/*
* Lua RTOS, Lua CAN module
*
* Copyright (C) 2015 - 2017
* IBEROXARXA SERVICIOS INTEGRALES, S.L. & CSS IBÉRICA, S.L.
*
* Author: Jaume Olivé ([email protected] / [email protected])
*
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purpose and without fee is hereby
* granted, provided that the above copyright notice appear in all
* copies and that both that the copyright notice and this
* permission notice and warranty disclaimer appear in supporting
* documentation, and that the name of the author not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
*
* The author disclaim all warranties with regard to this
* software, including all implied warranties of merchantability
* and fitness. In no event shall the author be liable for any
* special, indirect or consequential damages or any damages
* whatsoever resulting from loss of use, ƒintedata or profits, whether
* in an action of contract, negligence or other tortious action,
* arising out of or in connection with the use or performance of
* this software.
*/
#if LUA_USE_CAN
#include "lualib.h"
#include "lauxlib.h"
#include "auxmods.h"
#include <drivers/can/can.h>
static int lcan_pins( lua_State* L ) {
return platform_can_pins(L);
}
// Lua: result = setup( id, clock )
static int lcan_setup( lua_State* L )
{
unsigned id;
u32 clock, res;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( can, id );
clock = luaL_checkinteger( L, 2 );
res = platform_can_setup( id, clock );
if (res > 0) {
lua_pushinteger( L, res );
} else {
return luaL_error( L, "can't setup CAN" );
}
return 1;
}
// Lua: success = send( id, canid, canidtype, message )
static int lcan_send( lua_State* L ) {
size_t len;
int id, canid, idtype;
const char *data;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( can, id );
canid = luaL_checkinteger( L, 2 );
idtype = luaL_checkinteger( L, 3 );
len = luaL_checkinteger( L, 4 );
data = luaL_checkstring (L, 5);
if ( len > CAN_MAX_LEN )
return luaL_error( L, "message exceeds max length" );
platform_can_send( id, canid, idtype, len, ( const u8 * )data);
return 0;
}
// Lua: canid, canidtype, message = recv( id )
static int lcan_recv( lua_State* L ) {
u8 len;
int id;
u32 canid;
u8 idtype, data[ CAN_MAX_LEN ];
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( can, id );
if( platform_can_recv( id, &canid, &idtype, &len, data ))
{
lua_pushinteger( L, canid );
lua_pushinteger( L, idtype );
lua_pushinteger( L, len );
lua_pushlstring( L, ( const char * )data, ( size_t )len );
return 4;
}
else
return 0;
}
static int lcan_stats( lua_State* L )
{
u8 len;
int id;
struct can_stats stats;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( can, id );
if( platform_can_stats( id, &stats ))
{
lua_pushinteger( L, stats.rx );
lua_pushinteger( L, stats.tx );
lua_pushinteger( L, stats.rxqueued );
lua_pushinteger( L, stats.rxunqueued );
return 4;
}
else
return 0;
}
// Module function map
#define MIN_OPT_LEVEL 2
const luaL_Reg can_map[] =
{
{ "setup", lcan_setup },
{ "pins", lcan_pins },
{ "send", lcan_send },
{ "recv", lcan_recv },
{ "stats", lcan_stats },
{ NULL, NULL }
};
LUALIB_API int luaopen_can( lua_State *L )
{
#if LUA_OPTIMIZE_MEMORY > 0
return 0;
#else // #if LUA_OPTIMIZE_MEMORY > 0
luaL_register( L, AUXLIB_CAN, can_map );
// Module constants
MOD_REG_INTEGER( L, "STD", 0 );
MOD_REG_INTEGER( L, "EXT", 1 );
int i;
char buff[5];
for(i=1;i<=NCAN;i++) {
sprintf(buff,"CAN%d",i);
MOD_REG_INTEGER( L, buff, i );
}
return 1;
#endif // #if LUA_OPTIMIZE_MEMORY > 0
}
#endif
|
the_stack_data/77786.c
|
// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd -ferror-limit 100 %s -Wuninitialized
int foo() {
L1:
foo();
#pragma omp atomic
// expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected an expression statement}}
{
foo();
goto L1; // expected-error {{use of undeclared label 'L1'}}
}
goto L2; // expected-error {{use of undeclared label 'L2'}}
#pragma omp atomic
// expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected an expression statement}}
{
foo();
L2:
foo();
}
return 0;
}
struct S {
int a;
};
int readint() {
int a = 0, b = 0;
// Test for atomic read
#pragma omp atomic read
// expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}}
// expected-note@+1 {{expected an expression statement}}
;
#pragma omp atomic read
// expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}}
// expected-note@+1 {{expected built-in assignment operator}}
foo();
#pragma omp atomic read
// expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}}
// expected-note@+1 {{expected built-in assignment operator}}
a += b;
#pragma omp atomic read
// expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}}
// expected-note@+1 {{expected lvalue expression}}
a = 0;
#pragma omp atomic read
a = b;
// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'read' clause}}
#pragma omp atomic read read
a = b;
return 0;
}
int readS() {
struct S a, b;
// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'read' clause}} expected-error@+1 {{unexpected OpenMP clause 'allocate' in directive '#pragma omp atomic'}}
#pragma omp atomic read read allocate(a)
// expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}}
// expected-note@+1 {{expected expression of scalar type}}
a = b;
return a.a;
}
int writeint() {
int a = 0, b = 0;
// Test for atomic write
#pragma omp atomic write
// expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
// expected-note@+1 {{expected an expression statement}}
;
#pragma omp atomic write
// expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
// expected-note@+1 {{expected built-in assignment operator}}
foo();
#pragma omp atomic write
// expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
// expected-note@+1 {{expected built-in assignment operator}}
a += b;
#pragma omp atomic write
a = 0;
#pragma omp atomic write
a = b;
// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'write' clause}}
#pragma omp atomic write write
a = b;
return 0;
}
int writeS() {
struct S a, b;
// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'write' clause}}
#pragma omp atomic write write
// expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
// expected-note@+1 {{expected expression of scalar type}}
a = b;
return a.a;
}
int updateint() {
int a = 0, b = 0;
// Test for atomic update
#pragma omp atomic update
// expected-error@+2 {{the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected an expression statement}}
;
#pragma omp atomic
// expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected built-in binary or unary operator}}
foo();
#pragma omp atomic
// expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected built-in binary operator}}
a = b;
#pragma omp atomic update
// expected-error@+2 {{the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected one of '+', '*', '-', '/', '&', '^', '|', '<<', or '>>' built-in operations}}
a = b || a;
#pragma omp atomic update
// expected-error@+2 {{the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected one of '+', '*', '-', '/', '&', '^', '|', '<<', or '>>' built-in operations}}
a = a && b;
#pragma omp atomic update
// expected-error@+2 {{the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected in right hand side of expression}}
a = (float)a + b;
#pragma omp atomic
// expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected in right hand side of expression}}
a = 2 * b;
#pragma omp atomic
// expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected in right hand side of expression}}
a = b + *&a;
#pragma omp atomic update
*&a = *&a + 2;
#pragma omp atomic update
a++;
#pragma omp atomic
++a;
#pragma omp atomic update
a--;
#pragma omp atomic
--a;
#pragma omp atomic update
a += b;
#pragma omp atomic
a %= b;
#pragma omp atomic update
a *= b;
#pragma omp atomic
a -= b;
#pragma omp atomic update
a /= b;
#pragma omp atomic
a &= b;
#pragma omp atomic update
a ^= b;
#pragma omp atomic
a |= b;
#pragma omp atomic update
a <<= b;
#pragma omp atomic
a >>= b;
#pragma omp atomic update
a = b + a;
#pragma omp atomic
a = a * b;
#pragma omp atomic update
a = b - a;
#pragma omp atomic
a = a / b;
#pragma omp atomic update
a = b & a;
#pragma omp atomic
a = a ^ b;
#pragma omp atomic update
a = b | a;
#pragma omp atomic
a = a << b;
#pragma omp atomic
a = b >> a;
// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'update' clause}}
#pragma omp atomic update update
a /= b;
return 0;
}
int captureint() {
int a = 0, b = 0, c = 0;
// Test for atomic capture
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected compound statement}}
;
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected assignment expression}}
foo();
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected built-in binary or unary operator}}
a = b;
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected assignment expression}}
a = b || a;
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected one of '+', '*', '-', '/', '&', '^', '|', '<<', or '>>' built-in operations}}
b = a = a && b;
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected assignment expression}}
a = (float)a + b;
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected assignment expression}}
a = 2 * b;
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected assignment expression}}
a = b + *&a;
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected exactly two expression statements}}
{ a = b; }
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected exactly two expression statements}}
{}
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected in right hand side of the first expression}}
{a = b;a = b;}
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}}
// expected-note@+1 {{expected in right hand side of the first expression}}
{a = b; a = b || a;}
#pragma omp atomic capture
{b = a; a = a && b;}
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected in right hand side of expression}}
b = a = (float)a + b;
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected in right hand side of expression}}
b = a = 2 * b;
#pragma omp atomic capture
// expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}}
// expected-note@+1 {{expected in right hand side of expression}}
b = a = b + *&a;
#pragma omp atomic capture
c = *&a = *&a + 2;
#pragma omp atomic capture
c = a++;
#pragma omp atomic capture
c = ++a;
#pragma omp atomic capture
c = a--;
#pragma omp atomic capture
c = --a;
#pragma omp atomic capture
c = a += b;
#pragma omp atomic capture
c = a %= b;
#pragma omp atomic capture
c = a *= b;
#pragma omp atomic capture
c = a -= b;
#pragma omp atomic capture
c = a /= b;
#pragma omp atomic capture
c = a &= b;
#pragma omp atomic capture
c = a ^= b;
#pragma omp atomic capture
c = a |= b;
#pragma omp atomic capture
c = a <<= b;
#pragma omp atomic capture
c = a >>= b;
#pragma omp atomic capture
c = a = b + a;
#pragma omp atomic capture
c = a = a * b;
#pragma omp atomic capture
c = a = b - a;
#pragma omp atomic capture
c = a = a / b;
#pragma omp atomic capture
c = a = b & a;
#pragma omp atomic capture
c = a = a ^ b;
#pragma omp atomic capture
c = a = b | a;
#pragma omp atomic capture
c = a = a << b;
#pragma omp atomic capture
c = a = b >> a;
#pragma omp atomic capture
{ c = *&a; *&a = *&a + 2;}
#pragma omp atomic capture
{ *&a = *&a + 2; c = *&a;}
#pragma omp atomic capture
{c = a; a++;}
#pragma omp atomic capture
{c = a; (a)++;}
#pragma omp atomic capture
{++a;c = a;}
#pragma omp atomic capture
{c = a;a--;}
#pragma omp atomic capture
{--a;c = a;}
#pragma omp atomic capture
{c = a; a += b;}
#pragma omp atomic capture
{c = a; (a) += b;}
#pragma omp atomic capture
{a %= b; c = a;}
#pragma omp atomic capture
{c = a; a *= b;}
#pragma omp atomic capture
{a -= b;c = a;}
#pragma omp atomic capture
{c = a; a /= b;}
#pragma omp atomic capture
{a &= b; c = a;}
#pragma omp atomic capture
{c = a; a ^= b;}
#pragma omp atomic capture
{a |= b; c = a;}
#pragma omp atomic capture
{c = a; a <<= b;}
#pragma omp atomic capture
{a >>= b; c = a;}
#pragma omp atomic capture
{c = a; a = b + a;}
#pragma omp atomic capture
{a = a * b; c = a;}
#pragma omp atomic capture
{c = a; a = b - a;}
#pragma omp atomic capture
{a = a / b; c = a;}
#pragma omp atomic capture
{c = a; a = b & a;}
#pragma omp atomic capture
{a = a ^ b; c = a;}
#pragma omp atomic capture
{c = a; a = b | a;}
#pragma omp atomic capture
{a = a << b; c = a;}
#pragma omp atomic capture
{c = a; a = b >> a;}
#pragma omp atomic capture
{c = a; a = foo();}
// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'capture' clause}}
#pragma omp atomic capture capture
b = a /= b;
return 0;
}
|
the_stack_data/170453725.c
|
# include <stdio.h>
# include <stdlib.h>
int main(int argc, const int *argv[]){
int n = 1000;
double a = 1, b = 1, sum = 0;
for(n = 1000; n>0; n-=2){
a+=b;
sum+=(a/b);
b+=a;
sum-=(b/a);
}
printf("The answer is %f",sum);
return EXIT_SUCCESS;
}
|
the_stack_data/67326051.c
|
#include <stdio.h>
#include <stdlib.h>
void main() {
int i, j;
/*
* Create an array 3 rows long.
*/
int **pnumbers = (int **) malloc(3 * sizeof(int));
/*
* Each row in the array has an incrementing amount of columns.
*/
pnumbers[0] = (int *) malloc(1 * sizeof(int));
pnumbers[1] = (int *) malloc(2 * sizeof(int));
pnumbers[2] = (int *) malloc(3 * sizeof(int));
pnumbers[0][0] = 1;
pnumbers[1][0] = 1;
pnumbers[1][1] = 1;
pnumbers[2][0] = 1;
pnumbers[2][1] = 2;
pnumbers[2][2] = 1;
for (i = 0; i < 3; i++) {
for (j = 0; j <= i; j++) {
printf("%d ", pnumbers[i][j]);
}
printf("\n");
}
for (i = 0; i < 3; i++) {
free(pnumbers[i]);
}
free(pnumbers);
}
|
the_stack_data/69542.c
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define STRLEN 81
char* custom_string_input(char* st, int n);
int main()
{
/* Creating Space */
//char* name = ""; // Error at RUN-TIME
/*char name[128];
int result = scanf("%s", name);*/
/*
scanf() vs gets()
scanf() reads one word
gets() reads one line and removes \n and add \0
*/
//char words[STRLEN] = ""; // Warning without initialization
////gets(words); // gets receives pointer. No idea when string ends.
//gets_s(words, sizeof(words)); // C11
////int result = scanf("%s", words);
//printf("START\n");
//printf("%s", words); // no \n at the end
//puts(words); // puts() adds \n at the end
//puts("END.");
//TODO: try char words[5];
/* fgets() and fputs() */
//char words[STRLEN] = "";
//fgets(words, STRLEN, stdin); // does NOT remove \n
////TODO: replace '\n' with '\0'
//int i = 0;
//while (words[i] != '\n' && words[i] != '\0')
// i++;
//if (words[i] == '\n')
// words[i] = '\0';
////char* ptr = words;
////while (*ptr != '\n')
//// ptr++;
////*ptr = '\0';
//fputs(words, stdout); // does NOT add \n
//fputs("END", stdout);
/* Small array */
//char small_array[5];
//puts("Enter long strings:");
////fgets(small_array, 5, stdin); // FILE *_Stream
//printf("%p\n", small_array);
//printf("%p\n", fgets(small_array, 5, stdin));
//fputs(small_array, stdout);
/* Repeating short reading */
//char small_array[5];
//puts("Enter long strings:");
//while (fgets(small_array, 5, stdin) != NULL && small_array[0] != '\n')
// fputs(small_array, stdout);
/* scanf() */
//char str1[6], str2[6];
////int count = scanf("%5s %5s", str1, str2);
////int count = scanf("%6s %6s", str1, str2); // run-time error
//int count = scanf_s("%5s %5s", str1, 6, str2, 6);
//printf("%s|%s \n", str1, str2);
/* An example of custom input function */
char word[11];
puts(custom_string_input(word, 11));
return 0;
}
// implemented by myself
//char* custom_string_input(char* st, int n)
//{
// char buffer[STRLEN];
// printf("Enter a string.\n");
//
// fgets(buffer, n, stdin);
// buffer[n] = '\0';
// //gets(buffer);
// //buffer[n] = '\0';
// ////puts(buffer);
// ////for (int i = 0; i < n; i++)
// //// buffer[i] = st[i];
//
// return buffer;
//}
char* custom_string_input(char* st, int n)
{
char* ret_ptr;
int i = 0;
ret_ptr = fgets(st, n, stdin);
if (ret_ptr)
{
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
{
st[i] = '\0';
}
else
{
while (getchar() != '\n')
continue;
}
}
return ret_ptr;
}
|
the_stack_data/31386934.c
|
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
static char ALPHABET[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
static int char_to_int(char c) {
switch (c) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'A':
case 'a': return 10;
case 'B':
case 'b': return 11;
case 'C':
case 'c': return 12;
case 'D':
case 'd': return 13;
case 'E':
case 'e': return 14;
case 'F':
case 'f': return 15;
default:
return -1;
}
}
char* unhex(const char* hex, size_t length) {
if (length % 2 != 0) {
return "";
}
size_t size = length/2;
char* result = malloc((size + 1)*sizeof(char));
for (size_t i = 0; i < size; i++) {
result[i] = (char) (char_to_int(hex[2*i]) << 4 | char_to_int(hex[2*i + 1]));
}
result[size] = 0x00;
return result;
}
char* hex(const char* text, size_t length) {
char* result = malloc((2*length + 1)*sizeof(char));
size_t k = 0;
for (size_t i = 0; i < length; i++, k += 2) {
char c = text[i];
result[k] = ALPHABET[(c & 0xF0) >> 4];
result[k + 1] = ALPHABET[c & 0x0F];
}
result[k] = '\0';
return result;
}
char* strhex(const char* text) {
return hex(text, strlen(text));
}
void put_uint32_t(char* array, uint32_t value) {
array[0] = (char) ((value >> 24) & 0xFF);
array[1] = (char) ((value >> 16) & 0xFF);
array[2] = (char) ((value >> 8) & 0xFF);
array[3] = (char) (value & 0xFF);
}
void put_uint64_t(char* array, uint64_t value) {
array[0] = (char) ((value >> 56) & 0xFF);
array[1] = (char) ((value >> 48) & 0xFF);
array[2] = (char) ((value >> 40) & 0xFF);
array[3] = (char) ((value >> 32) & 0xFF);
array[4] = (char) ((value >> 24) & 0xFF);
array[5] = (char) ((value >> 16) & 0xFF);
array[6] = (char) ((value >> 8) & 0xFF);
array[7] = (char) (value & 0xFF);
}
|
the_stack_data/108939.c
|
/* passiveUDP.c - passiveUDP */
int passivesock(const char *service, const char *transport,
int qlen);
/*------------------------------------------------------------------------
* passiveUDP - create a passive socket for use in a UDP server
*------------------------------------------------------------------------
*/
int
passiveUDP(const char *service)
/*
* Arguments:
* service - service associated with the desired port
*/
{
return passivesock(service, "udp", 0);
}
|
the_stack_data/175143347.c
|
/***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function mul8_287
/// Library = EvoApprox8b
/// Circuit = mul8_287
/// Area (180) = 6978
/// Delay (180) = 3.190
/// Power (180) = 2906.10
/// Area (45) = 517
/// Delay (45) = 1.220
/// Power (45) = 247.30
/// Nodes = 132
/// HD = 305572
/// MAE = 167.22028
/// MSE = 46663.15625
/// MRE = 4.90 %
/// WCE = 1092
/// WCRE = 200 %
/// EP = 98.5 %
uint16_t mul8_287(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n0 = (a >> 0) & 0x1;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n16 = (b >> 0) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n32;
uint8_t n33;
uint8_t n36;
uint8_t n37;
uint8_t n39;
uint8_t n41;
uint8_t n42;
uint8_t n46;
uint8_t n47;
uint8_t n49;
uint8_t n50;
uint8_t n54;
uint8_t n55;
uint8_t n56;
uint8_t n57;
uint8_t n60;
uint8_t n62;
uint8_t n63;
uint8_t n65;
uint8_t n70;
uint8_t n71;
uint8_t n73;
uint8_t n75;
uint8_t n76;
uint8_t n86;
uint8_t n89;
uint8_t n105;
uint8_t n106;
uint8_t n107;
uint8_t n113;
uint8_t n121;
uint8_t n131;
uint8_t n134;
uint8_t n137;
uint8_t n149;
uint8_t n165;
uint8_t n209;
uint8_t n215;
uint8_t n223;
uint8_t n233;
uint8_t n234;
uint8_t n238;
uint8_t n246;
uint8_t n257;
uint8_t n281;
uint8_t n310;
uint8_t n313;
uint8_t n343;
uint8_t n356;
uint8_t n372;
uint8_t n417;
uint8_t n446;
uint8_t n460;
uint8_t n476;
uint8_t n489;
uint8_t n490;
uint8_t n550;
uint8_t n564;
uint8_t n565;
uint8_t n580;
uint8_t n581;
uint8_t n594;
uint8_t n608;
uint8_t n654;
uint8_t n668;
uint8_t n682;
uint8_t n688;
uint8_t n698;
uint8_t n709;
uint8_t n712;
uint8_t n728;
uint8_t n772;
uint8_t n786;
uint8_t n802;
uint8_t n816;
uint8_t n832;
uint8_t n846;
uint8_t n876;
uint8_t n890;
uint8_t n906;
uint8_t n920;
uint8_t n934;
uint8_t n950;
uint8_t n964;
uint8_t n980;
uint8_t n981;
uint8_t n1023;
uint8_t n1025;
uint8_t n1038;
uint8_t n1054;
uint8_t n1055;
uint8_t n1068;
uint8_t n1069;
uint8_t n1082;
uint8_t n1098;
uint8_t n1126;
uint8_t n1157;
uint8_t n1172;
uint8_t n1173;
uint8_t n1186;
uint8_t n1187;
uint8_t n1202;
uint8_t n1203;
uint8_t n1232;
uint8_t n1233;
uint8_t n1246;
uint8_t n1291;
uint8_t n1307;
uint8_t n1321;
uint8_t n1334;
uint8_t n1335;
uint8_t n1350;
uint8_t n1351;
uint8_t n1394;
uint8_t n1395;
uint8_t n1408;
uint8_t n1409;
uint8_t n1424;
uint8_t n1425;
uint8_t n1438;
uint8_t n1439;
uint8_t n1454;
uint8_t n1455;
uint8_t n1468;
uint8_t n1482;
uint8_t n1528;
uint8_t n1529;
uint8_t n1542;
uint8_t n1557;
uint8_t n1572;
uint8_t n1573;
uint8_t n1586;
uint8_t n1587;
uint8_t n1602;
uint8_t n1603;
uint8_t n1616;
uint8_t n1632;
uint8_t n1646;
uint8_t n1660;
uint8_t n1676;
uint8_t n1677;
uint8_t n1691;
uint8_t n1706;
uint8_t n1734;
uint8_t n1750;
uint8_t n1751;
uint8_t n1764;
uint8_t n1765;
uint8_t n1780;
uint8_t n1781;
uint8_t n1794;
uint8_t n1795;
uint8_t n1808;
uint8_t n1809;
uint8_t n1824;
uint8_t n1838;
uint8_t n1854;
uint8_t n1868;
uint8_t n1898;
uint8_t n1912;
uint8_t n1928;
uint8_t n1929;
uint8_t n1942;
uint8_t n1943;
uint8_t n1956;
uint8_t n1957;
uint8_t n1972;
uint8_t n1973;
uint8_t n1986;
uint8_t n1987;
uint8_t n2016;
n32 = n18 & n14;
n33 = n18 & n14;
n36 = ~(n26 | n28 | n14);
n37 = ~(n26 | n28 | n14);
n39 = n22 & n8;
n41 = n28 ^ n28;
n42 = ~(n6 & n16 & n14);
n46 = n2 & n16;
n47 = n2 & n16;
n49 = n18 | n12;
n50 = ~(n26 & n20 & n18);
n54 = ~(n49 & n33);
n55 = ~(n49 & n33);
n56 = ~(n18 | n28);
n57 = ~(n18 | n28);
n60 = (n39 & n4) | (~n39 & n37);
n62 = (n55 & n32) | (~n55 & n22);
n63 = (n55 & n32) | (~n55 & n22);
n65 = ~(n57 | n55);
n70 = ~(n65 | n42);
n71 = ~(n65 | n42);
n73 = ~(n49 | n54);
n75 = (n26 & n60) | (~n26 & n41);
n76 = ~n26;
n86 = ~(n47 & n24 & n41);
n89 = n33;
n105 = n70 | n12;
n106 = n63 & n56;
n107 = n63 & n56;
n113 = n89 ^ n71;
n121 = n18 & n62;
n131 = (n41 & n4) | (n4 & n107) | (n41 & n107);
n134 = n14 & n16;
n137 = n73;
n149 = ~((n89 | n20) & n6);
n165 = n37 & n131;
n209 = n41 & n18;
n215 = ~n165;
n223 = ~((n2 | n0) & n26);
n233 = n121;
n234 = ~n223;
n238 = n12 & n18;
n246 = ~(n223 | n50);
n257 = ~(n73 | n86);
n281 = ~(n137 ^ n246);
n310 = ~n149;
n313 = (n75 & n86) | (~n75 & n113);
n343 = n10 & n20;
n356 = n12 & n20;
n372 = n14 & n20;
n417 = n18 & n310;
n446 = n8 & n22;
n460 = n10 & n22;
n476 = n12 & n22;
n489 = n209 | n70;
n490 = n14 & n22;
n550 = n215 | n76;
n564 = n8 & n24;
n565 = n8 & n24;
n580 = n10 & n24;
n581 = n10 & n24;
n594 = n12 & n24;
n608 = n14 & n24;
n654 = n4 & n26;
n668 = n6 & n26;
n682 = n8 & n26;
n688 = n105 ^ n12;
n698 = n10 & n26;
n709 = n33 | n234;
n712 = n12 & n26;
n728 = n14 & n26;
n772 = n4 & n28;
n786 = n6 & n28;
n802 = n8 & n28;
n816 = n10 & n28;
n832 = n12 & n28;
n846 = n14 & n28;
n876 = n2 & n30;
n890 = n4 & n30;
n906 = n6 & n30;
n920 = n8 & n30;
n934 = n10 & n30;
n950 = n12 & n30;
n964 = n14 & n30;
n980 = n46 ^ n698;
n981 = n46 ^ n698;
n1023 = ~(n281 & n54);
n1025 = n233 | n54;
n1038 = (n565 & n688) | (~n565 & n106);
n1054 = n121;
n1055 = n121;
n1068 = (n134 ^ n238) ^ n343;
n1069 = (n134 & n238) | (n238 & n343) | (n134 & n343);
n1082 = n257 & n356;
n1098 = n65 | n356;
n1126 = n65;
n1157 = (n654 & n550) | (~n654 & n446);
n1172 = (n460 ^ n564) ^ n668;
n1173 = (n460 & n564) | (n564 & n668) | (n460 & n668);
n1186 = (n476 ^ n580) ^ n682;
n1187 = (n476 & n580) | (n580 & n682) | (n476 & n682);
n1202 = (n490 ^ n594) ^ n698;
n1203 = (n490 & n594) | (n594 & n698) | (n490 & n698);
n1232 = n608 ^ n712;
n1233 = n608 & n712;
n1246 = n233 ^ n981;
n1291 = (n1038 & n1025) | (n1025 & n417) | (n1038 & n417);
n1307 = n1054 & n36;
n1321 = n1068 | n1055;
n1334 = (n1098 ^ n1069) ^ n1172;
n1335 = (n1098 & n1069) | (n1069 & n1172) | (n1098 & n1172);
n1350 = (n372 ^ n1082) ^ n1186;
n1351 = (n372 & n1082) | (n1082 & n1186) | (n372 & n1186);
n1394 = (n1157 ^ n772) ^ n876;
n1395 = (n1157 & n772) | (n772 & n876) | (n1157 & n876);
n1408 = (n1173 ^ n786) ^ n890;
n1409 = (n1173 & n786) | (n786 & n890) | (n1173 & n890);
n1424 = (n1187 ^ n802) ^ n906;
n1425 = (n1187 & n802) | (n802 & n906) | (n1187 & n906);
n1438 = (n1203 ^ n816) ^ n920;
n1439 = (n1203 & n816) | (n816 & n920) | (n1203 & n920);
n1454 = (n1233 ^ n832) ^ n934;
n1455 = (n1233 & n832) | (n832 & n934) | (n1233 & n934);
n1468 = n846 & n950;
n1482 = n846 ^ n950;
n1528 = n489;
n1529 = n489;
n1542 = n1455 ^ n1291;
n1557 = n581 & n1307;
n1572 = (n1334 ^ n1321) ^ n1394;
n1573 = (n1334 & n1321) | (n1321 & n1394) | (n1334 & n1394);
n1586 = (n1350 ^ n1335) ^ n1408;
n1587 = (n1350 & n1335) | (n1335 & n1408) | (n1350 & n1408);
n1602 = (n1202 ^ n1351) ^ n1424;
n1603 = (n1202 & n1351) | (n1351 & n1424) | (n1202 & n1424);
n1616 = n1232 & n1438;
n1632 = n1232 ^ n1438;
n1646 = n728 & n1454;
n1660 = n728 ^ n1454;
n1676 = n709;
n1677 = n709;
n1691 = n1528 & n1126;
n1706 = n1542 | n1529;
n1734 = n1572 ^ n1557;
n1750 = (n1586 ^ n1573) ^ n1395;
n1751 = (n1586 & n1573) | (n1573 & n1395) | (n1586 & n1395);
n1764 = (n1602 ^ n1587) ^ n1409;
n1765 = (n1602 & n1587) | (n1587 & n1409) | (n1602 & n1409);
n1780 = (n1632 ^ n1603) ^ n1425;
n1781 = (n1632 & n1603) | (n1603 & n1425) | (n1632 & n1425);
n1794 = (n1660 ^ n1616) ^ n1439;
n1795 = (n1660 & n1616) | (n1616 & n1439) | (n1660 & n1439);
n1808 = (n1482 ^ n1646) ^ n1455;
n1809 = (n1482 & n1646) | (n1646 & n1455) | (n1482 & n1455);
n1824 = n964 & n1468;
n1838 = n964 ^ n1468;
n1854 = n1023 | n1677;
n1868 = n1706 ^ n1691;
n1898 = n1734 | n688;
n1912 = n1750;
n1928 = n1764 ^ n1751;
n1929 = n1764 & n1751;
n1942 = (n1780 ^ n1765) ^ n1929;
n1943 = (n1780 & n1765) | (n1765 & n1929) | (n1780 & n1929);
n1956 = (n1794 ^ n1781) ^ n1943;
n1957 = (n1794 & n1781) | (n1781 & n1943) | (n1794 & n1943);
n1972 = (n1808 ^ n1795) ^ n1957;
n1973 = (n1808 & n1795) | (n1795 & n1957) | (n1808 & n1957);
n1986 = (n1838 ^ n1809) ^ n1973;
n1987 = (n1838 & n1809) | (n1809 & n1973) | (n1838 & n1973);
n2016 = n1824 | n1987;
c |= (n313 & 0x1) << 0;
c |= (n980 & 0x1) << 1;
c |= (n1246 & 0x1) << 2;
c |= (n816 & 0x1) << 3;
c |= (n1676 & 0x1) << 4;
c |= (n1854 & 0x1) << 5;
c |= (n1868 & 0x1) << 6;
c |= (n1780 & 0x1) << 7;
c |= (n1898 & 0x1) << 8;
c |= (n1912 & 0x1) << 9;
c |= (n1928 & 0x1) << 10;
c |= (n1942 & 0x1) << 11;
c |= (n1956 & 0x1) << 12;
c |= (n1972 & 0x1) << 13;
c |= (n1986 & 0x1) << 14;
c |= (n2016 & 0x1) << 15;
return c;
}
|
the_stack_data/237643340.c
|
// PARAM: --set ana.activated "['base','threadid','threadflag','escape','mutex','mallocWrapper']"
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
int *x;
int *y;
void *t_fun(void *arg) {
*x = 3;
return NULL;
}
int main() {
pthread_t id;
x = malloc(sizeof(int));
y = malloc(sizeof(int));
*x = 0;
*y = 1;
assert(*x == 0);
assert(*y == 1);
pthread_create(&id, NULL, t_fun, NULL);
assert(*x == 0); // UNKNOWN
assert(*y == 1);
return 0;
}
|
the_stack_data/20450438.c
|
#include <stdio.h>
int strend(char *s, char *t);
int main()
{
char s1[] = "orld!";
char s2[] = "world!";
printf("%d\n", strend(s2, s1));
getchar();
}
int strend(char *s, char *t)
{
char *ps, *pt;
ps = s;
pt = t;
for (; *s; s++) {
;
}
for (; *t; t++) {
;
}
for (; *s == *t; s--, t--) {
if (s == ps || t == pt) {
break;
}
}
if (*s == *t && t == pt && *s != '\0') {
return 1;
}
else {
return 0;
}
}
|
the_stack_data/89004.c
|
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#include <limits.h>
char enc[1200]; // encode buffer
int enclen;
uint8_t dec[700]; // decode buffer
int declen;
const uint8_t dec64table[] = {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255};
void b64decode(const char *code, int code_len, uint8_t *result, int *result_len, int max_len)
{
int x, y;
uint8_t *ptr = result;
*result_len = max_len;
if (max_len <= 3 * (code_len / 4))
return;
while ((x = *code++) != 0) {
if (isspace(x))
continue;
if (x > 127 || (x = dec64table[x]) == 255)
return;
while (isspace(y = *code++))
;
if (y == 0 || (y = dec64table[y]) == 255)
return;
*result++ = (x << 2) | (y >> 4);
while (isspace(x = *code++))
;
if (x == '=') {
while (isspace(x = *code++))
;
if (x != '=')
return;
while (isspace(y = *code++))
;
if (y != 0)
return;
break;
} else {
if (x > 127 || (x = dec64table[x]) == 255)
return;
*result++ = (y << 4) | (x >> 2);
while (isspace(y = *code++))
;
if (y == '=') {
while (isspace(y = *code++))
;
if (y != 0)
return;
break;
} else {
if (y > 127 || (y = dec64table[y]) == 255)
return;
*result++ = (x << 6) | y;
}
}
}
*result_len = result - ptr;
}
char flag[100];
void read_flag()
{
FILE *f = fopen("flag.txt", "r");
fread(flag, 1, sizeof(flag), f);
int flaglen = strlen(flag);
printf("flag has %d bytes\n", flaglen);
fclose(f);
}
void print_hex(const char *buf, int len)
{
for (int i = 0; i < len; ++i)
//printf("%02x", buf[i]);
printf("%c", buf[i]);
}
int main() {
setbuf(stdout, NULL);
read_flag();
printf("guess flag (base64): ");
scanf("%s", enc);
enclen = strlen(enc);
b64decode(enc, enclen, dec, &declen, sizeof(dec));
if (declen == sizeof(dec)) {
puts("decode error");
return 0;
}
if (strcmp(flag, dec) == 0) {
printf("You already know the flag:\n");
print_hex(dec, declen);
}
else {
printf("This is not the flag:\n");
print_hex(dec, declen);
}
return 0;
}
|
the_stack_data/26846.c
|
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int matriz[8][8];
int i, j, num;
printf("Preencha a matriz com numeros inteiros.\n");
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
printf("Posicao [%d][%d]: ", i + 1, j + 1);
scanf(" %d", &matriz[i][j]);
}
}
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
if (matriz[i][j] == matriz[j][i])
{
num++;
}
}
}
if (num == 16)
{
printf("A matriz e simetrica.");
}
else
{
printf("A matriz não é simetrica.");
}
return 0;
}
|
the_stack_data/61074042.c
|
void test_id_map ();
void test_enc ();
int main () {
test_id_map();
test_enc();
return 0;
}
|
the_stack_data/181394191.c
|
#include <stdio.h>
#include <string.h>
#include <assert.h>
int main() {
int x = 0;
char buf1[] = "12345";
sscanf(buf1, "%d", &x);
assert(x == 12345);
// From dsda-doom
char buf2[] = "process_priority 0\n";
char def[80], strparm[128];
memset(def, '!', 80);
memset(strparm, '!', 128);
sscanf(buf2, "%s %[^\n]\n", def, strparm);
assert(!strcmp(def, "process_priority"));
assert(!strcmp(strparm, "0"));
char buf3[] = "fffffffff100";
unsigned long y = 0;
sscanf(buf3, "%lx", &y);
assert(y == 0xfffffffff100);
char buf4[] = "410dc000";
sscanf(buf4, "%lx", &y);
assert(y == 0x410dc000);
return 0;
}
|
the_stack_data/26700978.c
|
/***********************************************************
Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************/
/* Configurable Python configuration file */
#include <stdio.h>
#ifdef USE_STDWIN
#include <stdwin.h>
static int use_stdwin;
#endif
/*ARGSUSED*/
void initargs(int *p_argc, char ***p_argv)
{
#ifdef USE_STDWIN
extern char *getenv();
char *display;
/* Ignore an initial argument of '-s', for backward compatibility */
if (*p_argc > 1 && strcmp((*p_argv)[1], "-s") == 0) {
(*p_argv)[1] = (*p_argv)[0];
(*p_argc)--, (*p_argv)++;
}
/* Assume we have to initialize stdwin if either of the following
conditions holds:
- the environment variable $DISPLAY is set
- there is an argument "-display" somewhere
*/
display = getenv("DISPLAY");
if (display != 0)
use_stdwin = 1;
else {
int i;
/* Scan through the arguments looking for "-display" */
for (i = 1; i < *p_argc; i++) {
if (strcmp((*p_argv)[i], "-display") == 0) {
use_stdwin = 1;
break;
}
}
}
if (use_stdwin)
wargs(p_argc, p_argv);
#endif
}
void initcalls()
{
}
void
donecalls()
{
#ifdef USE_STDWIN
if (use_stdwin)
wdone();
#endif
#ifdef USE_AUDIO
asa_done();
#endif
}
#ifdef USE_STDWIN
static void
maybeinitstdwin()
{
if (use_stdwin)
initstdwin();
else
fprintf(stderr,
"No $DISPLAY nor -display arg -- stdwin not available\n");
}
#endif
#ifndef PYTHONPATH
#define PYTHONPATH ".:/usr/local/lib/python"
#endif
extern char *getenv();
char * getpythonpath()
{
char *path = getenv("PYTHONPATH");
if (path == 0)
path = PYTHONPATH;
return path;
}
/* Table of built-in modules.
These are initialized when first imported. */
/* Standard modules */
extern void inittime();
extern void initmath();
extern void initregexp();
extern void initposix();
#ifdef USE_AUDIO
extern void initaudio();
#endif
#ifdef USE_AMOEBA
extern void initamoeba();
#endif
#ifdef USE_GL
extern void initgl();
#ifdef USE_PANEL
extern void initpanel();
#endif
#endif
#ifdef USE_STDWIN
extern void maybeinitstdwin();
#endif
struct {
char *name;
void (*initfunc)();
} inittab[] = {
/* Standard modules */
{"time", inittime},
{"math", initmath},
{"regexp", initregexp},
{"posix", initposix},
/* Optional modules */
#ifdef USE_AUDIO
{"audio", initaudio},
#endif
#ifdef USE_AMOEBA
{"amoeba", initamoeba},
#endif
#ifdef USE_GL
{"gl", initgl},
#ifdef USE_PANEL
{"pnl", initpanel},
#endif
#endif
#ifdef USE_STDWIN
{"stdwin", maybeinitstdwin},
#endif
{0, 0} /* Sentinel */
};
|
the_stack_data/178265730.c
|
/* Capstone Disassembly Engine */
/* BPF Backend by david942j <[email protected]>, 2019 */
#ifdef CAPSTONE_HAS_BPF
#include <string.h>
#include <stddef.h> // offsetof macro
#include "BPFConstants.h"
#include "BPFDisassembler.h"
#include "BPFMapping.h"
#include "../../cs_priv.h"
static uint16_t read_u16(cs_struct *ud, const uint8_t *code)
{
if (MODE_IS_BIG_ENDIAN(ud->mode))
return (((uint16_t)code[0] << 8) | code[1]);
else
return (((uint16_t)code[1] << 8) | code[0]);
}
static uint32_t read_u32(cs_struct *ud, const uint8_t *code)
{
if (MODE_IS_BIG_ENDIAN(ud->mode))
return ((uint32_t)read_u16(ud, code) << 16) | read_u16(ud, code + 2);
else
return ((uint32_t)read_u16(ud, code + 2) << 16) | read_u16(ud, code);
}
///< Malloc bpf_internal, also checks if code_len is large enough.
static bpf_internal *alloc_bpf_internal(size_t code_len)
{
bpf_internal *bpf;
if (code_len < 8)
return NULL;
bpf = cs_mem_malloc(sizeof(bpf_internal));
if (bpf == NULL)
return NULL;
/* default value */
bpf->insn_size = 8;
return bpf;
}
///< Fetch a cBPF structure from code
static bpf_internal* fetch_cbpf(cs_struct *ud, const uint8_t *code,
size_t code_len)
{
bpf_internal *bpf;
bpf = alloc_bpf_internal(code_len);
if (bpf == NULL)
return NULL;
bpf->op = read_u16(ud, code);
bpf->jt = code[2];
bpf->jf = code[3];
bpf->k = read_u32(ud, code + 4);
return bpf;
}
///< Fetch an eBPF structure from code
static bpf_internal* fetch_ebpf(cs_struct *ud, const uint8_t *code,
size_t code_len)
{
bpf_internal *bpf;
bpf = alloc_bpf_internal(code_len);
if (bpf == NULL)
return NULL;
bpf->op = (uint16_t)code[0];
// eBPF has one 16-byte instruction: BPF_LD | BPF_DW | BPF_IMM,
// in this case imm is combined with the next block's imm.
if (bpf->op == (BPF_CLASS_LD | BPF_SIZE_DW | BPF_MODE_IMM)) {
if (code_len < 16) {
cs_mem_free(bpf);
return NULL;
}
bpf->k = read_u32(ud, code + 4) | (((uint64_t)read_u32(ud, code + 12)) << 32);
bpf->insn_size = 16;
}
else {
bpf->dst = code[1] & 0xf;
bpf->src = (code[1] & 0xf0) >> 4;
bpf->offset = read_u16(ud, code + 2);
bpf->k = read_u32(ud, code + 4);
}
return bpf;
}
#define CHECK_READABLE_REG(ud, reg) do { \
if (! ((reg) >= BPF_REG_R0 && (reg) <= BPF_REG_R10)) \
return false; \
} while (0)
#define CHECK_WRITABLE_REG(ud, reg) do { \
if (! ((reg) >= BPF_REG_R0 && (reg) < BPF_REG_R10)) \
return false; \
} while (0)
#define CHECK_READABLE_AND_PUSH(ud, MI, r) do { \
CHECK_READABLE_REG(ud, r + BPF_REG_R0); \
MCOperand_CreateReg0(MI, r + BPF_REG_R0); \
} while (0)
#define CHECK_WRITABLE_AND_PUSH(ud, MI, r) do { \
CHECK_WRITABLE_REG(ud, r + BPF_REG_R0); \
MCOperand_CreateReg0(MI, r + BPF_REG_R0); \
} while (0)
static bool decodeLoad(cs_struct *ud, MCInst *MI, bpf_internal *bpf)
{
if (!EBPF_MODE(ud)) {
/*
* +-----+-----------+--------------------+
* | ldb | [k] | [x+k] |
* | ldh | [k] | [x+k] |
* +-----+-----------+--------------------+
*/
if (BPF_SIZE(bpf->op) == BPF_SIZE_DW)
return false;
if (BPF_SIZE(bpf->op) == BPF_SIZE_B || BPF_SIZE(bpf->op) == BPF_SIZE_H) {
/* no ldx */
if (BPF_CLASS(bpf->op) != BPF_CLASS_LD)
return false;
/* can only be BPF_ABS and BPF_IND */
if (BPF_MODE(bpf->op) == BPF_MODE_ABS) {
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
else if (BPF_MODE(bpf->op) == BPF_MODE_IND) {
MCOperand_CreateReg0(MI, BPF_REG_X);
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
return false;
}
/*
* +-----+----+------+------+-----+-------+
* | ld | #k | #len | M[k] | [k] | [x+k] |
* +-----+----+------+------+-----+-------+
* | ldx | #k | #len | M[k] | 4*([k]&0xf) |
* +-----+----+------+------+-------------+
*/
switch (BPF_MODE(bpf->op)) {
default:
break;
case BPF_MODE_IMM:
MCOperand_CreateImm0(MI, bpf->k);
return true;
case BPF_MODE_LEN:
return true;
case BPF_MODE_MEM:
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
if (BPF_CLASS(bpf->op) == BPF_CLASS_LD) {
if (BPF_MODE(bpf->op) == BPF_MODE_ABS) {
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
else if (BPF_MODE(bpf->op) == BPF_MODE_IND) {
MCOperand_CreateReg0(MI, BPF_REG_X);
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
}
else { /* LDX */
if (BPF_MODE(bpf->op) == BPF_MODE_MSH) {
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
}
return false;
}
/* eBPF mode */
/*
* - IMM: lddw imm64
* - ABS: ld{w,h,b,dw} [k]
* - IND: ld{w,h,b,dw} [src+k]
* - MEM: ldx{w,h,b,dw} dst, [src+off]
*/
if (BPF_CLASS(bpf->op) == BPF_CLASS_LD) {
switch (BPF_MODE(bpf->op)) {
case BPF_MODE_IMM:
if (bpf->op != (BPF_CLASS_LD | BPF_SIZE_DW | BPF_MODE_IMM))
return false;
MCOperand_CreateImm0(MI, bpf->k);
return true;
case BPF_MODE_ABS:
MCOperand_CreateImm0(MI, bpf->k);
return true;
case BPF_MODE_IND:
CHECK_READABLE_AND_PUSH(ud, MI, bpf->src);
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
return false;
}
/* LDX */
if (BPF_MODE(bpf->op) == BPF_MODE_MEM) {
CHECK_WRITABLE_AND_PUSH(ud, MI, bpf->dst);
CHECK_READABLE_AND_PUSH(ud, MI, bpf->src);
MCOperand_CreateImm0(MI, bpf->offset);
return true;
}
return false;
}
static bool decodeStore(cs_struct *ud, MCInst *MI, bpf_internal *bpf)
{
/* in cBPF, only BPF_ST* | BPF_MEM | BPF_W is valid
* while in eBPF:
* - BPF_STX | BPF_XADD | BPF_{W,DW}
* - BPF_ST* | BPF_MEM | BPF_{W,H,B,DW}
* are valid
*/
if (!EBPF_MODE(ud)) {
/* can only store to M[] */
if (bpf->op != (BPF_CLASS(bpf->op) | BPF_MODE_MEM | BPF_SIZE_W))
return false;
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
/* eBPF */
if (BPF_MODE(bpf->op) == BPF_MODE_XADD) {
if (BPF_CLASS(bpf->op) != BPF_CLASS_STX)
return false;
if (BPF_SIZE(bpf->op) != BPF_SIZE_W && BPF_SIZE(bpf->op) != BPF_SIZE_DW)
return false;
/* xadd [dst + off], src */
CHECK_READABLE_AND_PUSH(ud, MI, bpf->dst);
MCOperand_CreateImm0(MI, bpf->offset);
CHECK_READABLE_AND_PUSH(ud, MI, bpf->src);
return true;
}
if (BPF_MODE(bpf->op) != BPF_MODE_MEM)
return false;
/* st [dst + off], src */
CHECK_READABLE_AND_PUSH(ud, MI, bpf->dst);
MCOperand_CreateImm0(MI, bpf->offset);
if (BPF_CLASS(bpf->op) == BPF_CLASS_ST)
MCOperand_CreateImm0(MI, bpf->k);
else
CHECK_READABLE_AND_PUSH(ud, MI, bpf->src);
return true;
}
static bool decodeALU(cs_struct *ud, MCInst *MI, bpf_internal *bpf)
{
/* Set MI->Operands */
/* cBPF */
if (!EBPF_MODE(ud)) {
if (BPF_OP(bpf->op) > BPF_ALU_XOR)
return false;
/* cBPF's NEG has no operands */
if (BPF_OP(bpf->op) == BPF_ALU_NEG)
return true;
if (BPF_SRC(bpf->op) == BPF_SRC_K)
MCOperand_CreateImm0(MI, bpf->k);
else /* BPF_SRC_X */
MCOperand_CreateReg0(MI, BPF_REG_X);
return true;
}
/* eBPF */
if (BPF_OP(bpf->op) > BPF_ALU_END)
return false;
/* ALU64 class doesn't have ENDian */
/* ENDian's imm must be one of 16, 32, 64 */
if (BPF_OP(bpf->op) == BPF_ALU_END) {
if (BPF_CLASS(bpf->op) == BPF_CLASS_ALU64)
return false;
if (bpf->k != 16 && bpf->k != 32 && bpf->k != 64)
return false;
}
/* - op dst, imm
* - op dst, src
* - neg dst
* - le<imm> dst
*/
/* every ALU instructions have dst op */
CHECK_WRITABLE_AND_PUSH(ud, MI, bpf->dst);
/* special cases */
if (BPF_OP(bpf->op) == BPF_ALU_NEG)
return true;
if (BPF_OP(bpf->op) == BPF_ALU_END) {
/* bpf->k must be one of 16, 32, 64 */
MCInst_setOpcode(MI, MCInst_getOpcode(MI) | ((uint32_t)bpf->k << 4));
return true;
}
/* normal cases */
if (BPF_SRC(bpf->op) == BPF_SRC_K) {
MCOperand_CreateImm0(MI, bpf->k);
}
else { /* BPF_SRC_X */
CHECK_READABLE_AND_PUSH(ud, MI, bpf->src);
}
return true;
}
static bool decodeJump(cs_struct *ud, MCInst *MI, bpf_internal *bpf)
{
/* cBPF and eBPF are very different in class jump */
if (!EBPF_MODE(ud)) {
if (BPF_OP(bpf->op) > BPF_JUMP_JSET)
return false;
/* ja is a special case of jumps */
if (BPF_OP(bpf->op) == BPF_JUMP_JA) {
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
if (BPF_SRC(bpf->op) == BPF_SRC_K)
MCOperand_CreateImm0(MI, bpf->k);
else /* BPF_SRC_X */
MCOperand_CreateReg0(MI, BPF_REG_X);
MCOperand_CreateImm0(MI, bpf->jt);
MCOperand_CreateImm0(MI, bpf->jf);
}
else {
if (BPF_OP(bpf->op) > BPF_JUMP_JSLE)
return false;
/* No operands for exit */
if (BPF_OP(bpf->op) == BPF_JUMP_EXIT)
return bpf->op == (BPF_CLASS_JMP | BPF_JUMP_EXIT);
if (BPF_OP(bpf->op) == BPF_JUMP_CALL) {
if (bpf->op != (BPF_CLASS_JMP | BPF_JUMP_CALL))
return false;
MCOperand_CreateImm0(MI, bpf->k);
return true;
}
/* ja is a special case of jumps */
if (BPF_OP(bpf->op) == BPF_JUMP_JA) {
if (BPF_SRC(bpf->op) != BPF_SRC_K)
return false;
MCOperand_CreateImm0(MI, bpf->offset);
return true;
}
/* <j> dst, src, +off */
CHECK_READABLE_AND_PUSH(ud, MI, bpf->dst);
if (BPF_SRC(bpf->op) == BPF_SRC_K)
MCOperand_CreateImm0(MI, bpf->k);
else
CHECK_READABLE_AND_PUSH(ud, MI, bpf->src);
MCOperand_CreateImm0(MI, bpf->offset);
}
return true;
}
static bool decodeReturn(cs_struct *ud, MCInst *MI, bpf_internal *bpf)
{
/* Here only handles the BPF_RET class in cBPF */
switch (BPF_RVAL(bpf->op)) {
case BPF_SRC_K:
MCOperand_CreateImm0(MI, bpf->k);
return true;
case BPF_SRC_X:
MCOperand_CreateReg0(MI, BPF_REG_X);
return true;
case BPF_SRC_A:
MCOperand_CreateReg0(MI, BPF_REG_A);
return true;
}
return false;
}
static bool decodeMISC(cs_struct *ud, MCInst *MI, bpf_internal *bpf)
{
uint16_t op = bpf->op ^ BPF_CLASS_MISC;
return op == BPF_MISCOP_TAX || op == BPF_MISCOP_TXA;
}
///< 1. Check if the instruction is valid
///< 2. Set MI->opcode
///< 3. Set MI->Operands
static bool getInstruction(cs_struct *ud, MCInst *MI, bpf_internal *bpf)
{
cs_detail *detail;
detail = MI->flat_insn->detail;
// initialize detail
if (detail) {
memset(detail, 0, offsetof(cs_detail, bpf) + sizeof(cs_bpf));
}
MCInst_clear(MI);
MCInst_setOpcode(MI, bpf->op);
switch (BPF_CLASS(bpf->op)) {
default: /* should never happen */
return false;
case BPF_CLASS_LD:
case BPF_CLASS_LDX:
return decodeLoad(ud, MI, bpf);
case BPF_CLASS_ST:
case BPF_CLASS_STX:
return decodeStore(ud, MI, bpf);
case BPF_CLASS_ALU:
return decodeALU(ud, MI, bpf);
case BPF_CLASS_JMP:
return decodeJump(ud, MI, bpf);
case BPF_CLASS_RET:
/* eBPF doesn't have this class */
if (EBPF_MODE(ud))
return false;
return decodeReturn(ud, MI, bpf);
case BPF_CLASS_MISC:
/* case BPF_CLASS_ALU64: */
if (EBPF_MODE(ud))
return decodeALU(ud, MI, bpf);
else
return decodeMISC(ud, MI, bpf);
}
}
bool BPF_getInstruction(csh ud, const uint8_t *code, size_t code_len,
MCInst *instr, uint16_t *size, uint64_t address, void *info)
{
cs_struct *cs;
bpf_internal *bpf;
cs = (cs_struct*)ud;
if (EBPF_MODE(cs))
bpf = fetch_ebpf(cs, code, code_len);
else
bpf = fetch_cbpf(cs, code, code_len);
if (bpf == NULL)
return false;
if (!getInstruction(cs, instr, bpf)) {
cs_mem_free(bpf);
return false;
}
*size = bpf->insn_size;
cs_mem_free(bpf);
return true;
}
#endif
|
the_stack_data/182954329.c
|
/* -------------------------------------------------------------------------
@file read_CSV.c
@date 03/27/17 11:10:25
@author Martin Noblia
@email [email protected]
@brief
@detail
Licence:
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
---------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char buffer[1024] ;
char *record;
char *line;
int i=0,j=0;
int mat[100][100];
FILE* fstream = fopen("/home/elsuizo/Dropbox/Freelance/ACC_filter/Acc_SampleFile_001.csv","r");
if(fstream == NULL)
{
printf("\n file opening failed ");
return -1 ;
}
while((line = fgets(buffer,sizeof(buffer),fstream)) != NULL)
{
record = strtok(line,",");
while(record != NULL)
{
printf("record : %s",record) ; //here you can put the record into the array as per your requirement.
mat[i][j++] = atoi(record) ;
record = strtok(NULL,",");
}
++i ;
}
return 0 ;
}
|
the_stack_data/45451343.c
|
//file: _insn_test_v1cmpeq_X0.c
//op=238
#include <stdio.h>
#include <stdlib.h>
void func_exit(void) {
printf("%s\n", __func__);
exit(0);
}
void func_call(void) {
printf("%s\n", __func__);
exit(0);
}
unsigned long mem[2] = { 0xbc7e18adc4f4bcd4, 0xdd853a2377c4c1cd };
int main(void) {
unsigned long a[4] = { 0, 0 };
asm __volatile__ (
"moveli r3, -28260\n"
"shl16insli r3, r3, -3800\n"
"shl16insli r3, r3, 26206\n"
"shl16insli r3, r3, 20590\n"
"moveli r43, -7555\n"
"shl16insli r43, r43, -10473\n"
"shl16insli r43, r43, 1769\n"
"shl16insli r43, r43, 20859\n"
"moveli r22, 31720\n"
"shl16insli r22, r22, -26184\n"
"shl16insli r22, r22, -29280\n"
"shl16insli r22, r22, 21783\n"
"{ v1cmpeq r3, r43, r22 ; fnop }\n"
"move %0, r3\n"
"move %1, r43\n"
"move %2, r22\n"
:"=r"(a[0]),"=r"(a[1]),"=r"(a[2]));
printf("%016lx\n", a[0]);
printf("%016lx\n", a[1]);
printf("%016lx\n", a[2]);
return 0;
}
|
the_stack_data/24515.c
|
#include <stdio.h>
#include <stdlib.h>
int *malloc2d(int r, int c);
int main(void) {
int rig, col, *mat, i, j;
printf("Inserisci numero righe: ");
scanf("%d", &rig);
printf("Inserisci numero colonne: ");
scanf("%d", &col);
mat = malloc2d(rig, col);
if(mat) {
for(i=0;i<rig;i++) {
for(j=0;j<col;j++) {
printf("%d\t", *(mat+i*col+j));
}
printf("\n");
}
free(mat);
}
else
printf("Errore allocazione memoria\n");
return 0;
}
int *malloc2d(int r, int c)
{
int *p, i, j;
p = malloc(sizeof(int)*r*c);
if(p) {
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
*(p+i*c+j) = 0;
}
}
}
return p;
}
|
the_stack_data/482333.c
|
// RUN: %bmc -bound 10 "%s" | FileCheck "%s"
// RUN: %bmc -bound 10 -math-int "%s" | FileCheck "%s"
// CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}}
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern int __VERIFIER_nondet_int();
int main()
{
int p1 = __VERIFIER_nondet_int(); // condition variable
int lk1; // lock variable
int p2 = __VERIFIER_nondet_int(); // condition variable
int lk2; // lock variable
int p3 = __VERIFIER_nondet_int(); // condition variable
int lk3; // lock variable
int p4 = __VERIFIER_nondet_int(); // condition variable
int lk4; // lock variable
int p5 = __VERIFIER_nondet_int(); // condition variable
int lk5; // lock variable
int p6 = __VERIFIER_nondet_int(); // condition variable
int lk6; // lock variable
int p7 = __VERIFIER_nondet_int(); // condition variable
int lk7; // lock variable
int p8 = __VERIFIER_nondet_int(); // condition variable
int lk8; // lock variable
int p9 = __VERIFIER_nondet_int(); // condition variable
int lk9; // lock variable
int p10 = __VERIFIER_nondet_int(); // condition variable
int lk10; // lock variable
int p11 = __VERIFIER_nondet_int(); // condition variable
int lk11; // lock variable
int cond;
while(1) {
cond = __VERIFIER_nondet_int();
if (cond == 0) {
goto out;
} else {}
lk1 = 0; // initially lock is open
lk2 = 0; // initially lock is open
lk3 = 0; // initially lock is open
lk4 = 0; // initially lock is open
lk5 = 0; // initially lock is open
lk6 = 0; // initially lock is open
lk7 = 0; // initially lock is open
lk8 = 0; // initially lock is open
lk9 = 0; // initially lock is open
lk10 = 0; // initially lock is open
lk11 = 0; // initially lock is open
// lock phase
if (p1 != 0) {
lk1 = 1; // acquire lock
} else {}
if (p2 != 0) {
lk2 = 1; // acquire lock
} else {}
if (p3 != 0) {
lk3 = 1; // acquire lock
} else {}
if (p4 != 0) {
lk4 = 1; // acquire lock
} else {}
if (p5 != 0) {
lk5 = 1; // acquire lock
} else {}
if (p6 != 0) {
lk6 = 1; // acquire lock
} else {}
if (p7 != 0) {
lk7 = 1; // acquire lock
} else {}
if (p8 != 0) {
lk8 = 1; // acquire lock
} else {}
if (p9 != 0) {
lk9 = 1; // acquire lock
} else {}
if (p10 != 0) {
lk10 = 1; // acquire lock
} else {}
if (p11 != 0) {
lk11 = 1; // acquire lock
} else {}
// unlock phase
if (p1 != 0) {
if (lk1 != 1) goto ERROR; // assertion failure
lk1 = 0;
} else {}
if (p2 != 0) {
if (lk2 != 1) goto ERROR; // assertion failure
lk2 = 0;
} else {}
if (p3 != 0) {
if (lk3 != 1) goto ERROR; // assertion failure
lk3 = 0;
} else {}
if (p4 != 0) {
if (lk4 != 1) goto ERROR; // assertion failure
lk4 = 0;
} else {}
if (p5 != 0) {
if (lk5 != 1) goto ERROR; // assertion failure
lk5 = 0;
} else {}
if (p6 != 0) {
if (lk6 != 1) goto ERROR; // assertion failure
lk6 = 0;
} else {}
if (p7 != 0) {
if (lk7 != 1) goto ERROR; // assertion failure
lk7 = 0;
} else {}
if (p8 != 0) {
if (lk8 != 1) goto ERROR; // assertion failure
lk8 = 0;
} else {}
if (p9 != 0) {
if (lk9 != 1) goto ERROR; // assertion failure
lk9 = 0;
} else {}
if (p10 != 0) {
if (lk10 != 1) goto ERROR; // assertion failure
lk10 = 0;
} else {}
if (p11 != 0) {
if (lk11 != 1) goto ERROR; // assertion failure
lk11 = 0;
} else {}
}
out:
return 0;
ERROR: __VERIFIER_error();
return 0;
}
|
the_stack_data/265283.c
|
/*
* Copyright 2012-17 Advanced Micro Devices, Inc.
*
* 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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: AMD
*
*/
#if defined(CONFIG_DRM_AMD_DC_DCN)
#include "reg_helper.h"
#include "resource.h"
#include "dwb.h"
#include "dcn10_dwb.h"
#define REG(reg)\
dwbc10->dwbc_regs->reg
#define CTX \
dwbc10->base.ctx
#undef FN
#define FN(reg_name, field_name) \
dwbc10->dwbc_shift->field_name, dwbc10->dwbc_mask->field_name
#define TO_DCN10_DWBC(dwbc_base) \
container_of(dwbc_base, struct dcn10_dwbc, base)
static bool dwb1_get_caps(struct dwbc *dwbc, struct dwb_caps *caps)
{
if (caps) {
caps->adapter_id = 0; /* we only support 1 adapter currently */
caps->hw_version = DCN_VERSION_1_0;
caps->num_pipes = 2;
memset(&caps->reserved, 0, sizeof(caps->reserved));
memset(&caps->reserved2, 0, sizeof(caps->reserved2));
caps->sw_version = dwb_ver_1_0;
caps->caps.support_dwb = true;
caps->caps.support_ogam = false;
caps->caps.support_wbscl = true;
caps->caps.support_ocsc = false;
return true;
} else {
return false;
}
}
static bool dwb1_enable(struct dwbc *dwbc, struct dc_dwb_params *params)
{
struct dcn10_dwbc *dwbc10 = TO_DCN10_DWBC(dwbc);
/* disable first. */
dwbc->funcs->disable(dwbc);
/* disable power gating */
REG_UPDATE_5(WB_EC_CONFIG, DISPCLK_R_WB_GATE_DIS, 1,
DISPCLK_G_WB_GATE_DIS, 1, DISPCLK_G_WBSCL_GATE_DIS, 1,
WB_LB_LS_DIS, 1, WB_LUT_LS_DIS, 1);
REG_UPDATE(WB_ENABLE, WB_ENABLE, 1);
return true;
}
static bool dwb1_disable(struct dwbc *dwbc)
{
struct dcn10_dwbc *dwbc10 = TO_DCN10_DWBC(dwbc);
/* disable CNV */
REG_UPDATE(CNV_MODE, CNV_FRAME_CAPTURE_EN, 0);
/* disable WB */
REG_UPDATE(WB_ENABLE, WB_ENABLE, 0);
/* soft reset */
REG_UPDATE(WB_SOFT_RESET, WB_SOFT_RESET, 1);
REG_UPDATE(WB_SOFT_RESET, WB_SOFT_RESET, 0);
/* enable power gating */
REG_UPDATE_5(WB_EC_CONFIG, DISPCLK_R_WB_GATE_DIS, 0,
DISPCLK_G_WB_GATE_DIS, 0, DISPCLK_G_WBSCL_GATE_DIS, 0,
WB_LB_LS_DIS, 0, WB_LUT_LS_DIS, 0);
return true;
}
const struct dwbc_funcs dcn10_dwbc_funcs = {
.get_caps = dwb1_get_caps,
.enable = dwb1_enable,
.disable = dwb1_disable,
.update = NULL,
.set_stereo = NULL,
.set_new_content = NULL,
.set_warmup = NULL,
.dwb_set_scaler = NULL,
};
void dcn10_dwbc_construct(struct dcn10_dwbc *dwbc10,
struct dc_context *ctx,
const struct dcn10_dwbc_registers *dwbc_regs,
const struct dcn10_dwbc_shift *dwbc_shift,
const struct dcn10_dwbc_mask *dwbc_mask,
int inst)
{
dwbc10->base.ctx = ctx;
dwbc10->base.inst = inst;
dwbc10->base.funcs = &dcn10_dwbc_funcs;
dwbc10->dwbc_regs = dwbc_regs;
dwbc10->dwbc_shift = dwbc_shift;
dwbc10->dwbc_mask = dwbc_mask;
}
#endif
|
the_stack_data/132260.c
|
#include <stdio.h>
#include <stdlib.h>
int determinant(int mat[3][3]);
int traceOfMatrix(int T[3][3]);
int matrix_product(int A[3][3], int B[3][3]);
int mat_in[3][3], in_mat[3][3];
int main()
{
printf("## Inverse of a matrix ##\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("\nEnter the A(%d%d) :", i + 1, j + 1);
scanf("%d", &mat_in[i][j]);
}
}
int deter = determinant(mat_in);
if (deter == 0)
{
printf("\nInverse cannot be find !!");
exit(0);
}
int traceA = traceOfMatrix(mat_in);
matrix_product(mat_in, mat_in);
int traceA2 = traceOfMatrix(in_mat);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
int test=0;
if(i==j)
{
test=1;
}
in_mat[i][j] -= (traceA * mat_in[i][j]);
in_mat[i][j] -= test*(traceA2 - traceA*traceA)/2;
printf("%d ", in_mat[i][j]);
}
printf("\n");
}
printf("______________\n");
printf("%d", deter);
return 0;
}
int determinant(int mat[3][3])
{
int deter;
deter = mat[0][0] * mat[1][1] * mat[2][2];
deter += (mat[0][1] * mat[1][2] * mat[2][0]);
deter += (mat[0][2] * mat[1][0] * mat[2][1]);
deter -= (mat[0][0] * mat[1][2] * mat[2][1]);
deter -= (mat[0][1] * mat[1][0] * mat[2][2]);
deter -= (mat[0][2] * mat[1][1] * mat[2][0]);
return (deter);
}
int matrix_product(int A[3][3], int B[3][3])
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
in_mat[i][j] = 0;
for (int n = 0; n < 3; n++)
{
in_mat[i][j] = in_mat[i][j] + (A[i][n] * B[n][j]);
}
}
}
return 0;
}
int traceOfMatrix(int T[3][3])
{
int trace;
trace = T[0][0] + T[1][1] + T[2][2];
return (trace);
}
|
the_stack_data/115526.c
|
#include <stdio.h>
int main() {
printf("Arreglos e Iteradores.\n\n");
int listaEnteros[11];
for (int i = 0; i <= 11; i++) {
listaEnteros[i] = i * i;
printf("valor (%d): %d \n", i, listaEnteros[i]);
}
return 0;
}
|
the_stack_data/179830818.c
|
/****************************************************************************/
/* memmov.c */
/* */
/* Copyright (c) 1996 Texas Instruments Incorporated */
/* http://www.ti.com/ */
/* */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions */
/* are met: */
/* */
/* Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* */
/* Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in */
/* the documentation and/or other materials provided with the */
/* distribution. */
/* */
/* Neither the name of Texas Instruments Incorporated nor the names */
/* of its contributors may be used to endorse or promote products */
/* derived from this software without specific prior written */
/* permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR */
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */
/* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY */
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/****************************************************************************/
#include <string.h>
void *memmove(void *s1, const void *s2, size_t n)
{
if (s2 > s1)
return memcpy(s1, s2, n);
else
{
unsigned char *st1 = (unsigned char *)s1;
unsigned char *st2 = (unsigned char *)s2;
size_t ln;
st1 += n;
st2 += n;
for (ln = 0; ln < n; ln++) *--st1 = *--st2;
}
return s1;
}
|
the_stack_data/43886932.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
char matrix[100 * 100];
void rec(int n, int target)
{
if (n > target)
return;
if (n == 0) {
matrix[0] = '0';
rec(n + 1, target);
}else{
int halfSquare = pow(2, n) / 2;
int i;
char tmp[100];
memcpy(tmp, matrix, halfSquare * halfSquare);
for (i = 0;i < halfSquare;i++){
memset(matrix + (i * 2 * halfSquare), '1', halfSquare);
memcpy(matrix + ((i * 2 + 1) * halfSquare), tmp + halfSquare * i, halfSquare);
}
for (i = 0;i < halfSquare;i++){
memset(matrix + (halfSquare * 2 * halfSquare) + (i * 2 * halfSquare), '2', halfSquare);
memset(matrix + (halfSquare * 2 * halfSquare) + ((i * 2 + 1) * halfSquare), '3', halfSquare);
}
rec(n + 1, target);
}
}
int main()
{
int n, r;
int i;
scanf("%d %d", &n, &r);
rec(0, n);
for (i = 0;i < pow(2, n);i++){
char tmp[1000];
strncpy(tmp, matrix + (int)(i * pow(2, n)), pow(2, n));
tmp[(int)pow(2, n)] = '\0';
printf("%s\n", tmp);
}
}
|
the_stack_data/132952559.c
|
// Andre Rossi Korol - 01810067
// EComp-5UNA
#include <stdio.h>
int main()
{
int a, b, soma;
puts("Entre o primeiro numero:");
scanf("%d", &a);
puts("Entre o segundo numero:");
scanf("%d", &b);
soma = a + b;
printf("Resultado da soma: %d + %d = %d\n", a, b, soma);
return 0;
}
|
the_stack_data/150140173.c
|
/*
** time.c for 42sh in /home/chauvi_d/Rendu-2015-Epitech/rendu/Systunix/for42/history
**
** Made by chauvi_d
** Login <[email protected]>
**
** Started on Sun Jun 5 14:41:52 2016 chauvi_d
** Last update Sun Jun 5 14:43:54 2016 chauvi_d
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
char *parse_time(char *time)
{
int j;
int i;
int space;
char *new_time;
i = 0;
space = 0;
j = 0;
if ((new_time = malloc(sizeof(char) * (strlen(time) + 1))) == NULL)
return (NULL);
while (time[i] && space != 4)
{
if (time[i] == ' ')
space++;
i++;
}
while (time[i] != ' ' && time[i])
new_time[j++] = time[i++];
new_time[j - 3] = 0;
return (new_time);
}
char *my_time()
{
time_t timer;
char *tim;
char *new_time;
timer = time(NULL);
tim = asctime(localtime(&timer));
new_time = parse_time(tim);
return (new_time);
}
|
the_stack_data/161081859.c
|
//카운팅 정렬
#include <stdio.h>
#define size 10001
int main(void)
{
int n, num, cnt[size];
scanf("%d", &n);
for (int i = 0; i < size; i++)//초기화
cnt[i] = 0;
for (int i = 0; i < n; i++)//카운팅
{
scanf("%d", &num);
cnt[num]++;
}
for (int i = 0; i < size; i++)//출력
{
if (cnt[i] == 0)
continue;
for (int j = 0; j < cnt[i]; j++)
printf("%d\n", i);
}
return 0;
}
|
the_stack_data/40761491.c
|
//
// main.c
// DLT
//
// Created by MoringStar on 2019/7/3.
// Copyright © 2019 MoringStar. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
return 0;
}
|
the_stack_data/59513638.c
|
/* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void RandomFunc(unsigned long input[1] , unsigned long output[1] )
{
unsigned long state[1] ;
unsigned short copy12 ;
char copy13 ;
unsigned short copy14 ;
{
state[0UL] = (input[0UL] & 914778474UL) << 7UL;
if ((state[0UL] >> 1UL) & 1UL) {
if ((state[0UL] >> 1UL) & 1UL) {
if (! ((state[0UL] >> 4UL) & 1UL)) {
copy12 = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = copy12;
copy12 = *((unsigned short *)(& state[0UL]) + 2);
*((unsigned short *)(& state[0UL]) + 2) = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = copy12;
}
} else {
copy13 = *((char *)(& state[0UL]) + 6);
*((char *)(& state[0UL]) + 6) = *((char *)(& state[0UL]) + 5);
*((char *)(& state[0UL]) + 5) = copy13;
copy13 = *((char *)(& state[0UL]) + 3);
*((char *)(& state[0UL]) + 3) = *((char *)(& state[0UL]) + 2);
*((char *)(& state[0UL]) + 2) = copy13;
}
} else {
copy14 = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = copy14;
}
output[0UL] = state[0UL] | 1072062461UL;
}
}
int main(int argc , char *argv[] )
{
unsigned long input[1] ;
unsigned long output[1] ;
int randomFuns_i5 ;
unsigned long randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 1072062461UL) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%lu\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void megaInit(void)
{
{
}
}
|
the_stack_data/39841.c
|
/**
* Exercise 4-5, page 68
* Упражнение 4.5, страница 92
*
* Add access to library functions like sin , exp , and pow . See <math.h> in
* Appendix B, Section 4.
*
* Добавьте реализацию библиотечных математических функций sin, exp, pow.
* См. заголовочный файл <math.h> в приложении Б, раздел 4.
*/
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
/** max size of operand or operator */
#define MAXOP 100
/** signal that a number was found */
#define NUMBER '0'
/** signal that some function was found */
#define FUNCTION '1'
/** maximum depth of val stack */
#define MAXVAL 100
/** size of buffer for getch/ungetch */
#define BUFSIZE 100
/** next free stack position */
int sp = 0;
/** value stack */
double val[MAXVAL];
/** buffer for ungetch */
char buf[BUFSIZE];
/** next free position in buf */
int bufp = 0;
void push (double f) {
if (sp < MAXVAL)
val[sp++] = f;
else
printf("error: stack full, can`t push %f\n", f);
}
double pop (void) {
if (sp > 0)
return val[--sp];
else {
printf("error: stack empty\n");
return 0.0;
}
}
//double stack_show(void) {
// return val[sp];
//}
void stack_show(void) {
if (sp > 0)
printf("stack top: %f\n", val[sp-1]);
else
printf("error: stack empty\n");
}
void stack_duplicate(void) {
double tmp = pop();
push(tmp);
push(tmp);
// push(stack_show());
}
void stack_swap(void) {
double tmp1 = pop();
double tmp2 = pop();
push(tmp1);
push(tmp2);
}
void stack_clear(void) {
sp = 0;
}
/** get a (possibly pushed back) character */
int getch(void) {
return (bufp > 0) ? buf[--bufp] : getchar();
}
/** push character back on input */
void ungetch(int c) {
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
int getop (char s[]) {
int i = 0;
int c, next_ch;
/** skip space symbpols */
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if (isalpha(c)) {
while (isalpha(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
return FUNCTION;
}
if (!isdigit(c) && c != '.' && c != '-')
/** not number */
return c;
/** check if there`s a number or '.' after '-' */
if (c == '-') {
next_ch = getch();
if (!isdigit(next_ch) && next_ch != '.')
return c;
c = next_ch;
}
else
c = getch();
/** collect integer */
while (isdigit(s[++i] = c))
c = getch();
if (c == '.')
/** collect fraction */
while (isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
return NUMBER;
}
double atof (char s[]) {
double val, power;
int i, sign, exp_sign;
int exp;
/** skip former space-char`s */
for (i = 0; isspace(s[i]); i++)
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
/** integer */
for (val = 0.0; isdigit(s[i]); i++)
val = 10.0 * val + (s[i] - '0');
/** fraction */
if (s[i] == '.') {
i++;
for (power = 1.0; isdigit(s[i]); i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10;
}
val *= sign / power;
}
/** exponent */
if (s[i] == 'e' || s[i] == 'E') {
exp_sign = (s[++i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (exp = 0.0; isdigit(s[i]); i++)
exp = 10.0 * exp + (s[i] - '0');
val *= pow(10, exp_sign * exp);
}
return val;
}
void execute_function(char *name) {
if (strcmp(name, "sin") == 0)
push(sin(pop()));
else if (strcmp(name, "cos") == 0)
push(cos(pop()));
else if (strcmp(name, "tan") == 0)
push(tan(pop()));
else if (strcmp(name, "exp") == 0)
push(exp(pop()));
else if (strcmp(name, "pow") == 0) {
double op2 = pop();
double op1 = pop();
/** division by zero */
if (op1 == 0 && op2 <= 0)
printf("error: trying to get \'%f^%f\'\n", op1, op2);
else
push(pow(op1, op2));
}
else
printf("error: unknown command \'%s\'\n", name);
}
/**
* reverse polish calculator\
* 1 2 - 4 5 + * == (1 - 2) * (4 + 5)
*/
int main (void) {
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch(type) {
case NUMBER:
push(atof(s));
break;
case FUNCTION:
execute_function(s);
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
/** first pop second operand*/
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: division by zero\n");
break;
case '%':
op2 = pop();
if (op2 != 0.0)
push(fmod(pop(), op2));
else
printf("error: division by zero\n");
break;
case '?':
stack_show();
break;
case '#':
stack_duplicate();
break;
case '~':
stack_swap();
break;
case '!':
stack_clear();
break;
case '\n':
printf("\t%.8f\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}
|
the_stack_data/96003.c
|
// RUN: env CC_PRINT_OPTIONS=1 \
// RUN: CC_PRINT_OPTIONS_FILE=%t.log \
// RUN: %clang -no-canonical-prefixes -S -o %t.s %s
// RUN: FileCheck %s < %t.log
// CHECK: [Logging clang options]
// CHECK: {{.*}}clang{{.*}}"-S"
|
the_stack_data/220456622.c
|
///////////////////////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2019.
// Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// chapter07_01-001_register_address.c
#include <stdio.h>
#include <stdint.h>
static uint8_t simulated_register_portb;
// The simulated address of portb.
#define REG_PORTB ((uintptr_t) &simulated_register_portb)
void do_something()
{
// Set portb to 0.
*((volatile uint8_t*) REG_PORTB) = UINT8_C(0);
}
int main()
{
do_something();
printf("simulated_register_portb: %d\n",
(unsigned) simulated_register_portb);
}
|
the_stack_data/206394245.c
|
//#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct date {
int day;
int month;
int year;
} Date;
typedef struct movie {
char *name;
int rank;
Date releaseDate;
} Movie;
void getMoviesInput(Movie ***pMovies, int *pSize);
Movie *getHighest(Movie **arr, int size);
Movie *getMovie();
char *getMovieName();
void sortMovies(Movie **arr, int size);
void printMovies(Movie **arr, int size);
void freeAll(Movie **arr, int size);
void checkMemoryAllocation(void *ptr);
void main() {
Movie **movies, *max;
int size;
getMoviesInput(&movies, &size);
max = getHighest(movies, size);
printf("The best movie is: %s\n", max->name);
max = getHighest(NULL, size);
printf("The second best movie is: %s\n", max->name);
max = getHighest(NULL, size);
printf("The third best movie is: %s\n", max->name);
// sortMovies(movies, size);
printMovies(movies, size);
freeAll(movies, size);
}
void printMovies(Movie **arr, int size) {
int i;
for (i = 0; i < size; i++) {
printf("Movie number %d\n", i + 1);
printf("Name: %s\nRank %d\nRelease date: %d/%d/%d", arr[i]->name, arr[i]->rank, (arr[i]->releaseDate).day,
(arr[i]->releaseDate).month, (arr[i]->releaseDate).year);
}
}
void freeAll(Movie **arr, int size) {
int i;
for (i = 0; i < size; ++i) {
free(arr[i]->name);
free(arr[i]);
}
free(arr);
}
Movie *getHighest(Movie **arr, int size) {
static Movie **arrSaver = NULL;
static Movie *lastMax = NULL;
Movie *max = NULL;
int i;
if (arr != NULL) {
arrSaver = arr;
max = arr[0];
for (i = 0; i < size; i++) {
if (arr[i]->rank > max->rank) {
max = arr[i];
}
}
} else {
bool found = false;
arr = arrSaver;
for (i = 0; i < size && !found; i++) {
if (arr[i]->rank < lastMax->rank) {
max = arr[i];
found = true;
}
}
for (i = 0; i < size; i++) {
if ((arr[i]->rank > max->rank) && (arr[i]->rank < lastMax->rank)) {
max = arr[i];
}
}
}
lastMax = max;
}
void getMoviesInput(Movie ***pMovies, int *pSize) {
Movie **movies;
int size, i;
printf("please enter number of movies :");
scanf("%d", &size);
movies = (Movie **) malloc(sizeof(Movie *) * size);
checkMemoryAllocation(movies);
for (i = 0; i < size; i++) {
printf("Movie number %d:", i + 1);
movies[i] = getMovie();
}
*pMovies = movies;
*pSize = size;
}
Movie *getMovie() {
Movie *movie = (Movie *) malloc(sizeof(Movie));
checkMemoryAllocation(movie);
getchar();
printf("Enter movie name: ");
movie->name = getMovieName();
printf("Enter movie rank");
scanf("%d", &(movie->rank));
printf("Enter movie release date (date/month/year):");
scanf("%d %d %d", &(movie->releaseDate.day), &(movie->releaseDate.month), &(movie->releaseDate.year));
}
char *getMovieName() {
char *str;
int logSize = 0, phySize = 1;
char c;
str = (char *) malloc(sizeof(char) * phySize);
checkMemoryAllocation(str);
c = getchar();
while (c != '\n') {
if (logSize == phySize) {
phySize *= 2;
str = (char *) realloc(str, sizeof(char) * phySize);
checkMemoryAllocation(str);
}
str[logSize] = c;
logSize++;
c = getchar();
}
if (logSize < phySize) {
str = (char *) realloc(str, sizeof(char) * (logSize + 1));
checkMemoryAllocation(str);
}
str[logSize] = '\0';
return str;
}
void checkMemoryAllocation(void *ptr) {
if (ptr == NULL) {
printf("Memory Allocation Failed...\n");
exit(1);
}
}
|
the_stack_data/167331114.c
|
/*
Scrivere un programma che produca 20 numeri casuali da 1 a 20. Il programma deve
immagazzinare in un vettore tutti i valori non duplicati. Utilizzate il vettore
più piccolo possibile per portare a termine questo lavoro.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define N 20
int main()
{
srand(time(NULL));
int vettore[N] = {0};
int vect[N] = {0};
int num_Casuale;
/*
[1,3,4,1 ]
*/
int shift = 0;
int i;
for(i = 0; i < N; i++)
{
num_Casuale = 1 + rand() % 20;
vect[i] = num_Casuale;
bool isEqual = false;
int k = i;
for(k = i; k >= 0; k--)
{
if(num_Casuale == vettore[k])
{
isEqual = true;
++shift;
}
}
if(isEqual != true)
{
vettore[i - shift] = num_Casuale;
}
}
/*
Stampa vettori
*/
puts("Vettore con duplicati e non");
for(i = 0; i < N; i++)
{
printf(" %d", vect[i]);
}
puts("\n");
for(i = 0; i < N; i++)
{
printf(" %d", vettore[i]);
}
puts("\n");
return 0;
}
|
the_stack_data/154827591.c
|
/**
* Exercise 6-1: Our version of getword does not properly handle
* underscores, string constants, comments, or preprocessor
* control lines. Write a better version.
*
* compile:
* gcc 6-1.c helpers.c
* */
#include <stdio.h>
#include <ctype.h>
#include <string.h>
struct key {
char *word;
int count;
} keytab[] = {
{"auto", 0}, {"break", 0}, {"case", 0}, {"char", 0},
{"const", 0}, {"continue", 0}, {"default", 0}, {"do", 0},
{"double", 0}, {"else", 0}, {"enum", 0}, {"extern", 0},
{"float", 0}, {"for", 0}, {"goto", 0}, {"if", 0},
{"int", 0}, {"long", 0}, {"register", 0}, {"return", 0},
{"short", 0}, {"signed", 0}, {"sizeof", 0}, {"static", 0},
{"struct", 0}, {"switch", 0}, {"typedef", 0}, {"union", 0},
{"unsigned", 0}, {"void", 0}, {"volatile", 0}, {"while", 0}
};
#define MAXWORD 100
#define NKEYS (sizeof keytab / sizeof keytab[0])
int getword(char *, int);
int binsearch(char *, struct key *, int);
// count C keywords
int main()
{
int n;
char word[MAXWORD];
while (getword(word, MAXWORD) != EOF)
if (isalpha(word[0]))
if ((n = binsearch(word, keytab, NKEYS)) >= 0)
keytab[n].count++;
for (n = 0; n < NKEYS; n++)
if (keytab[n].count > 0)
printf("%4d %s\n", keytab[n].count, keytab[n].word);
return 0;
}
// binsearch: find word in tab[0] ... tab[n-1]
int binsearch(char *word, struct key tab[], int n)
{
int cond;
int low, high, mid;
low = 0;
high = n-1;
while (low <= high) {
mid = (low+high)/2;
if ((cond = strcmp(word, tab[mid].word)) < 0)
high = mid -1; // drop second half
else if (cond > 0)
low = mid + 1; // drop first half
else
return mid; // found it!
}
return -1; // didn't find it :(
}
// getword: get the word or character from input
int getword(char *word, int lim)
{
int c, getch(void);
void ungetch(int);
char *w = word;
while (isspace(c = getch()))
;
if (c != EOF)
*w++ = c;
if (!isalpha(c) || c == '_' || c == '#') {
*w = '\0';
return c;
}
for ( ; --lim > 0; w++)
if (!isalnum(*w = getch())) {
ungetch(*w);
break;
}
*w = '\0';
return word[0];
}
|
the_stack_data/129826713.c
|
#include<stdio.h>
#include<string.h>
int main()
{
char koce[1000];
int k=0,fam[26]={0},o;
fgets(koce,1000,stdin);
while (koce[k] !='\0')
{
if (koce[k] >='a' && koce[k] <='z'){
o=koce[k]-'a';
fam[o]++;}
if (koce [k] >='A' && koce[k] <='Z'){
o=koce[k]-'A';
fam[o]++;}
k++;
}
for ( k = 0 ; k < 26 ; k++ )
{
if( fam[k] != 0 )
printf("%c - %d\n",k+'a',fam[k]);
}
return 0;
}
|
the_stack_data/40763889.c
|
#include <stdio.h>
void print_second_greetings(void)
{
printf("Hello from UNPATCHED shared library\n");
}
void print_third_greetings(void)
{
printf("Hello from PATCHED shared library!\n");
}
void print_greetings(void)
{
print_second_greetings();
}
|
the_stack_data/51203.c
|
/* copt version 1.00 (C) Copyright Christopher W. Fraser 1984 */
/* Added out of memory checking and ANSI prototyping. DG 1999 */
/* Added %L - %N variables, %activate, regexp, %check. Zrin Z. 2002 */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define USE_REGEXP
#ifdef USE_REGEXP
#include <sys/types.h>
#ifdef LOCAL_REGEXP
#include "regex/regex.h"
#else
#include <regex.h>
#endif
#endif
#if defined(_MSC_VER) || defined(__TURBOC__)
#define strcasecmp stricmp
#endif
int rpn_eval(const char* expr, char** vars);
#define HSIZE 107
#define MAXLINE 256
#define MAXFIRECOUNT 65535L
#define MAX_PASS 16
int debug = 0;
int global_again = 0; /* signalize that rule set has changed */
#define FIRSTLAB 'L'
#define LASTLAB 'N'
int nextlab = 1; /* unique label counter */
int labnum[LASTLAB - FIRSTLAB + 1]; /* unique label numbers */
struct lnode {
char* l_text;
struct lnode *l_prev, *l_next;
};
struct onode {
struct lnode *o_old, *o_new;
struct onode* o_next;
long firecount;
}* opts = 0, *activerule = 0;
void printlines(struct lnode* beg, struct lnode* end, FILE* out)
{
struct lnode* p;
for (p = beg; p != end; p = p->l_next)
fputs(p->l_text, out);
}
void printrule(struct onode* o, FILE* out)
{
struct lnode* p = o->o_old;
while (p->l_prev)
p = p->l_prev;
printlines(p, 0, out);
fputs("=\n", out);
printlines(o->o_new, 0, out);
}
/* error - report error and quit */
void error(char* s)
{
fputs(s, stderr);
if (activerule) {
fputs("active rule:\n", stderr);
printrule(activerule, stderr);
}
exit(1);
}
/* connect - connect p1 to p2 */
void connect(struct lnode* p1, struct lnode* p2)
{
if (p1 == 0 || p2 == 0)
error("connect: can't happen\n");
p1->l_next = p2;
p2->l_prev = p1;
}
/* install - install str in string table */
char* install(char* str)
{
register struct hnode* p;
register char *p1, *p2, *s;
register int i;
static struct hnode {
char* h_str;
struct hnode* h_ptr;
} * htab[HSIZE] = { 0 };
s = str;
for (i = 0; *s; i += *s++)
;
i = abs(i) % HSIZE;
for (p = htab[i]; p; p = p->h_ptr)
for (p1 = str, p2 = p->h_str; *p1++ == *p2++;)
if (p1[-1] == '\0')
return (p->h_str);
p = (struct hnode*)malloc(sizeof *p);
if (p == NULL)
error("install 1: out of memory\n");
p->h_str = (char*)malloc((s - str) + 1);
if (p->h_str == NULL)
error("install 2: out of memory\n");
strcpy(p->h_str, str);
p->h_ptr = htab[i];
htab[i] = p;
return (p->h_str);
}
/* insert - insert a new node with text s before node p */
void insert(char* s, struct lnode* p)
{
struct lnode* n;
n = (struct lnode*)malloc(sizeof *n);
if (n == NULL)
error("insert: out of memory\n");
n->l_text = s;
connect(p->l_prev, n);
connect(n, p);
}
/* getlst - link lines from fp in between p1 and p2 */
void getlst(FILE* fp, char* quit, struct lnode* p1, struct lnode* p2)
{
char *install(), lin[MAXLINE];
connect(p1, p2);
while (fgets(lin, MAXLINE, fp) != NULL && strcmp(lin, quit)) {
insert(install(lin), p2);
}
}
/* getlst_1 - link lines from fp in between p1 and p2 */
/* skip blank lines and comments at the start */
void getlst_1(FILE* fp, char* quit, struct lnode* p1, struct lnode* p2)
{
char *install(), lin[MAXLINE];
int firstline = 1;
connect(p1, p2);
while (fgets(lin, MAXLINE, fp) != NULL && strcmp(lin, quit)) {
if (firstline) {
char* p = lin;
while (isspace(*p))
++p;
if (!*p)
continue;
if (lin[0] == ';' && lin[1] == ';')
continue;
firstline = 0;
}
insert(install(lin), p2);
}
}
/* init - read patterns file */
void init(FILE* fp)
{
struct lnode head, tail;
struct onode *p, **next;
next = &opts;
while (*next)
next = &((*next)->o_next);
while (!feof(fp)) {
p = (struct onode*)malloc((unsigned)sizeof(struct onode));
if (p == NULL)
error("init: out of memory\n");
p->firecount = MAXFIRECOUNT;
getlst_1(fp, "=\n", &head, &tail);
head.l_next->l_prev = 0;
if (tail.l_prev)
tail.l_prev->l_next = 0;
p->o_old = tail.l_prev;
if (p->o_old == NULL) { /* do not create empty rules */
free(p);
continue;
}
getlst(fp, "\n", &head, &tail);
tail.l_prev->l_next = 0;
if (head.l_next)
head.l_next->l_prev = 0;
p->o_new = head.l_next;
*next = p;
next = &p->o_next;
}
*next = 0;
}
/* match - check conditions in rules */
/* format: %check min <= %n <= max */
int check(char* pat, char** vars)
{
int low, high, x;
char v;
x = sscanf(pat, "%d <= %%%c <= %d", &low, &v, &high);
if (x != 3 || !('0' <= v && v <= '9')) {
fprintf(stderr, "warning: invalid use of '%%check' in \"%s\"\n", pat);
fprintf(stderr, "format is '%%check min <= %%n <= max'\n");
return 0;
}
if (vars[v - '0'] == 0) {
fprintf(stderr, "error in pattern \"%s\"\n", pat);
error("variable is not set\n");
}
if (sscanf(vars[v - '0'], "%d", &x) != 1)
return 0;
return low <= x && x <= high;
}
int check_eval(char* pat, char** vars)
{
char expr[1024];
int expected, result, x;
char v1, v2;
x = sscanf(pat, "%d = %[^\n]s", &expected, expr);
if (x != 2) {
fprintf(stderr, "warning: invalid use of '%%check_eval' in \"%s\"\n", pat);
fprintf(stderr, "format is '%%check_eval result = expr");
return 0;
}
return expected == rpn_eval(expr, vars);
}
/* match - match ins against pat and set vars */
int match(char* ins, char* pat, char** vars)
{
char *p, lin[MAXLINE], *start = pat;
#ifdef USE_REGEXP
char re[MAXLINE]; /* regular expression */
char* istart = ins;
regex_t reg;
#define NMATCH 3
regmatch_t match[NMATCH];
char var;
int reerr, eflags, mi;
#endif
while (*ins && *pat)
if (pat[0] == '%') {
switch (pat[1]) {
case '%':
if (*pat != *ins++)
return 0;
pat += 2;
break;
#ifdef USE_REGEXP
case '"':
p = pat + 2;
for (; *p && (*p != '"' || p[-1] == '\\'); ++p)
;
if (*p != '"') {
fprintf(stderr,
"warning: invalid use of '%%\"..\"n' in \"%s\"\n",
start);
break;
}
if (isdigit(p[1]))
var = p[1];
else
var = 0;
if (var && vars[var - '0'] != 0) {
fprintf(stderr, "warning: variable %%%c has already a value in \"%s\"\n", p[1], start);
fprintf(stderr, "please use REGEXP only on the last occurance of a variable in the input pattern\n");
goto l_fallthrough;
}
strncpy(re, pat + 2, p - pat - 2);
re[p - pat - 2] = '\0';
pat = p;
reerr = regcomp(®, re, REG_EXTENDED);
if (reerr != 0) {
regerror(reerr, ®, re, sizeof(re));
fprintf(stderr, "error in \"%s\": %s\n", start, re);
error("error: invalid rule\n");
}
eflags = 0;
if (ins != istart)
eflags |= REG_NOTBOL;
reerr = regexec(®, ins, NMATCH, match, eflags);
if (reerr != 0 && reerr != REG_NOMATCH) {
regerror(reerr, ®, re, sizeof(re));
fprintf(stderr, "error in \"%s\": %s\n", start, re);
error("error: while matching REGEXP\n");
}
regfree(®);
if (reerr != 0 || match[0].rm_so != 0)
return 0; /* not matched */
mi = match[1].rm_eo == -1 ? 0 : 1; /* which match to use */
if (var) {
int i = match[mi].rm_eo - match[mi].rm_so;
strncpy(re, ins + match[mi].rm_so, i);
re[i] = '\0';
ins += match[0].rm_eo; /* eat whole match */
vars[var - '0'] = install(re);
pat += 2;
} else {
ins += match[0].rm_eo;
++pat;
}
continue;
l_fallthrough:
#endif
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (pat[2] == '%' && pat[3] != '%') {
fprintf(stderr, "error in \"%s\": ", start);
error("input pattern %n% is not allowed\n");
}
for (p = lin; *ins && *ins != pat[2];)
*p++ = *ins++;
*p = 0;
p = install(lin);
if (vars[pat[1] - '0'] == 0)
vars[pat[1] - '0'] = p;
else if (vars[pat[1] - '0'] != p)
return 0;
pat += 2;
continue;
default:
break;
}
if (*pat++ != *ins++)
return 0;
} else if (*pat++ != *ins++)
return 0;
return *pat == *ins; /* compare end of string */
}
/* subst_imp - return result of substituting vars into pat */
char* subst_imp(char* pat, char** vars)
{
static char errormsg[80];
static char lin[MAXLINE];
char num[30];
char *s, *start = pat;
int i;
i = 0;
for (;;) {
if (pat[0] == '%' && pat[1] == '%') {
if (i < MAXLINE) {
lin[i] = '%';
++i;
}
pat += 2;
} else if (pat[0] == '%' && pat[1] >= FIRSTLAB && pat[1] <= LASTLAB) {
int il = pat[1] - FIRSTLAB;
if (!labnum[il])
labnum[il] = nextlab++;
sprintf(num, "%d", labnum[il]);
for (s = num; i < MAXLINE && (lin[i] = *s++) != 0; ++i)
;
pat += 2;
} else if (pat[0] == '%' && strncmp(pat,"%eval(", 6) == 0 ) {
char expr[1024];
int x = 0;
int r;
pat += 6;
while (*pat != ')') {
expr[x++] = *pat++;
}
expr[x] = 0;
pat++;
sprintf(expr, "%d", rpn_eval(expr, vars));
for ( s = expr; i <MAXLINE && *s; i++ )
lin[i] = *s++;
} else if (pat[0] == '%' && isdigit(pat[1])) {
if (vars[pat[1] - '0'] == 0) {
sprintf(errormsg, "error: variable %c is not set in \"%s\"",
pat[1], start);
error(errormsg);
}
for (s = vars[pat[1] - '0']; i < MAXLINE && (lin[i] = *s++) != 0; i++)
;
pat += 2;
} else if (i >= MAXLINE)
error("line too long\n");
else if (!(lin[i++] = *pat++))
return &lin[0];
}
}
/* subst - return install(result of substituting vars into pat) */
char* subst(char* pat, char** vars)
{
return install(subst_imp(pat, vars));
}
/* rep - substitute vars into new and replace lines between p1 and p2 */
struct lnode* rep(
struct lnode* p1, struct lnode* p2, struct lnode* new, char** vars)
{
char *exec(), *subst();
int i;
struct lnode *p, *psav;
for (i = 0; i < LASTLAB - FIRSTLAB + 1; ++i)
labnum[i] = 0;
for (p = p1->l_next; p != p2; p = psav) {
psav = p->l_next;
if (debug)
fputs(p->l_text, stderr);
free(p);
}
connect(p1, p2);
if (debug)
fputs("=\n", stderr);
for (; new; new = new->l_next) {
insert(subst(new->l_text, vars), p2);
if (debug)
fputs(p2->l_prev->l_text, stderr);
}
if (debug)
putc('\n', stderr);
return p1->l_next;
}
/* copylist - copy activated rule; substitute variables */
struct lnode* copylist(
struct lnode* source, struct lnode** pat, struct lnode** sub, char** vars)
{
struct lnode head, tail, *more = 0;
int pattern = 1; /* allow nested rules */
int i;
connect(&head, &tail);
head.l_prev = tail.l_next = 0;
for (i = 0; i < LASTLAB - FIRSTLAB + 1; ++i)
labnum[i] = 0;
for (; source; source = source->l_next) {
if (pattern && strcmp(source->l_text, "=\n") == 0) {
pattern = 0;
if (head.l_next == &tail)
error("error: empty pattern\n");
*pat = tail.l_prev;
head.l_next->l_prev = 0;
tail.l_prev->l_next = 0;
connect(&head, &tail);
continue;
}
if (strcmp(source->l_text, "%activate\n") == 0) {
if (pattern)
error("error: %activate in pattern (before '=')\n");
more = source->l_next;
break;
}
insert(subst(source->l_text, vars), &tail);
}
if (head.l_next == &tail)
*sub = 0;
else {
head.l_next->l_prev = 0;
tail.l_prev->l_next = 0;
*sub = head.l_next;
}
return more;
}
/* opt - replace instructions ending at r if possible */
struct lnode* opt(struct lnode* r)
{
char* vars[10];
int i, lines;
struct lnode *c, *p;
struct onode* o;
static char* activated = "%activated ";
for (o = opts; o; o = o->o_next) {
activerule = o;
if (o->firecount < 1)
continue;
c = r;
p = o->o_old;
if (p == 0)
continue; /* skip empty rules */
for (i = 0; i < 10; i++)
vars[i] = 0;
lines = 0;
while (p && c) {
if (strncmp(p->l_text, "%check", 6) == 0) {
if (!check(p->l_text + 6, vars))
break;
} else if ( strncmp(p->l_text, "%eval", 5) == 0 ) {
if (!check_eval(p->l_text + 5, vars))
break;
} else {
if (!match(c->l_text, p->l_text, vars))
break;
c = c->l_prev;
++lines;
}
p = p->l_prev;
}
if (p != 0)
continue;
/* decrease firecount */
--o->firecount;
/* check for %once */
if (o->o_new && strcmp(o->o_new->l_text, "%once\n") == 0) {
struct lnode* tmp = o->o_new; /* delete the %once line */
o->o_new = o->o_new->l_next;
o->o_new->l_prev = 0;
free(tmp);
o->firecount = 0; /* never again */
}
/* check for activation rules */
if (o->o_new && strcmp(o->o_new->l_text, "%activate\n") == 0) {
/* we have to prevent repeated activation of rules */
char signature[300];
struct lnode* lnp;
struct onode *nn, *last;
int skip = 0;
/* since we 'install()' strings, we can compare pointers */
sprintf(signature, "%s%p%p%p%p%p%p%p%p%p%p\n",
activated,
vars[0], vars[1], vars[2], vars[3], vars[4],
vars[5], vars[6], vars[7], vars[8], vars[9]);
lnp = o->o_new->l_next;
while (lnp && strncmp(lnp->l_text, activated, strlen(activated)) == 0) {
if (strcmp(lnp->l_text, signature) == 0) {
skip = 1;
break;
}
lnp = lnp->l_next;
}
if (!lnp || skip)
continue;
insert(install(signature), lnp);
if (debug) {
fputs("matched pattern:\n", stderr);
for (p = o->o_old; p->l_prev; p = p->l_prev)
;
printlines(p, 0, stderr);
fputs("with:\n", stderr);
printlines(c->l_next, r->l_next, stderr);
}
/* allow creation of several rules */
last = o;
while (lnp) {
nn = (struct onode*)
malloc((unsigned)sizeof(struct onode));
if (nn == NULL)
error("activate: out of memory\n");
nn->o_old = 0, nn->o_new = 0;
nn->firecount = MAXFIRECOUNT;
lnp = copylist(lnp, &nn->o_old, &nn->o_new, vars);
nn->o_next = last->o_next;
last->o_next = nn;
last = nn;
if (debug) {
fputs("activated rule:\n", stderr);
printrule(nn, stderr);
}
}
if (debug)
fputs("\n", stderr);
/* step back to allow (shorter) activated rules to match
in the order they appear */
while (--lines && r->l_prev)
r = r->l_prev;
global_again = 1; /* signalize changes */
continue;
}
/* fire the rule */
r = rep(c, r->l_next, o->o_new, vars);
activerule = 0;
return r;
}
activerule = 0;
return r->l_next;
}
/* #define _TESTING */
/* main - peephole optimizer */
int main(int argc, char** argv)
{
FILE* fp;
#ifdef _TESTING
FILE* inp;
#endif
int i, pass;
struct lnode head, *p, *opt(), tail;
for (i = 1; i < argc; i++)
if (strcasecmp(argv[i], "-D") == 0)
debug = 1;
else if ((fp = fopen(argv[i], "r")) == NULL)
error("copt: can't open patterns file\n");
else
init(fp);
#ifdef _TESTING
if ((inp = fopen("input.asm", "r")) == NULL)
error("copt: can't open input.asm\n");
getlst(inp, "", &head, &tail);
#else
getlst(stdin, "", &head, &tail);
#endif
head.l_text = tail.l_text = "";
pass = 0;
do {
++pass;
if (debug)
fprintf(stderr, "\n--- pass %d ---\n", pass);
global_again = 0;
for (p = head.l_next; p != &tail; p = opt(p))
;
} while (global_again && pass < MAX_PASS);
if (global_again) {
fprintf(stderr, "error: maximum of %d passes exceeded\n", MAX_PASS);
error(" check for recursive substitutions");
}
printlines(head.l_next, &tail, stdout);
exit(0);
return 1; /* make compiler happy */
}
#define STACKSIZE 20
int sp;
int stack[STACKSIZE];
void push(int l)
{
if (sp < STACKSIZE)
stack[sp++] = l;
;
}
int pop()
{
if (sp > 0)
return stack[--sp];
return 0;
}
int top()
{
if (sp > 0)
return stack[sp - 1];
return 0;
}
int rpn_eval(const char* expr, char** vars)
{
const char* ptr = expr;
char* endptr;
int type;
int op2;
int n;
sp = 0;
while (*ptr) {
switch (*ptr++) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
n = strtoll(ptr - 1, &endptr, 10);
ptr = endptr;
push(n);
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '|':
op2 = pop();
push(pop() | op2);
break;
case '&':
op2 = pop();
push(pop() & op2);
break;
case '>':
op2 = pop();
push(pop() >> op2);
break;
case '<':
op2 = pop();
push(pop() << op2);
break;
case '/':
op2 = pop();
if (op2 != 0)
push(pop() / op2);
else
return 0; // Divide by zero
break;
case '%':
if ( isdigit(*ptr) ) {
// It's a variable
char v = *ptr++;
push(atoi(vars[v - '0']));
} else if ( *ptr++ == '%' ) {
op2 = pop();
if (op2 != 0) {
push(pop() % op2);
} else {
return 0; // Divide by zero
}
}
break;
}
}
return top();
}
|
the_stack_data/62636578.c
|
// RUN: jlang-cc -E %s 2>&1 | not grep error
#if 0
"
'
#endif
|
the_stack_data/76545.c
|
/*
* The problem
* -----------
* On platforms that use a two-level symbol namespace for dynamic libraries
* (most notably MacOS X), integrating tcmalloc requires special modifications.
*
* Most Unix platforms use a flat namespace for symbol lookup, which is why
* linking to tcmalloc causes it override malloc() and free() for the entire
* process. This is not the case on OS X: if Ruby calls a function from library
* that's not compiled with -flat_namespace, then that library will use the
* system's memory allocator instead of tcmalloc.
*
* The Ruby readline extension is a good example of how things can go wrong.
* The readline extension calls the readline() function in the readline library.
* This library is not compiled with -flat_namespace; readline() returns a string
* that's allocated by the system memory allocator. The Ruby readline extension
* then frees this string by passing it to tcmalloc's free() function. This
* results in a crash.
* Note that setting DYLD_FORCE_FLAT_NAMESPACE on OS X does not work: the
* resulting Ruby interpreter will crash immediately.
*
*
* The solution
* ------------
* This can be fixed by making it possible for Ruby extensions to call the
* system's memory allocator functions, instead of tcmalloc's, if it knows
* that a piece of memory is allocated by the system's memory allocator.
*
* This library, libsystem_allocator provides wrapper functions for the system
* memory allocator. libsystem_allocator will be compiled without -flat_namespace
* on OS X, and so it will always use the system's memory allocator instead of
* tcmalloc.
*
* libsystem_allocator will not be compiled on systems that only support flat
* namespaces (e.g. Linux). On those platforms, system_malloc() and
* system_free() have no special effect.
*/
#include <stdlib.h>
void *
system_malloc(long size)
{
return malloc(size);
}
void
system_free(void *ptr)
{
free(ptr);
}
|
the_stack_data/9304.c
|
#ifdef GAME_TEMPLATE
Game g_Game;
Game GetGame()
{
return g_Game;
}
class Game
{
ScriptModule GameScript;
ScriptModule GetScriptModule()
{
return GameScript;
}
void SetDebug(bool isDebug) {}
//!
/**
\brief Called when some system event occur.
@param eventTypeId event type.
@param params Param object, cast to specific param class to get parameters for particular event.
*/
void OnEvent(EventType eventTypeId, Param params)
{
Print("OnEvent");
}
/**
\brief Called after full initialization of Game instance
*/
void OnAfterInit()
{
Print("OnAfterInit");
}
/**
\brief Called on World update
@param timeslice time elapsed from last call
*/
void OnUpdate(float timeslice)
{
}
/**
\brief Sets world file to be loaded. Returns false if file doesn't exist.
@param path Path to the ent file
@param reload Force reload the world
*/
proto native bool SetWorldFile(string path, bool reload);
/**
\brief Returns path of world file loaded
*/
proto native owned string GetWorldFile();
/**
\brief Event which is called right before game starts (all entities are created and initialized). Returns true if the game can start.
*/
bool OnGameStart()
{
return true;
}
/**
\brief Event which is called right before game end.
*/
void OnGameEnd()
{
}
/**
\brief Creates loading screen
*/
void ShowLoadingAnim()
{
}
/**
\brief Hides loading screen
*/
void HideLoadingAnim()
{
}
/**
\brief Used for updating the loading screen
@param timeslice
@param progress loading progress between 0 and 1
*/
void UpdateLoadingAnim(float timeslice, float progress)
{
}
/**
\brief Safely instantiate the entity and calls EOnInit if the entity sets event mask EntityEvent.INIT.
@param typename Name of entity's type to instantiate.
@return instantiated entity
*/
proto native IEntity SpawnEntity(typename typeName);
/**
\brief Safely instantiate the entity from template (with all components) and calls EOnInit if the entity sets event mask EntityEvent.INIT.
@param templateResource Template resource of the entity to instantiate.
@return instantiated entity
*/
proto native IEntity SpawnEntityTemplate(vobject templateResource);
/**
\brief Safely instantiate the component from template, insert it to entity and calls EOnInit if the component sets event mask EntityEvent.INIT.
@param owner Entity which will own the component
@param templateResource Template resource of the component to instantiate.
@return instantiated component
*/
proto native GenericComponent SpawnComponentTemplate(IEntity owner, vobject templateResource);
proto native IEntity FindEntity(string name);
proto native WorkspaceWidget GetWorkspace();
/**
\brief Setting request flag for engine to exit the game
*/
proto native void RequestClose();
/**
\brief Setting request flag for the engine to reinitialize the game
* Doesn't do anything in Workbench
*/
proto native void RequestReload();
/**
\brief Returns version of the game
*/
proto native owned string GetBuildVersion();
/**
\brief Returns date and time when the game was built
*/
proto native owned string GetBuildTime();
/**
\brief Returns World entity when in game or in play mode in WE. NULL otherwise.
*/
proto native GenericWorldEntity GetWorldEntity();
proto native InputManager GetInputManager();
proto native MenuManager GetMenuManager();
proto native int GetTickCount();
}
void GameLibInit()
{
}
#endif
|
the_stack_data/184517880.c
|
#include<stdio.h>
int main(void) {
unsigned int a;
printf("RA: ");
scanf("%d", &a);
switch(a) {
case 10129:
printf("Maria Cândida Moreira Telles\n");
break;
case 33860:
printf("Larissa Garcia Alfonsi\n");
break;
case 33967:
printf("Leonardo Kozlowiski Kenupp\n");
break;
}
}
|
the_stack_data/61074109.c
|
/*
* Copyright (C) 2009-2021 Alex Smith
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* @file
* @brief String to integer functions.
*/
#include <stdlib.h>
/** Convert a string to an integer.
* @param s String to convert.
* @return Converted value. */
int atoi(const char *s) {
return (int)strtol(s, NULL, 10);
}
/** Convert a string to a double.
* @param s String to convert.
* @return Converted value. */
double atof(const char *s) {
return strtod(s, NULL);
}
/** Convert a string to a long long.
* @param s String to convert.
* @return Converted value. */
long long atoll(const char *s) {
return strtoll(s, NULL, 10);
}
/** Convert a string to a long.
* @param s String to convert.
* @return Converted value.
*/
long atol(const char *s) {
return strtol(s, NULL, 10);
}
|
the_stack_data/111079000.c
|
#include <stdio.h>
int main()
{
long long int n;
scanf("%lld", &n);
if(n%2==0) printf("%lld\n", n/2);
else printf("%lld\n", ((n-1)/2)-n);
return 0;
}
|
the_stack_data/68781.c
|
//
// Created by shinnlove on 2019-04-02.
//
#include <stdio.h>
/**
* 贝壳找房面试题:
*
* 有两个整型有序数组,num1数组中有m个有序数,整个数组长度为m+n;num2数组中有n个有序数,
* 现将num2数组元素合并到num1数组中,保持有序。
*
* 时间复杂度是:O(n2)。
*
* 优化:num1数组有序,还可以采用折半查找方式找到插入位置。
*
* 如果允许额外的空间复杂度,遍历O(m+n)就可以合并到新数组中。
*
* @return
*/
int main() {
// 初始化
int m = 6, n = 5;
int num1[11] = {2, 6, 8, 10, 12, 16};
int num2[5] = {1, 3, 5, 7, 11};
int sorted_count = 0;
// 将num2每个数插入num1
for (int i = n - 1; i >= 0; i--) {
// 寻找插入位置
int j = m - 1 + sorted_count;
for (j; j >= 0; j--) {
if (num2[i] > num1[j]) {
break;
}
}
// 移动num1数组
for (int k = m - 1 + sorted_count; k > j; k--) {
num1[k + 1] = num1[k];
}
// 将num2这个数放入
num1[j + 1] = num2[i];
sorted_count += 1;
}
printf("排序后的数组是:\n");
for (int k = 0; k < m + n; k++) {
printf("%d ", num1[k]);
}
printf("\n");
return 0;
}
|
the_stack_data/147576.c
|
/// Copyright (C) strawberryhacker
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.