file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/43887697.c | /* $NetBSD: malloc.c,v 1.4 2004/12/14 00:21:01 nathanw Exp $ */
/*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)malloc.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: malloc.c,v 1.4 2004/12/14 00:21:01 nathanw Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
/*
* malloc.c (Caltech) 2/21/82
* Chris Kingsley, kingsley@cit-20.
*
* This is a very fast storage allocator. It allocates blocks of a small
* number of different sizes, and keeps free lists of each size. Blocks that
* don't exactly fit are passed up to the next larger size. In this
* implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
* This is designed for use in a virtual memory environment.
*/
#include <sys/types.h>
#if defined(DEBUG) || defined(RCHECK)
#include <sys/uio.h>
#endif
#if defined(RCHECK) || defined(MSTATS)
#include <stdio.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
/*
* The overhead on a block is at least 4 bytes. When free, this space
* contains a pointer to the next free block, and the bottom two bits must
* be zero. When in use, the first byte is set to MAGIC, and the second
* byte is the size index. The remaining bytes are for alignment.
* If range checking is enabled then a second word holds the size of the
* requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
* The order of elements is critical: ov_magic must overlay the low order
* bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
*/
union overhead {
union overhead *ov_next; /* when free */
struct {
u_char ovu_magic; /* magic number */
u_char ovu_index; /* bucket # */
#ifdef RCHECK
u_short ovu_rmagic; /* range magic number */
u_long ovu_size; /* actual block size */
#endif
} ovu;
#define ov_magic ovu.ovu_magic
#define ov_index ovu.ovu_index
#define ov_rmagic ovu.ovu_rmagic
#define ov_size ovu.ovu_size
};
#define MAGIC 0xef /* magic # on accounting info */
#ifdef RCHECK
#define RMAGIC 0x5555 /* magic # on range info */
#endif
#ifdef RCHECK
#define RSLOP sizeof (u_short)
#else
#define RSLOP 0
#endif
/*
* nextf[i] is the pointer to the next free block of size 2^(i+3). The
* smallest allocatable block is 8 bytes. The overhead information
* precedes the data area returned to the user.
*/
#define NBUCKETS 30
static union overhead *nextf[NBUCKETS];
static long pagesz; /* page size */
static int pagebucket; /* page size bucket */
#ifdef MSTATS
/*
* nmalloc[i] is the difference between the number of mallocs and frees
* for a given block size.
*/
static u_int nmalloc[NBUCKETS];
#endif
static pthread_mutex_t malloc_mutex = PTHREAD_MUTEX_INITIALIZER;
static void morecore(int);
static int findbucket(union overhead *, int);
#ifdef MSTATS
void mstats(const char *);
#endif
#if defined(DEBUG) || defined(RCHECK)
#define ASSERT(p) if (!(p)) botch(__STRING(p))
static void botch(const char *);
/*
* NOTE: since this may be called while malloc_mutex is locked, stdio must not
* be used in this function.
*/
static void
botch(s)
const char *s;
{
struct iovec iov[3];
iov[0].iov_base = "\nassertion botched: ";
iov[0].iov_len = 20;
iov[1].iov_base = (void *)s;
iov[1].iov_len = strlen(s);
iov[2].iov_base = "\n";
iov[2].iov_len = 1;
/*
* This place deserves a word of warning: a cancellation point will
* occur when executing writev(), and we might be still owning
* malloc_mutex. At this point we need to disable cancellation
* until `after' abort() because i) establishing a cancellation handler
* might, depending on the implementation, result in another malloc()
* to be executed, and ii) it is really not desirable to let execution
* continue. `Fix me.'
*
* Note that holding mutex_lock during abort() is safe.
*/
(void)writev(STDERR_FILENO, iov, 3);
abort();
}
#else
#define ASSERT(p)
#endif
void *
malloc(nbytes)
size_t nbytes;
{
union overhead *op;
int bucket;
long n;
unsigned amt;
pthread_mutex_lock(&malloc_mutex);
/*
* First time malloc is called, setup page size and
* align break pointer so all data will be page aligned.
*/
if (pagesz == 0) {
pagesz = n = getpagesize();
ASSERT(pagesz > 0);
op = (union overhead *)(void *)sbrk(0);
n = n - sizeof (*op) - ((long)op & (n - 1));
if (n < 0)
n += pagesz;
if (n) {
if (sbrk((int)n) == (void *)-1) {
pthread_mutex_unlock(&malloc_mutex);
return (NULL);
}
}
bucket = 0;
amt = 8;
while (pagesz > amt) {
amt <<= 1;
bucket++;
}
pagebucket = bucket;
}
/*
* Convert amount of memory requested into closest block size
* stored in hash buckets which satisfies request.
* Account for space used per block for accounting.
*/
if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
#ifndef RCHECK
amt = 8; /* size of first bucket */
bucket = 0;
#else
amt = 16; /* size of first bucket */
bucket = 1;
#endif
n = -((long)sizeof (*op) + RSLOP);
} else {
amt = (unsigned)pagesz;
bucket = pagebucket;
}
while (nbytes > amt + n) {
amt <<= 1;
if (amt == 0)
return (NULL);
bucket++;
}
/*
* If nothing in hash bucket right now,
* request more memory from the system.
*/
if ((op = nextf[bucket]) == NULL) {
morecore(bucket);
if ((op = nextf[bucket]) == NULL) {
pthread_mutex_unlock(&malloc_mutex);
return (NULL);
}
}
/* remove from linked list */
nextf[bucket] = op->ov_next;
op->ov_magic = MAGIC;
op->ov_index = bucket;
#ifdef MSTATS
nmalloc[bucket]++;
#endif
pthread_mutex_unlock(&malloc_mutex);
#ifdef RCHECK
/*
* Record allocated size of block and
* bound space with magic numbers.
*/
op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
op->ov_rmagic = RMAGIC;
*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
#endif
return ((void *)(op + 1));
}
/*
* Allocate more memory to the indicated bucket.
*/
static void
morecore(bucket)
int bucket;
{
union overhead *op;
long sz; /* size of desired block */
long amt; /* amount to allocate */
long nblks; /* how many blocks we get */
/*
* sbrk_size <= 0 only for big, FLUFFY, requests (about
* 2^30 bytes on a VAX, I think) or for a negative arg.
*/
sz = 1 << (bucket + 3);
#ifdef DEBUG
ASSERT(sz > 0);
#else
if (sz <= 0)
return;
#endif
if (sz < pagesz) {
amt = pagesz;
nblks = amt / sz;
} else {
amt = sz + pagesz;
nblks = 1;
}
op = (union overhead *)(void *)sbrk((int)amt);
/* no more room! */
if ((long)op == -1)
return;
/*
* Add new memory allocated to that on
* free list for this hash bucket.
*/
nextf[bucket] = op;
while (--nblks > 0) {
op->ov_next =
(union overhead *)(void *)((caddr_t)(void *)op+(size_t)sz);
op = op->ov_next;
}
}
void
free(cp)
void *cp;
{
long size;
union overhead *op;
if (cp == NULL)
return;
op = (union overhead *)(void *)((caddr_t)cp - sizeof (union overhead));
#ifdef DEBUG
ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */
#else
if (op->ov_magic != MAGIC)
return; /* sanity */
#endif
#ifdef RCHECK
ASSERT(op->ov_rmagic == RMAGIC);
ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
#endif
size = op->ov_index;
ASSERT(size < NBUCKETS);
pthread_mutex_lock(&malloc_mutex);
op->ov_next = nextf[(unsigned int)size];/* also clobbers ov_magic */
nextf[(unsigned int)size] = op;
#ifdef MSTATS
nmalloc[(size_t)size]--;
#endif
pthread_mutex_unlock(&malloc_mutex);
}
/*
* When a program attempts "storage compaction" as mentioned in the
* old malloc man page, it realloc's an already freed block. Usually
* this is the last block it freed; occasionally it might be farther
* back. We have to search all the free lists for the block in order
* to determine its bucket: 1st we make one pass thru the lists
* checking only the first block in each; if that fails we search
* ``__realloc_srchlen'' blocks in each list for a match (the variable
* is extern so the caller can modify it). If that fails we just copy
* however many bytes was given to realloc() and hope it's not huge.
*/
int __realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */
void *
realloc(cp, nbytes)
void *cp;
size_t nbytes;
{
u_long onb;
long i;
union overhead *op;
char *res;
int was_alloced = 0;
if (cp == NULL)
return (malloc(nbytes));
if (nbytes == 0) {
free (cp);
return (NULL);
}
op = (union overhead *)(void *)((caddr_t)cp - sizeof (union overhead));
pthread_mutex_lock(&malloc_mutex);
if (op->ov_magic == MAGIC) {
was_alloced++;
i = op->ov_index;
} else {
/*
* Already free, doing "compaction".
*
* Search for the old block of memory on the
* free list. First, check the most common
* case (last element free'd), then (this failing)
* the last ``__realloc_srchlen'' items free'd.
* If all lookups fail, then assume the size of
* the memory block being realloc'd is the
* largest possible (so that all "nbytes" of new
* memory are copied into). Note that this could cause
* a memory fault if the old area was tiny, and the moon
* is gibbous. However, that is very unlikely.
*/
if ((i = findbucket(op, 1)) < 0 &&
(i = findbucket(op, __realloc_srchlen)) < 0)
i = NBUCKETS;
}
onb = (u_long)1 << (u_long)(i + 3);
if (onb < pagesz)
onb -= sizeof (*op) + RSLOP;
else
onb += pagesz - sizeof (*op) - RSLOP;
/* avoid the copy if same size block */
if (was_alloced) {
if (i) {
i = (long)1 << (long)(i + 2);
if (i < pagesz)
i -= sizeof (*op) + RSLOP;
else
i += pagesz - sizeof (*op) - RSLOP;
}
if (nbytes <= onb && nbytes > i) {
#ifdef RCHECK
op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
#endif
pthread_mutex_unlock(&malloc_mutex);
return (cp);
}
#ifndef _REENT
else
free(cp);
#endif
}
pthread_mutex_unlock(&malloc_mutex);
if ((res = malloc(nbytes)) == NULL) {
#ifdef _REENT
free(cp);
#endif
return (NULL);
}
#ifndef _REENT
if (cp != res) /* common optimization if "compacting" */
(void)memmove(res, cp, (size_t)((nbytes < onb) ? nbytes : onb));
#else
(void)memmove(res, cp, (size_t)((nbytes < onb) ? nbytes : onb));
free(cp);
#endif
return (res);
}
/*
* Search ``srchlen'' elements of each free list for a block whose
* header starts at ``freep''. If srchlen is -1 search the whole list.
* Return bucket number, or -1 if not found.
*/
static int
findbucket(freep, srchlen)
union overhead *freep;
int srchlen;
{
union overhead *p;
int i, j;
for (i = 0; i < NBUCKETS; i++) {
j = 0;
for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
if (p == freep)
return (i);
j++;
}
}
return (-1);
}
#ifdef MSTATS
/*
* mstats - print out statistics about malloc
*
* Prints two lines of numbers, one showing the length of the free list
* for each size category, the second showing the number of mallocs -
* frees for each size category.
*/
void
mstats(s)
char *s;
{
int i, j;
union overhead *p;
int totfree = 0,
totused = 0;
fprintf(stderr, "Memory allocation statistics %s\nfree: ", s);
for (i = 0; i < NBUCKETS; i++) {
for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
;
fprintf(stderr, " %d", j);
totfree += j * (1 << (i + 3));
}
fprintf(stderr, "\nused: ");
for (i = 0; i < NBUCKETS; i++) {
fprintf(stderr, " %d", nmalloc[i]);
totused += nmalloc[i] * (1 << (i + 3));
}
fprintf(stderr, "\n Total in use: %d, total free: %d\n",
totused, totfree);
}
#endif
|
the_stack_data/220454617.c | #include <ctype.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
/*
* Compare a string to a mask
* Mask characters:
* @ - uppercase letter
* # - lowercase letter
* & - hex digit
* # - digit
* * - swallow remaining characters
* <x> - exact match for any other character
*/
static int checkmask(const char *data, const char *mask)
{
int i, ch, d;
for (i = 0; mask[i] != '\0' && mask[i] != '*'; i++) {
ch = mask[i];
d = data[i];
if (ch == '@') {
if (!isupper(d))
return 0;
}
else if (ch == '$') {
if (!islower(d))
return 0;
}
else if (ch == '#') {
if (!isdigit(d))
return 0;
}
else if (ch == '&') {
if (!isxdigit(d))
return 0;
}
else if (ch != d)
return 0;
}
if (mask[i] == '*')
return 1;
else
return (data[i] == '\0');
}
/*
* Converts 8 hex digits to a time integer
*/
static int hex2sec(const char *x)
{
int i, ch;
unsigned int j;
for (i = 0, j = 0; i < 8; i++) {
ch = x[i];
j <<= 4;
if (isdigit(ch))
j |= ch - '0';
else if (isupper(ch))
j |= ch - ('A' - 10);
else
j |= ch - ('a' - 10);
}
if (j == 0xffffffff)
return -1; /* so that it works with 8-byte ints */
else
return j;
}
int main(int argc, char **argv)
{
int i, ver;
DIR *d;
struct dirent *e;
const char *s;
FILE *fp;
char path[FILENAME_MAX + 1];
char line[1035];
time_t date, lmod, expire;
unsigned int len;
struct tm ts;
char sdate[30], slmod[30], sexpire[30];
const char time_format[] = "%e %b %Y %R";
if (argc != 2) {
printf("Usage: cls directory\n");
exit(0);
}
d = opendir(argv[1]);
if (d == NULL) {
perror("opendir");
exit(1);
}
for (;;) {
e = readdir(d);
if (e == NULL)
break;
s = e->d_name;
if (s[0] == '.' || s[0] == '#')
continue;
sprintf(path, "%s/%s", argv[1], s);
fp = fopen(path, "r");
if (fp == NULL) {
perror("fopen");
continue;
}
if (fgets(line, 1034, fp) == NULL) {
perror("fgets");
fclose(fp);
continue;
}
if (!checkmask(line, "&&&&&&&& &&&&&&&& &&&&&&&& &&&&&&&& &&&&&&&&\n")) {
fprintf(stderr, "Bad cache file\n");
fclose(fp);
continue;
}
date = hex2sec(line);
lmod = hex2sec(line + 9);
expire = hex2sec(line + 18);
ver = hex2sec(line + 27);
len = hex2sec(line + 35);
if (fgets(line, 1034, fp) == NULL) {
perror("fgets");
fclose(fp);
continue;
}
fclose(fp);
i = strlen(line);
if (strncmp(line, "X-URL: ", 7) != 0 || line[i - 1] != '\n') {
fprintf(stderr, "Bad cache file\n");
continue;
}
line[i - 1] = '\0';
if (date != -1) {
ts = *gmtime(&date);
strftime(sdate, 30, time_format, &ts);
}
else
strcpy(sdate, "-");
if (lmod != -1) {
ts = *gmtime(&lmod);
strftime(slmod, 30, time_format, &ts);
}
else
strcpy(slmod, "-");
if (expire != -1) {
ts = *gmtime(&expire);
strftime(sexpire, 30, time_format, &ts);
}
else
strcpy(sexpire, "-");
printf("%s: %d; %s %s %s\n", line + 7, ver, sdate, slmod, sexpire);
}
closedir(d);
return 0;
}
|
the_stack_data/161081474.c | #include <stdio.h>
int fibo(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else if (n > 1)
return fibo(n - 1) + fibo(n - 2);
}
int main(void)
{
int n;
scanf("%d", &n);
printf("%d", fibo(n));
return 0;
}
|
the_stack_data/132952974.c | #include <stdio.h>
#define exchange(a, b) {int t; t = a; a = b; b = t;}
int main()
{
int x = 10;
int y = 20;
printf("x = %d y = %d \n", x, y);
exchange(x, y);
printf("x = %d y = %d \n", x, y);
return 0;
} |
the_stack_data/179830435.c | #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <string.h>
typedef struct sockaddr* saddrp;
#define PORT 23456
void udpack_recv(int sockfd, struct sockaddr_in addr,int i)
{
struct sockaddr_in src_addr;
char buff[256] = "";
int ret;
char *token = NULL;
char check[8] = "";
socklen_t addr_len = sizeof(struct sockaddr_in);
ret = recvfrom(sockfd,buff,sizeof(buff),0,(saddrp)&src_addr,&addr_len);
token = strtok(buff,"_");
sprintf(check,"%d",i);
if (ret && token)
{
if (strcmp(check,token) == 0) /*check the order of mesg*/
{
/*send ack to client for response*/
strcat(buff,"_ack");
sendto(sockfd,buff,strlen(buff)+1,0,(saddrp)&src_addr,sizeof(addr));
printf("send is %s\n",buff);
}
else
{
printf("Find the data loss\n");
return;
}
}
}
int main(int argc, char const *argv[])
{
int sockfd;
int ret;
int i;
sockfd = socket(AF_INET,SOCK_DGRAM,0);
if (0 > sockfd)
{
perror("sockfd");
return -1;
}
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = INADDR_ANY;
ret = bind(sockfd,(saddrp)&addr,sizeof(addr));
if (0 > ret)
{
perror("bind");
return -1;
}
//while(1)//just read from client
for (i=0; i<100; i++)
udpack_recv(sockfd,addr,i);
close(sockfd);
return 0;
}
|
the_stack_data/74570.c | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#define TAM 10
int main(int argc, char const *argv[]){
int matriz[TAM][TAM];
int linhas, colunas;
scanf("%d", &linhas);
scanf("%d", &colunas);
for(int l = 0; l < linhas; l++){
for(int c = 0; c < colunas; c++){
if(l < c){
matriz[l][c] = (2 * l) + (7 * c) - 2;
}else if(l > c){
matriz[l][c] = (4 * (l * l * l)) + (5 * (c * c)) + 1;
}else{
matriz[l][c] = (3 * (l * l)) - 1;
}
}
}
for(int linha = 0; linha < linhas; linha++){
for (int coluna = 0; coluna < colunas; coluna++){
printf("%d ", matriz[linha][coluna]);
}
printf("\n");
}
return 0;
} |
the_stack_data/53236.c | /*
======================================================================
vecmath.c
Basic vector and matrix functions.
Ernie Wright 17 Sep 00
====================================================================== */
#include <math.h>
float dot(float a[], float b[])
{
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
void cross(float a[], float b[], float c[])
{
c[0] = a[1] * b[2] - a[2] * b[1];
c[1] = a[2] * b[0] - a[0] * b[2];
c[2] = a[0] * b[1] - a[1] * b[0];
}
void normalize(float v[])
{
float r;
r = (float)sqrt(dot(v, v));
if(r > 0)
{
v[0] /= r;
v[1] /= r;
v[2] /= r;
}
}
|
the_stack_data/165768699.c | // C Program Swap Numbers in Cyclic Order Using Call by Reference
// This program takes three three integer value from user and swap the numbers in cyclic order using call by reference technique....
#include<stdio.h>
void cyclicSwap(int *a,int *b,int *c);
int main()
{
int a, b, c;
printf("Enter a, b and c respectively: ");
scanf("%d %d %d",&a,&b,&c);
printf("Value before swapping:\n");
printf("a = %d \nb = %d \nc = %d\n",a,b,c);
cyclicSwap(&a, &b, &c);
printf("Value after swapping:\n");
printf("a = %d \nb = %d \nc = %d",a, b, c);
return 0;
}
void cyclicSwap(int *a,int *b,int *c)
{
int temp;
// swapping in cyclic order
temp = *b;
*b = *a;
*a = *c;
*c = temp;
}
// https://www.programiz.com/c-programming/examples/swapping-cyclic-order |
the_stack_data/225144275.c | // KASAN: use-after-free Read in hci_get_auth_info
// https://syzkaller.appspot.com/bug?id=6aae86371d7bfc48f52a
// status:0
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sched.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <linux/capability.h>
#include <linux/futex.h>
#include <linux/genetlink.h>
#include <linux/if_addr.h>
#include <linux/if_ether.h>
#include <linux/if_link.h>
#include <linux/if_tun.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/neighbour.h>
#include <linux/net.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/tcp.h>
#include <linux/veth.h>
static unsigned long long procid;
static __thread int skip_segv;
static __thread jmp_buf segv_env;
static void segv_handler(int sig, siginfo_t* info, void* ctx)
{
uintptr_t addr = (uintptr_t)info->si_addr;
const uintptr_t prog_start = 1 << 20;
const uintptr_t prog_end = 100 << 20;
int skip = __atomic_load_n(&skip_segv, __ATOMIC_RELAXED) != 0;
int valid = addr < prog_start || addr > prog_end;
if (skip && valid) {
_longjmp(segv_env, 1);
}
exit(sig);
}
static void install_segv_handler(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8);
syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8);
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = segv_handler;
sa.sa_flags = SA_NODEFER | SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGBUS, &sa, NULL);
}
#define NONFAILING(...) \
{ \
__atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \
if (_setjmp(segv_env) == 0) { \
__VA_ARGS__; \
} \
__atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \
}
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
static uint64_t current_time_ms(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
exit(1);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static void use_temporary_dir(void)
{
char tmpdir_template[] = "./syzkaller.XXXXXX";
char* tmpdir = mkdtemp(tmpdir_template);
if (!tmpdir)
exit(1);
if (chmod(tmpdir, 0777))
exit(1);
if (chdir(tmpdir))
exit(1);
}
static void thread_start(void* (*fn)(void*), void* arg)
{
pthread_t th;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 128 << 10);
int i;
for (i = 0; i < 100; i++) {
if (pthread_create(&th, &attr, fn, arg) == 0) {
pthread_attr_destroy(&attr);
return;
}
if (errno == EAGAIN) {
usleep(50);
continue;
}
break;
}
exit(1);
}
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (ev->state)
exit(1);
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
static int event_isset(event_t* ev)
{
return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE);
}
static int event_timedwait(event_t* ev, uint64_t timeout)
{
uint64_t start = current_time_ms();
uint64_t now = start;
for (;;) {
uint64_t remain = timeout - (now - start);
struct timespec ts;
ts.tv_sec = remain / 1000;
ts.tv_nsec = (remain % 1000) * 1000 * 1000;
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts);
if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
return 1;
now = current_time_ms();
if (now - start > timeout)
return 0;
}
}
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
struct nlmsg {
char* pos;
int nesting;
struct nlattr* nested[8];
char buf[1024];
};
static struct nlmsg nlmsg;
static void netlink_init(struct nlmsg* nlmsg, int typ, int flags,
const void* data, int size)
{
memset(nlmsg, 0, sizeof(*nlmsg));
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_type = typ;
hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
memcpy(hdr + 1, data, size);
nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size);
}
static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data,
int size)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_len = sizeof(*attr) + size;
attr->nla_type = typ;
memcpy(attr + 1, data, size);
nlmsg->pos += NLMSG_ALIGN(attr->nla_len);
}
static void netlink_nest(struct nlmsg* nlmsg, int typ)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_type = typ;
nlmsg->pos += sizeof(*attr);
nlmsg->nested[nlmsg->nesting++] = attr;
}
static void netlink_done(struct nlmsg* nlmsg)
{
struct nlattr* attr = nlmsg->nested[--nlmsg->nesting];
attr->nla_len = nlmsg->pos - (char*)attr;
}
static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type,
int* reply_len)
{
if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting)
exit(1);
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_len = nlmsg->pos - nlmsg->buf;
struct sockaddr_nl addr;
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0,
(struct sockaddr*)&addr, sizeof(addr));
if (n != hdr->nlmsg_len)
exit(1);
n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
if (reply_len)
*reply_len = 0;
if (hdr->nlmsg_type == NLMSG_DONE)
return 0;
if (n < sizeof(struct nlmsghdr))
exit(1);
if (reply_len && hdr->nlmsg_type == reply_type) {
*reply_len = n;
return 0;
}
if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr))
exit(1);
if (hdr->nlmsg_type != NLMSG_ERROR)
exit(1);
return -((struct nlmsgerr*)(hdr + 1))->error;
}
static int netlink_send(struct nlmsg* nlmsg, int sock)
{
return netlink_send_ext(nlmsg, sock, 0, NULL);
}
static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset,
unsigned int total_len)
{
struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset);
if (offset == total_len || offset + hdr->nlmsg_len > total_len)
return -1;
return hdr->nlmsg_len;
}
static void netlink_add_device_impl(struct nlmsg* nlmsg, const char* type,
const char* name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
netlink_init(nlmsg, RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr,
sizeof(hdr));
if (name)
netlink_attr(nlmsg, IFLA_IFNAME, name, strlen(name));
netlink_nest(nlmsg, IFLA_LINKINFO);
netlink_attr(nlmsg, IFLA_INFO_KIND, type, strlen(type));
}
static void netlink_add_device(struct nlmsg* nlmsg, int sock, const char* type,
const char* name)
{
netlink_add_device_impl(nlmsg, type, name);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_veth(struct nlmsg* nlmsg, int sock, const char* name,
const char* peer)
{
netlink_add_device_impl(nlmsg, "veth", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_nest(nlmsg, VETH_INFO_PEER);
nlmsg->pos += sizeof(struct ifinfomsg);
netlink_attr(nlmsg, IFLA_IFNAME, peer, strlen(peer));
netlink_done(nlmsg);
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_hsr(struct nlmsg* nlmsg, int sock, const char* name,
const char* slave1, const char* slave2)
{
netlink_add_device_impl(nlmsg, "hsr", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
int ifindex1 = if_nametoindex(slave1);
netlink_attr(nlmsg, IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1));
int ifindex2 = if_nametoindex(slave2);
netlink_attr(nlmsg, IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2));
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_linked(struct nlmsg* nlmsg, int sock, const char* type,
const char* name, const char* link)
{
netlink_add_device_impl(nlmsg, type, name);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_vlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link, uint16_t id, uint16_t proto)
{
netlink_add_device_impl(nlmsg, "vlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_VLAN_ID, &id, sizeof(id));
netlink_attr(nlmsg, IFLA_VLAN_PROTOCOL, &proto, sizeof(proto));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_macvlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link)
{
netlink_add_device_impl(nlmsg, "macvlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
uint32_t mode = MACVLAN_MODE_BRIDGE;
netlink_attr(nlmsg, IFLA_MACVLAN_MODE, &mode, sizeof(mode));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_geneve(struct nlmsg* nlmsg, int sock, const char* name,
uint32_t vni, struct in_addr* addr4,
struct in6_addr* addr6)
{
netlink_add_device_impl(nlmsg, "geneve", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_GENEVE_ID, &vni, sizeof(vni));
if (addr4)
netlink_attr(nlmsg, IFLA_GENEVE_REMOTE, addr4, sizeof(*addr4));
if (addr6)
netlink_attr(nlmsg, IFLA_GENEVE_REMOTE6, addr6, sizeof(*addr6));
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
#define IFLA_IPVLAN_FLAGS 2
#define IPVLAN_MODE_L3S 2
#undef IPVLAN_F_VEPA
#define IPVLAN_F_VEPA 2
static void netlink_add_ipvlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link, uint16_t mode, uint16_t flags)
{
netlink_add_device_impl(nlmsg, "ipvlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_IPVLAN_MODE, &mode, sizeof(mode));
netlink_attr(nlmsg, IFLA_IPVLAN_FLAGS, &flags, sizeof(flags));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_device_change(struct nlmsg* nlmsg, int sock,
const char* name, bool up, const char* master,
const void* mac, int macsize,
const char* new_name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
if (up)
hdr.ifi_flags = hdr.ifi_change = IFF_UP;
hdr.ifi_index = if_nametoindex(name);
netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr));
if (new_name)
netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name));
if (master) {
int ifindex = if_nametoindex(master);
netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex));
}
if (macsize)
netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static int netlink_add_addr(struct nlmsg* nlmsg, int sock, const char* dev,
const void* addr, int addrsize)
{
struct ifaddrmsg hdr;
memset(&hdr, 0, sizeof(hdr));
hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6;
hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120;
hdr.ifa_scope = RT_SCOPE_UNIVERSE;
hdr.ifa_index = if_nametoindex(dev);
netlink_init(nlmsg, RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr,
sizeof(hdr));
netlink_attr(nlmsg, IFA_LOCAL, addr, addrsize);
netlink_attr(nlmsg, IFA_ADDRESS, addr, addrsize);
return netlink_send(nlmsg, sock);
}
static void netlink_add_addr4(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in_addr in_addr;
inet_pton(AF_INET, addr, &in_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in_addr, sizeof(in_addr));
(void)err;
}
static void netlink_add_addr6(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in6_addr in6_addr;
inet_pton(AF_INET6, addr, &in6_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in6_addr, sizeof(in6_addr));
(void)err;
}
static void netlink_add_neigh(struct nlmsg* nlmsg, int sock, const char* name,
const void* addr, int addrsize, const void* mac,
int macsize)
{
struct ndmsg hdr;
memset(&hdr, 0, sizeof(hdr));
hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6;
hdr.ndm_ifindex = if_nametoindex(name);
hdr.ndm_state = NUD_PERMANENT;
netlink_init(nlmsg, RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr,
sizeof(hdr));
netlink_attr(nlmsg, NDA_DST, addr, addrsize);
netlink_attr(nlmsg, NDA_LLADDR, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static int tunfd = -1;
#define TUN_IFACE "syz_tun"
#define LOCAL_MAC 0xaaaaaaaaaaaa
#define REMOTE_MAC 0xaaaaaaaaaabb
#define LOCAL_IPV4 "172.20.20.170"
#define REMOTE_IPV4 "172.20.20.187"
#define LOCAL_IPV6 "fe80::aa"
#define REMOTE_IPV6 "fe80::bb"
#define IFF_NAPI 0x0010
static void initialize_tun(void)
{
tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
if (tunfd == -1) {
printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n");
printf("otherwise fuzzing or reproducing might not work as intended\n");
return;
}
const int kTunFd = 240;
if (dup2(tunfd, kTunFd) < 0)
exit(1);
close(tunfd);
tunfd = kTunFd;
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ);
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) {
exit(1);
}
char sysctl[64];
sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE);
write_file(sysctl, "0");
sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE);
write_file(sysctl, "0");
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
netlink_add_addr4(&nlmsg, sock, TUN_IFACE, LOCAL_IPV4);
netlink_add_addr6(&nlmsg, sock, TUN_IFACE, LOCAL_IPV6);
uint64_t macaddr = REMOTE_MAC;
struct in_addr in_addr;
inet_pton(AF_INET, REMOTE_IPV4, &in_addr);
netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in_addr, sizeof(in_addr),
&macaddr, ETH_ALEN);
struct in6_addr in6_addr;
inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr);
netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in6_addr, sizeof(in6_addr),
&macaddr, ETH_ALEN);
macaddr = LOCAL_MAC;
netlink_device_change(&nlmsg, sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN,
NULL);
close(sock);
}
const int kInitNetNsFd = 239;
#define DEVLINK_FAMILY_NAME "devlink"
#define DEVLINK_CMD_PORT_GET 5
#define DEVLINK_ATTR_BUS_NAME 1
#define DEVLINK_ATTR_DEV_NAME 2
#define DEVLINK_ATTR_NETDEV_NAME 7
static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
struct nlattr* attr;
int err, n;
uint16_t id = 0;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME,
strlen(DEVLINK_FAMILY_NAME) + 1);
err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
return id;
}
static struct nlmsg nlmsg2;
static void initialize_devlink_ports(const char* bus_name, const char* dev_name,
const char* netdev_prefix)
{
struct genlmsghdr genlhdr;
int len, total_len, id, err, offset;
uint16_t netdev_index;
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (rtsock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_PORT_GET;
netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
err = netlink_send_ext(&nlmsg, sock, id, &total_len);
if (err) {
goto error;
}
offset = 0;
netdev_index = 0;
while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) {
struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg.buf + offset + len;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) {
char* port_name;
char netdev_name[IFNAMSIZ];
port_name = (char*)(attr + 1);
snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix,
netdev_index);
netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0,
netdev_name);
break;
}
}
offset += len;
netdev_index++;
}
error:
close(rtsock);
close(sock);
}
#define DEV_IPV4 "172.20.20.%d"
#define DEV_IPV6 "fe80::%02x"
#define DEV_MAC 0x00aaaaaaaaaa
static void netdevsim_add(unsigned int addr, unsigned int port_count)
{
char buf[16];
sprintf(buf, "%u %u", addr, port_count);
if (write_file("/sys/bus/netdevsim/new_device", buf)) {
snprintf(buf, sizeof(buf), "netdevsim%d", addr);
initialize_devlink_ports("netdevsim", buf, "netdevsim");
}
}
#define WG_GENL_NAME "wireguard"
enum wg_cmd {
WG_CMD_GET_DEVICE,
WG_CMD_SET_DEVICE,
};
enum wgdevice_attribute {
WGDEVICE_A_UNSPEC,
WGDEVICE_A_IFINDEX,
WGDEVICE_A_IFNAME,
WGDEVICE_A_PRIVATE_KEY,
WGDEVICE_A_PUBLIC_KEY,
WGDEVICE_A_FLAGS,
WGDEVICE_A_LISTEN_PORT,
WGDEVICE_A_FWMARK,
WGDEVICE_A_PEERS,
};
enum wgpeer_attribute {
WGPEER_A_UNSPEC,
WGPEER_A_PUBLIC_KEY,
WGPEER_A_PRESHARED_KEY,
WGPEER_A_FLAGS,
WGPEER_A_ENDPOINT,
WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
WGPEER_A_LAST_HANDSHAKE_TIME,
WGPEER_A_RX_BYTES,
WGPEER_A_TX_BYTES,
WGPEER_A_ALLOWEDIPS,
WGPEER_A_PROTOCOL_VERSION,
};
enum wgallowedip_attribute {
WGALLOWEDIP_A_UNSPEC,
WGALLOWEDIP_A_FAMILY,
WGALLOWEDIP_A_IPADDR,
WGALLOWEDIP_A_CIDR_MASK,
};
static int netlink_wireguard_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
struct nlattr* attr;
int err, n;
uint16_t id = 0;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, WG_GENL_NAME,
strlen(WG_GENL_NAME) + 1);
err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
return id;
}
static void netlink_wireguard_setup(void)
{
const char ifname_a[] = "wg0";
const char ifname_b[] = "wg1";
const char ifname_c[] = "wg2";
const char private_a[] =
"\xa0\x5c\xa8\x4f\x6c\x9c\x8e\x38\x53\xe2\xfd\x7a\x70\xae\x0f\xb2\x0f\xa1"
"\x52\x60\x0c\xb0\x08\x45\x17\x4f\x08\x07\x6f\x8d\x78\x43";
const char private_b[] =
"\xb0\x80\x73\xe8\xd4\x4e\x91\xe3\xda\x92\x2c\x22\x43\x82\x44\xbb\x88\x5c"
"\x69\xe2\x69\xc8\xe9\xd8\x35\xb1\x14\x29\x3a\x4d\xdc\x6e";
const char private_c[] =
"\xa0\xcb\x87\x9a\x47\xf5\xbc\x64\x4c\x0e\x69\x3f\xa6\xd0\x31\xc7\x4a\x15"
"\x53\xb6\xe9\x01\xb9\xff\x2f\x51\x8c\x78\x04\x2f\xb5\x42";
const char public_a[] =
"\x97\x5c\x9d\x81\xc9\x83\xc8\x20\x9e\xe7\x81\x25\x4b\x89\x9f\x8e\xd9\x25"
"\xae\x9f\x09\x23\xc2\x3c\x62\xf5\x3c\x57\xcd\xbf\x69\x1c";
const char public_b[] =
"\xd1\x73\x28\x99\xf6\x11\xcd\x89\x94\x03\x4d\x7f\x41\x3d\xc9\x57\x63\x0e"
"\x54\x93\xc2\x85\xac\xa4\x00\x65\xcb\x63\x11\xbe\x69\x6b";
const char public_c[] =
"\xf4\x4d\xa3\x67\xa8\x8e\xe6\x56\x4f\x02\x02\x11\x45\x67\x27\x08\x2f\x5c"
"\xeb\xee\x8b\x1b\xf5\xeb\x73\x37\x34\x1b\x45\x9b\x39\x22";
const uint16_t listen_a = 20001;
const uint16_t listen_b = 20002;
const uint16_t listen_c = 20003;
const uint16_t af_inet = AF_INET;
const uint16_t af_inet6 = AF_INET6;
const struct sockaddr_in endpoint_b_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_b),
.sin_addr = {htonl(INADDR_LOOPBACK)}};
const struct sockaddr_in endpoint_c_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_c),
.sin_addr = {htonl(INADDR_LOOPBACK)}};
struct sockaddr_in6 endpoint_a_v6 = {.sin6_family = AF_INET6,
.sin6_port = htons(listen_a)};
endpoint_a_v6.sin6_addr = in6addr_loopback;
struct sockaddr_in6 endpoint_c_v6 = {.sin6_family = AF_INET6,
.sin6_port = htons(listen_c)};
endpoint_c_v6.sin6_addr = in6addr_loopback;
const struct in_addr first_half_v4 = {0};
const struct in_addr second_half_v4 = {htonl(128 << 24)};
const struct in6_addr first_half_v6 = {{{0}}};
const struct in6_addr second_half_v6 = {{{0x80}}};
const uint8_t half_cidr = 1;
const uint16_t persistent_keepalives[] = {1, 3, 7, 9, 14, 19};
struct genlmsghdr genlhdr = {.cmd = WG_CMD_SET_DEVICE, .version = 1};
int sock;
int id, err;
sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1) {
return;
}
id = netlink_wireguard_id_get(&nlmsg, sock);
if (id == -1)
goto error;
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_a, strlen(ifname_a) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_a, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_a, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4,
sizeof(endpoint_b_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[0], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v6,
sizeof(endpoint_c_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[1], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_b, strlen(ifname_b) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_b, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_b, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6,
sizeof(endpoint_a_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[2], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v4,
sizeof(endpoint_c_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[3], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_c, strlen(ifname_c) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_c, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_c, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6,
sizeof(endpoint_a_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[4], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4,
sizeof(endpoint_b_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[5], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
error:
close(sock);
}
static void initialize_netdevices(void)
{
char netdevsim[16];
sprintf(netdevsim, "netdevsim%d", (int)procid);
struct {
const char* type;
const char* dev;
} devtypes[] = {
{"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"},
{"vcan", "vcan0"}, {"bond", "bond0"},
{"team", "team0"}, {"dummy", "dummy0"},
{"nlmon", "nlmon0"}, {"caif", "caif0"},
{"batadv", "batadv0"}, {"vxcan", "vxcan1"},
{"netdevsim", netdevsim}, {"veth", 0},
{"xfrm", "xfrm0"}, {"wireguard", "wg0"},
{"wireguard", "wg1"}, {"wireguard", "wg2"},
};
const char* devmasters[] = {"bridge", "bond", "team", "batadv"};
struct {
const char* name;
int macsize;
bool noipv6;
} devices[] = {
{"lo", ETH_ALEN},
{"sit0", 0},
{"bridge0", ETH_ALEN},
{"vcan0", 0, true},
{"tunl0", 0},
{"gre0", 0},
{"gretap0", ETH_ALEN},
{"ip_vti0", 0},
{"ip6_vti0", 0},
{"ip6tnl0", 0},
{"ip6gre0", 0},
{"ip6gretap0", ETH_ALEN},
{"erspan0", ETH_ALEN},
{"bond0", ETH_ALEN},
{"veth0", ETH_ALEN},
{"veth1", ETH_ALEN},
{"team0", ETH_ALEN},
{"veth0_to_bridge", ETH_ALEN},
{"veth1_to_bridge", ETH_ALEN},
{"veth0_to_bond", ETH_ALEN},
{"veth1_to_bond", ETH_ALEN},
{"veth0_to_team", ETH_ALEN},
{"veth1_to_team", ETH_ALEN},
{"veth0_to_hsr", ETH_ALEN},
{"veth1_to_hsr", ETH_ALEN},
{"hsr0", 0},
{"dummy0", ETH_ALEN},
{"nlmon0", 0},
{"vxcan0", 0, true},
{"vxcan1", 0, true},
{"caif0", ETH_ALEN},
{"batadv0", ETH_ALEN},
{netdevsim, ETH_ALEN},
{"xfrm0", ETH_ALEN},
{"veth0_virt_wifi", ETH_ALEN},
{"veth1_virt_wifi", ETH_ALEN},
{"virt_wifi0", ETH_ALEN},
{"veth0_vlan", ETH_ALEN},
{"veth1_vlan", ETH_ALEN},
{"vlan0", ETH_ALEN},
{"vlan1", ETH_ALEN},
{"macvlan0", ETH_ALEN},
{"macvlan1", ETH_ALEN},
{"ipvlan0", ETH_ALEN},
{"ipvlan1", ETH_ALEN},
{"veth0_macvtap", ETH_ALEN},
{"veth1_macvtap", ETH_ALEN},
{"macvtap0", ETH_ALEN},
{"macsec0", ETH_ALEN},
{"veth0_to_batadv", ETH_ALEN},
{"veth1_to_batadv", ETH_ALEN},
{"batadv_slave_0", ETH_ALEN},
{"batadv_slave_1", ETH_ALEN},
{"geneve0", ETH_ALEN},
{"geneve1", ETH_ALEN},
{"wg0", 0},
{"wg1", 0},
{"wg2", 0},
};
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
unsigned i;
for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++)
netlink_add_device(&nlmsg, sock, devtypes[i].type, devtypes[i].dev);
for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) {
char master[32], slave0[32], veth0[32], slave1[32], veth1[32];
sprintf(slave0, "%s_slave_0", devmasters[i]);
sprintf(veth0, "veth0_to_%s", devmasters[i]);
netlink_add_veth(&nlmsg, sock, slave0, veth0);
sprintf(slave1, "%s_slave_1", devmasters[i]);
sprintf(veth1, "veth1_to_%s", devmasters[i]);
netlink_add_veth(&nlmsg, sock, slave1, veth1);
sprintf(master, "%s0", devmasters[i]);
netlink_device_change(&nlmsg, sock, slave0, false, master, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, slave1, false, master, 0, 0, NULL);
}
netlink_device_change(&nlmsg, sock, "bridge_slave_0", true, 0, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, "bridge_slave_1", true, 0, 0, 0, NULL);
netlink_add_veth(&nlmsg, sock, "hsr_slave_0", "veth0_to_hsr");
netlink_add_veth(&nlmsg, sock, "hsr_slave_1", "veth1_to_hsr");
netlink_add_hsr(&nlmsg, sock, "hsr0", "hsr_slave_0", "hsr_slave_1");
netlink_device_change(&nlmsg, sock, "hsr_slave_0", true, 0, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, "hsr_slave_1", true, 0, 0, 0, NULL);
netlink_add_veth(&nlmsg, sock, "veth0_virt_wifi", "veth1_virt_wifi");
netlink_add_linked(&nlmsg, sock, "virt_wifi", "virt_wifi0",
"veth1_virt_wifi");
netlink_add_veth(&nlmsg, sock, "veth0_vlan", "veth1_vlan");
netlink_add_vlan(&nlmsg, sock, "vlan0", "veth0_vlan", 0, htons(ETH_P_8021Q));
netlink_add_vlan(&nlmsg, sock, "vlan1", "veth0_vlan", 1, htons(ETH_P_8021AD));
netlink_add_macvlan(&nlmsg, sock, "macvlan0", "veth1_vlan");
netlink_add_macvlan(&nlmsg, sock, "macvlan1", "veth1_vlan");
netlink_add_ipvlan(&nlmsg, sock, "ipvlan0", "veth0_vlan", IPVLAN_MODE_L2, 0);
netlink_add_ipvlan(&nlmsg, sock, "ipvlan1", "veth0_vlan", IPVLAN_MODE_L3S,
IPVLAN_F_VEPA);
netlink_add_veth(&nlmsg, sock, "veth0_macvtap", "veth1_macvtap");
netlink_add_linked(&nlmsg, sock, "macvtap", "macvtap0", "veth0_macvtap");
netlink_add_linked(&nlmsg, sock, "macsec", "macsec0", "veth1_macvtap");
char addr[32];
sprintf(addr, DEV_IPV4, 14 + 10);
struct in_addr geneve_addr4;
if (inet_pton(AF_INET, addr, &geneve_addr4) <= 0)
exit(1);
struct in6_addr geneve_addr6;
if (inet_pton(AF_INET6, "fc00::01", &geneve_addr6) <= 0)
exit(1);
netlink_add_geneve(&nlmsg, sock, "geneve0", 0, &geneve_addr4, 0);
netlink_add_geneve(&nlmsg, sock, "geneve1", 1, 0, &geneve_addr6);
netdevsim_add((int)procid, 4);
netlink_wireguard_setup();
for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) {
char addr[32];
sprintf(addr, DEV_IPV4, i + 10);
netlink_add_addr4(&nlmsg, sock, devices[i].name, addr);
if (!devices[i].noipv6) {
sprintf(addr, DEV_IPV6, i + 10);
netlink_add_addr6(&nlmsg, sock, devices[i].name, addr);
}
uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40);
netlink_device_change(&nlmsg, sock, devices[i].name, true, 0, &macaddr,
devices[i].macsize, NULL);
}
close(sock);
}
static void initialize_netdevices_init(void)
{
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
struct {
const char* type;
int macsize;
bool noipv6;
bool noup;
} devtypes[] = {
{"nr", 7, true},
{"rose", 5, true, true},
};
unsigned i;
for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) {
char dev[32], addr[32];
sprintf(dev, "%s%d", devtypes[i].type, (int)procid);
sprintf(addr, "172.30.%d.%d", i, (int)procid + 1);
netlink_add_addr4(&nlmsg, sock, dev, addr);
if (!devtypes[i].noipv6) {
sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1);
netlink_add_addr6(&nlmsg, sock, dev, addr);
}
int macsize = devtypes[i].macsize;
uint64_t macaddr = 0xbbbbbb +
((unsigned long long)i << (8 * (macsize - 2))) +
(procid << (8 * (macsize - 1)));
netlink_device_change(&nlmsg, sock, dev, !devtypes[i].noup, 0, &macaddr,
macsize, NULL);
}
close(sock);
}
static int read_tun(char* data, int size)
{
if (tunfd < 0)
return -1;
int rv = read(tunfd, data, size);
if (rv < 0) {
if (errno == EAGAIN || errno == EBADFD)
return -1;
exit(1);
}
return rv;
}
static void flush_tun()
{
char data[1000];
while (read_tun(&data[0], sizeof(data)) != -1) {
}
}
#define MAX_FDS 30
static long syz_init_net_socket(volatile long domain, volatile long type,
volatile long proto)
{
int netns = open("/proc/self/ns/net", O_RDONLY);
if (netns == -1)
return netns;
if (setns(kInitNetNsFd, 0))
return -1;
int sock = syscall(__NR_socket, domain, type, proto);
int err = errno;
if (setns(netns, 0))
exit(1);
close(netns);
errno = err;
return sock;
}
#define BTPROTO_HCI 1
#define ACL_LINK 1
#define SCAN_PAGE 2
typedef struct {
uint8_t b[6];
} __attribute__((packed)) bdaddr_t;
#define HCI_COMMAND_PKT 1
#define HCI_EVENT_PKT 4
#define HCI_VENDOR_PKT 0xff
struct hci_command_hdr {
uint16_t opcode;
uint8_t plen;
} __attribute__((packed));
struct hci_event_hdr {
uint8_t evt;
uint8_t plen;
} __attribute__((packed));
#define HCI_EV_CONN_COMPLETE 0x03
struct hci_ev_conn_complete {
uint8_t status;
uint16_t handle;
bdaddr_t bdaddr;
uint8_t link_type;
uint8_t encr_mode;
} __attribute__((packed));
#define HCI_EV_CONN_REQUEST 0x04
struct hci_ev_conn_request {
bdaddr_t bdaddr;
uint8_t dev_class[3];
uint8_t link_type;
} __attribute__((packed));
#define HCI_EV_REMOTE_FEATURES 0x0b
struct hci_ev_remote_features {
uint8_t status;
uint16_t handle;
uint8_t features[8];
} __attribute__((packed));
#define HCI_EV_CMD_COMPLETE 0x0e
struct hci_ev_cmd_complete {
uint8_t ncmd;
uint16_t opcode;
} __attribute__((packed));
#define HCI_OP_WRITE_SCAN_ENABLE 0x0c1a
#define HCI_OP_READ_BUFFER_SIZE 0x1005
struct hci_rp_read_buffer_size {
uint8_t status;
uint16_t acl_mtu;
uint8_t sco_mtu;
uint16_t acl_max_pkt;
uint16_t sco_max_pkt;
} __attribute__((packed));
#define HCI_OP_READ_BD_ADDR 0x1009
struct hci_rp_read_bd_addr {
uint8_t status;
bdaddr_t bdaddr;
} __attribute__((packed));
#define HCI_EV_LE_META 0x3e
struct hci_ev_le_meta {
uint8_t subevent;
} __attribute__((packed));
#define HCI_EV_LE_CONN_COMPLETE 0x01
struct hci_ev_le_conn_complete {
uint8_t status;
uint16_t handle;
uint8_t role;
uint8_t bdaddr_type;
bdaddr_t bdaddr;
uint16_t interval;
uint16_t latency;
uint16_t supervision_timeout;
uint8_t clk_accurancy;
} __attribute__((packed));
struct hci_dev_req {
uint16_t dev_id;
uint32_t dev_opt;
};
struct vhci_vendor_pkt {
uint8_t type;
uint8_t opcode;
uint16_t id;
};
#define HCIDEVUP _IOW('H', 201, int)
#define HCISETSCAN _IOW('H', 221, int)
static int vhci_fd = -1;
static void hci_send_event_packet(int fd, uint8_t evt, void* data,
size_t data_len)
{
struct iovec iv[3];
struct hci_event_hdr hdr;
hdr.evt = evt;
hdr.plen = data_len;
uint8_t type = HCI_EVENT_PKT;
iv[0].iov_base = &type;
iv[0].iov_len = sizeof(type);
iv[1].iov_base = &hdr;
iv[1].iov_len = sizeof(hdr);
iv[2].iov_base = data;
iv[2].iov_len = data_len;
if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0)
exit(1);
}
static void hci_send_event_cmd_complete(int fd, uint16_t opcode, void* data,
size_t data_len)
{
struct iovec iv[4];
struct hci_event_hdr hdr;
hdr.evt = HCI_EV_CMD_COMPLETE;
hdr.plen = sizeof(struct hci_ev_cmd_complete) + data_len;
struct hci_ev_cmd_complete evt_hdr;
evt_hdr.ncmd = 1;
evt_hdr.opcode = opcode;
uint8_t type = HCI_EVENT_PKT;
iv[0].iov_base = &type;
iv[0].iov_len = sizeof(type);
iv[1].iov_base = &hdr;
iv[1].iov_len = sizeof(hdr);
iv[2].iov_base = &evt_hdr;
iv[2].iov_len = sizeof(evt_hdr);
iv[3].iov_base = data;
iv[3].iov_len = data_len;
if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0)
exit(1);
}
static bool process_command_pkt(int fd, char* buf, ssize_t buf_size)
{
struct hci_command_hdr* hdr = (struct hci_command_hdr*)buf;
if (buf_size < (ssize_t)sizeof(struct hci_command_hdr) ||
hdr->plen != buf_size - sizeof(struct hci_command_hdr)) {
exit(1);
}
switch (hdr->opcode) {
case HCI_OP_WRITE_SCAN_ENABLE: {
uint8_t status = 0;
hci_send_event_cmd_complete(fd, hdr->opcode, &status, sizeof(status));
return true;
}
case HCI_OP_READ_BD_ADDR: {
struct hci_rp_read_bd_addr rp = {0};
rp.status = 0;
memset(&rp.bdaddr, 0xaa, 6);
hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp));
return false;
}
case HCI_OP_READ_BUFFER_SIZE: {
struct hci_rp_read_buffer_size rp = {0};
rp.status = 0;
rp.acl_mtu = 1021;
rp.sco_mtu = 96;
rp.acl_max_pkt = 4;
rp.sco_max_pkt = 6;
hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp));
return false;
}
}
char dummy[0xf9] = {0};
hci_send_event_cmd_complete(fd, hdr->opcode, dummy, sizeof(dummy));
return false;
}
static void* event_thread(void* arg)
{
while (1) {
char buf[1024] = {0};
ssize_t buf_size = read(vhci_fd, buf, sizeof(buf));
if (buf_size < 0)
exit(1);
if (buf_size > 0 && buf[0] == HCI_COMMAND_PKT) {
if (process_command_pkt(vhci_fd, buf + 1, buf_size - 1))
break;
}
}
return NULL;
}
#define HCI_HANDLE_1 200
#define HCI_HANDLE_2 201
static void initialize_vhci()
{
int hci_sock = syz_init_net_socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
if (hci_sock < 0)
exit(1);
vhci_fd = open("/dev/vhci", O_RDWR);
if (vhci_fd == -1)
exit(1);
const int kVhciFd = 241;
if (dup2(vhci_fd, kVhciFd) < 0)
exit(1);
close(vhci_fd);
vhci_fd = kVhciFd;
struct vhci_vendor_pkt vendor_pkt;
if (read(vhci_fd, &vendor_pkt, sizeof(vendor_pkt)) != sizeof(vendor_pkt))
exit(1);
if (vendor_pkt.type != HCI_VENDOR_PKT)
exit(1);
pthread_t th;
if (pthread_create(&th, NULL, event_thread, NULL))
exit(1);
if (ioctl(hci_sock, HCIDEVUP, vendor_pkt.id) && errno != EALREADY)
exit(1);
struct hci_dev_req dr = {0};
dr.dev_id = vendor_pkt.id;
dr.dev_opt = SCAN_PAGE;
if (ioctl(hci_sock, HCISETSCAN, &dr))
exit(1);
struct hci_ev_conn_request request;
memset(&request, 0, sizeof(request));
memset(&request.bdaddr, 0xaa, 6);
*(uint8_t*)&request.bdaddr.b[5] = 0x10;
request.link_type = ACL_LINK;
hci_send_event_packet(vhci_fd, HCI_EV_CONN_REQUEST, &request,
sizeof(request));
struct hci_ev_conn_complete complete;
memset(&complete, 0, sizeof(complete));
complete.status = 0;
complete.handle = HCI_HANDLE_1;
memset(&complete.bdaddr, 0xaa, 6);
*(uint8_t*)&complete.bdaddr.b[5] = 0x10;
complete.link_type = ACL_LINK;
complete.encr_mode = 0;
hci_send_event_packet(vhci_fd, HCI_EV_CONN_COMPLETE, &complete,
sizeof(complete));
struct hci_ev_remote_features features;
memset(&features, 0, sizeof(features));
features.status = 0;
features.handle = HCI_HANDLE_1;
hci_send_event_packet(vhci_fd, HCI_EV_REMOTE_FEATURES, &features,
sizeof(features));
struct {
struct hci_ev_le_meta le_meta;
struct hci_ev_le_conn_complete le_conn;
} le_conn;
memset(&le_conn, 0, sizeof(le_conn));
le_conn.le_meta.subevent = HCI_EV_LE_CONN_COMPLETE;
memset(&le_conn.le_conn.bdaddr, 0xaa, 6);
*(uint8_t*)&le_conn.le_conn.bdaddr.b[5] = 0x11;
le_conn.le_conn.role = 1;
le_conn.le_conn.handle = HCI_HANDLE_2;
hci_send_event_packet(vhci_fd, HCI_EV_LE_META, &le_conn, sizeof(le_conn));
pthread_join(th, NULL);
close(hci_sock);
}
static long syz_emit_vhci(volatile long a0, volatile long a1)
{
if (vhci_fd < 0)
return (uintptr_t)-1;
char* data = (char*)a0;
uint32_t length = a1;
return write(vhci_fd, data, length);
}
#define XT_TABLE_SIZE 1536
#define XT_MAX_ENTRIES 10
struct xt_counters {
uint64_t pcnt, bcnt;
};
struct ipt_getinfo {
char name[32];
unsigned int valid_hooks;
unsigned int hook_entry[5];
unsigned int underflow[5];
unsigned int num_entries;
unsigned int size;
};
struct ipt_get_entries {
char name[32];
unsigned int size;
void* entrytable[XT_TABLE_SIZE / sizeof(void*)];
};
struct ipt_replace {
char name[32];
unsigned int valid_hooks;
unsigned int num_entries;
unsigned int size;
unsigned int hook_entry[5];
unsigned int underflow[5];
unsigned int num_counters;
struct xt_counters* counters;
char entrytable[XT_TABLE_SIZE];
};
struct ipt_table_desc {
const char* name;
struct ipt_getinfo info;
struct ipt_replace replace;
};
static struct ipt_table_desc ipv4_tables[] = {
{.name = "filter"}, {.name = "nat"}, {.name = "mangle"},
{.name = "raw"}, {.name = "security"},
};
static struct ipt_table_desc ipv6_tables[] = {
{.name = "filter"}, {.name = "nat"}, {.name = "mangle"},
{.name = "raw"}, {.name = "security"},
};
#define IPT_BASE_CTL 64
#define IPT_SO_SET_REPLACE (IPT_BASE_CTL)
#define IPT_SO_GET_INFO (IPT_BASE_CTL)
#define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1)
struct arpt_getinfo {
char name[32];
unsigned int valid_hooks;
unsigned int hook_entry[3];
unsigned int underflow[3];
unsigned int num_entries;
unsigned int size;
};
struct arpt_get_entries {
char name[32];
unsigned int size;
void* entrytable[XT_TABLE_SIZE / sizeof(void*)];
};
struct arpt_replace {
char name[32];
unsigned int valid_hooks;
unsigned int num_entries;
unsigned int size;
unsigned int hook_entry[3];
unsigned int underflow[3];
unsigned int num_counters;
struct xt_counters* counters;
char entrytable[XT_TABLE_SIZE];
};
struct arpt_table_desc {
const char* name;
struct arpt_getinfo info;
struct arpt_replace replace;
};
static struct arpt_table_desc arpt_tables[] = {
{.name = "filter"},
};
#define ARPT_BASE_CTL 96
#define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL)
#define ARPT_SO_GET_INFO (ARPT_BASE_CTL)
#define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1)
static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables,
int family, int level)
{
struct ipt_get_entries entries;
socklen_t optlen;
int fd, i;
fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (i = 0; i < num_tables; i++) {
struct ipt_table_desc* table = &tables[i];
strcpy(table->info.name, table->name);
strcpy(table->replace.name, table->name);
optlen = sizeof(table->info);
if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
exit(1);
}
if (table->info.size > sizeof(table->replace.entrytable))
exit(1);
if (table->info.num_entries > XT_MAX_ENTRIES)
exit(1);
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size;
if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen))
exit(1);
table->replace.valid_hooks = table->info.valid_hooks;
table->replace.num_entries = table->info.num_entries;
table->replace.size = table->info.size;
memcpy(table->replace.hook_entry, table->info.hook_entry,
sizeof(table->replace.hook_entry));
memcpy(table->replace.underflow, table->info.underflow,
sizeof(table->replace.underflow));
memcpy(table->replace.entrytable, entries.entrytable, table->info.size);
}
close(fd);
}
static void reset_iptables(struct ipt_table_desc* tables, int num_tables,
int family, int level)
{
struct xt_counters counters[XT_MAX_ENTRIES];
struct ipt_get_entries entries;
struct ipt_getinfo info;
socklen_t optlen;
int fd, i;
fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (i = 0; i < num_tables; i++) {
struct ipt_table_desc* table = &tables[i];
if (table->info.valid_hooks == 0)
continue;
memset(&info, 0, sizeof(info));
strcpy(info.name, table->name);
optlen = sizeof(info);
if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen))
exit(1);
if (memcmp(&table->info, &info, sizeof(table->info)) == 0) {
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size;
if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen))
exit(1);
if (memcmp(table->replace.entrytable, entries.entrytable,
table->info.size) == 0)
continue;
}
table->replace.num_counters = info.num_entries;
table->replace.counters = counters;
optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) +
table->replace.size;
if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen))
exit(1);
}
close(fd);
}
static void checkpoint_arptables(void)
{
struct arpt_get_entries entries;
socklen_t optlen;
unsigned i;
int fd;
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) {
struct arpt_table_desc* table = &arpt_tables[i];
strcpy(table->info.name, table->name);
strcpy(table->replace.name, table->name);
optlen = sizeof(table->info);
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
exit(1);
}
if (table->info.size > sizeof(table->replace.entrytable))
exit(1);
if (table->info.num_entries > XT_MAX_ENTRIES)
exit(1);
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size;
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen))
exit(1);
table->replace.valid_hooks = table->info.valid_hooks;
table->replace.num_entries = table->info.num_entries;
table->replace.size = table->info.size;
memcpy(table->replace.hook_entry, table->info.hook_entry,
sizeof(table->replace.hook_entry));
memcpy(table->replace.underflow, table->info.underflow,
sizeof(table->replace.underflow));
memcpy(table->replace.entrytable, entries.entrytable, table->info.size);
}
close(fd);
}
static void reset_arptables()
{
struct xt_counters counters[XT_MAX_ENTRIES];
struct arpt_get_entries entries;
struct arpt_getinfo info;
socklen_t optlen;
unsigned i;
int fd;
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) {
struct arpt_table_desc* table = &arpt_tables[i];
if (table->info.valid_hooks == 0)
continue;
memset(&info, 0, sizeof(info));
strcpy(info.name, table->name);
optlen = sizeof(info);
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen))
exit(1);
if (memcmp(&table->info, &info, sizeof(table->info)) == 0) {
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size;
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen))
exit(1);
if (memcmp(table->replace.entrytable, entries.entrytable,
table->info.size) == 0)
continue;
} else {
}
table->replace.num_counters = info.num_entries;
table->replace.counters = counters;
optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) +
table->replace.size;
if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen))
exit(1);
}
close(fd);
}
#define NF_BR_NUMHOOKS 6
#define EBT_TABLE_MAXNAMELEN 32
#define EBT_CHAIN_MAXNAMELEN 32
#define EBT_BASE_CTL 128
#define EBT_SO_SET_ENTRIES (EBT_BASE_CTL)
#define EBT_SO_GET_INFO (EBT_BASE_CTL)
#define EBT_SO_GET_ENTRIES (EBT_SO_GET_INFO + 1)
#define EBT_SO_GET_INIT_INFO (EBT_SO_GET_ENTRIES + 1)
#define EBT_SO_GET_INIT_ENTRIES (EBT_SO_GET_INIT_INFO + 1)
struct ebt_replace {
char name[EBT_TABLE_MAXNAMELEN];
unsigned int valid_hooks;
unsigned int nentries;
unsigned int entries_size;
struct ebt_entries* hook_entry[NF_BR_NUMHOOKS];
unsigned int num_counters;
struct ebt_counter* counters;
char* entries;
};
struct ebt_entries {
unsigned int distinguisher;
char name[EBT_CHAIN_MAXNAMELEN];
unsigned int counter_offset;
int policy;
unsigned int nentries;
char data[0] __attribute__((aligned(__alignof__(struct ebt_replace))));
};
struct ebt_table_desc {
const char* name;
struct ebt_replace replace;
char entrytable[XT_TABLE_SIZE];
};
static struct ebt_table_desc ebt_tables[] = {
{.name = "filter"},
{.name = "nat"},
{.name = "broute"},
};
static void checkpoint_ebtables(void)
{
socklen_t optlen;
unsigned i;
int fd;
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) {
struct ebt_table_desc* table = &ebt_tables[i];
strcpy(table->replace.name, table->name);
optlen = sizeof(table->replace);
if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace,
&optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
exit(1);
}
if (table->replace.entries_size > sizeof(table->entrytable))
exit(1);
table->replace.num_counters = 0;
table->replace.entries = table->entrytable;
optlen = sizeof(table->replace) + table->replace.entries_size;
if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace,
&optlen))
exit(1);
}
close(fd);
}
static void reset_ebtables()
{
struct ebt_replace replace;
char entrytable[XT_TABLE_SIZE];
socklen_t optlen;
unsigned i, j, h;
int fd;
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) {
struct ebt_table_desc* table = &ebt_tables[i];
if (table->replace.valid_hooks == 0)
continue;
memset(&replace, 0, sizeof(replace));
strcpy(replace.name, table->name);
optlen = sizeof(replace);
if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen))
exit(1);
replace.num_counters = 0;
table->replace.entries = 0;
for (h = 0; h < NF_BR_NUMHOOKS; h++)
table->replace.hook_entry[h] = 0;
if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) {
memset(&entrytable, 0, sizeof(entrytable));
replace.entries = entrytable;
optlen = sizeof(replace) + replace.entries_size;
if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen))
exit(1);
if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0)
continue;
}
for (j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) {
if (table->replace.valid_hooks & (1 << h)) {
table->replace.hook_entry[h] =
(struct ebt_entries*)table->entrytable + j;
j++;
}
}
table->replace.entries = table->entrytable;
optlen = sizeof(table->replace) + table->replace.entries_size;
if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen))
exit(1);
}
close(fd);
}
static void checkpoint_net_namespace(void)
{
checkpoint_ebtables();
checkpoint_arptables();
checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]),
AF_INET, SOL_IP);
checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]),
AF_INET6, SOL_IPV6);
}
static void reset_net_namespace(void)
{
reset_ebtables();
reset_arptables();
reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]),
AF_INET, SOL_IP);
reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]),
AF_INET6, SOL_IPV6);
}
static void setup_cgroups()
{
if (mkdir("/syzcgroup", 0777)) {
}
if (mkdir("/syzcgroup/unified", 0777)) {
}
if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) {
}
if (chmod("/syzcgroup/unified", 0777)) {
}
write_file("/syzcgroup/unified/cgroup.subtree_control",
"+cpu +memory +io +pids +rdma");
if (mkdir("/syzcgroup/cpu", 0777)) {
}
if (mount("none", "/syzcgroup/cpu", "cgroup", 0,
"cpuset,cpuacct,perf_event,hugetlb")) {
}
write_file("/syzcgroup/cpu/cgroup.clone_children", "1");
write_file("/syzcgroup/cpu/cpuset.memory_pressure_enabled", "1");
if (chmod("/syzcgroup/cpu", 0777)) {
}
if (mkdir("/syzcgroup/net", 0777)) {
}
if (mount("none", "/syzcgroup/net", "cgroup", 0,
"net_cls,net_prio,devices,freezer")) {
}
if (chmod("/syzcgroup/net", 0777)) {
}
}
static void setup_cgroups_loop()
{
int pid = getpid();
char file[128];
char cgroupdir[64];
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid);
if (mkdir(cgroupdir, 0777)) {
}
snprintf(file, sizeof(file), "%s/pids.max", cgroupdir);
write_file(file, "32");
snprintf(file, sizeof(file), "%s/memory.low", cgroupdir);
write_file(file, "%d", 298 << 20);
snprintf(file, sizeof(file), "%s/memory.high", cgroupdir);
write_file(file, "%d", 299 << 20);
snprintf(file, sizeof(file), "%s/memory.max", cgroupdir);
write_file(file, "%d", 300 << 20);
snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir);
write_file(file, "%d", pid);
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid);
if (mkdir(cgroupdir, 0777)) {
}
snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir);
write_file(file, "%d", pid);
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid);
if (mkdir(cgroupdir, 0777)) {
}
snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir);
write_file(file, "%d", pid);
}
static void setup_cgroups_test()
{
char cgroupdir[64];
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid);
if (symlink(cgroupdir, "./cgroup")) {
}
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid);
if (symlink(cgroupdir, "./cgroup.cpu")) {
}
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid);
if (symlink(cgroupdir, "./cgroup.net")) {
}
}
static void setup_common()
{
if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) {
}
setup_cgroups();
}
static void loop();
static void sandbox_common()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
setsid();
int netns = open("/proc/self/ns/net", O_RDONLY);
if (netns == -1)
exit(1);
if (dup2(netns, kInitNetNsFd) < 0)
exit(1);
close(netns);
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = (200 << 20);
setrlimit(RLIMIT_AS, &rlim);
rlim.rlim_cur = rlim.rlim_max = 32 << 20;
setrlimit(RLIMIT_MEMLOCK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 136 << 20;
setrlimit(RLIMIT_FSIZE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 1 << 20;
setrlimit(RLIMIT_STACK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 0;
setrlimit(RLIMIT_CORE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 256;
setrlimit(RLIMIT_NOFILE, &rlim);
if (unshare(CLONE_NEWNS)) {
}
if (unshare(CLONE_NEWIPC)) {
}
if (unshare(0x02000000)) {
}
if (unshare(CLONE_NEWUTS)) {
}
if (unshare(CLONE_SYSVSEM)) {
}
typedef struct {
const char* name;
const char* value;
} sysctl_t;
static const sysctl_t sysctls[] = {
{"/proc/sys/kernel/shmmax", "16777216"},
{"/proc/sys/kernel/shmall", "536870912"},
{"/proc/sys/kernel/shmmni", "1024"},
{"/proc/sys/kernel/msgmax", "8192"},
{"/proc/sys/kernel/msgmni", "1024"},
{"/proc/sys/kernel/msgmnb", "1024"},
{"/proc/sys/kernel/sem", "1024 1048576 500 1024"},
};
unsigned i;
for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++)
write_file(sysctls[i].name, sysctls[i].value);
}
static int wait_for_loop(int pid)
{
if (pid < 0)
exit(1);
int status = 0;
while (waitpid(-1, &status, __WALL) != pid) {
}
return WEXITSTATUS(status);
}
static void drop_caps(void)
{
struct __user_cap_header_struct cap_hdr = {};
struct __user_cap_data_struct cap_data[2] = {};
cap_hdr.version = _LINUX_CAPABILITY_VERSION_3;
cap_hdr.pid = getpid();
if (syscall(SYS_capget, &cap_hdr, &cap_data))
exit(1);
const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE);
cap_data[0].effective &= ~drop;
cap_data[0].permitted &= ~drop;
cap_data[0].inheritable &= ~drop;
if (syscall(SYS_capset, &cap_hdr, &cap_data))
exit(1);
}
static int do_sandbox_none(void)
{
if (unshare(CLONE_NEWPID)) {
}
int pid = fork();
if (pid != 0)
return wait_for_loop(pid);
setup_common();
sandbox_common();
drop_caps();
initialize_netdevices_init();
if (unshare(CLONE_NEWNET)) {
}
initialize_tun();
initialize_netdevices();
initialize_vhci();
loop();
exit(1);
}
#define FS_IOC_SETFLAGS _IOW('f', 2, long)
static void remove_dir(const char* dir)
{
DIR* dp;
struct dirent* ep;
int iter = 0;
retry:
dp = opendir(dir);
if (dp == NULL) {
if (errno == EMFILE) {
exit(1);
}
exit(1);
}
while ((ep = readdir(dp))) {
if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0)
continue;
char filename[FILENAME_MAX];
snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name);
struct stat st;
if (lstat(filename, &st))
exit(1);
if (S_ISDIR(st.st_mode)) {
remove_dir(filename);
continue;
}
int i;
for (i = 0;; i++) {
if (unlink(filename) == 0)
break;
if (errno == EPERM) {
int fd = open(filename, O_RDONLY);
if (fd != -1) {
long flags = 0;
if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) {
}
close(fd);
continue;
}
}
if (errno == EROFS) {
break;
}
if (errno != EBUSY || i > 100)
exit(1);
}
}
closedir(dp);
int i;
for (i = 0;; i++) {
if (rmdir(dir) == 0)
break;
if (i < 100) {
if (errno == EPERM) {
int fd = open(dir, O_RDONLY);
if (fd != -1) {
long flags = 0;
if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) {
}
close(fd);
continue;
}
}
if (errno == EROFS) {
break;
}
if (errno == EBUSY) {
continue;
}
if (errno == ENOTEMPTY) {
if (iter < 100) {
iter++;
goto retry;
}
}
}
exit(1);
}
}
static void kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
int i;
for (i = 0; i < 100; i++) {
if (waitpid(-1, status, WNOHANG | __WALL) == pid)
return;
usleep(1000);
}
DIR* dir = opendir("/sys/fs/fuse/connections");
if (dir) {
for (;;) {
struct dirent* ent = readdir(dir);
if (!ent)
break;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char abort[300];
snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort",
ent->d_name);
int fd = open(abort, O_WRONLY);
if (fd == -1) {
continue;
}
if (write(fd, abort, 1) < 0) {
}
close(fd);
}
closedir(dir);
} else {
}
while (waitpid(-1, status, __WALL) != pid) {
}
}
static void setup_loop()
{
setup_cgroups_loop();
checkpoint_net_namespace();
}
static void reset_loop()
{
reset_net_namespace();
}
static void setup_test()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
setup_cgroups_test();
write_file("/proc/self/oom_score_adj", "1000");
flush_tun();
}
static void close_fds()
{
int fd;
for (fd = 3; fd < MAX_FDS; fd++)
close(fd);
}
static void setup_binfmt_misc()
{
if (mount(0, "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, 0)) {
}
write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:\x01::./file0:");
write_file("/proc/sys/fs/binfmt_misc/register",
":syz1:M:1:\x02::./file0:POC");
}
struct thread_t {
int created, call;
event_t ready, done;
};
static struct thread_t threads[16];
static void execute_call(int call);
static int running;
static void* thr(void* arg)
{
struct thread_t* th = (struct thread_t*)arg;
for (;;) {
event_wait(&th->ready);
event_reset(&th->ready);
execute_call(th->call);
__atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED);
event_set(&th->done);
}
return 0;
}
static void execute_one(void)
{
int i, call, thread;
int collide = 0;
again:
for (call = 0; call < 16; call++) {
for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0]));
thread++) {
struct thread_t* th = &threads[thread];
if (!th->created) {
th->created = 1;
event_init(&th->ready);
event_init(&th->done);
event_set(&th->done);
thread_start(thr, th);
}
if (!event_isset(&th->done))
continue;
event_reset(&th->done);
th->call = call;
__atomic_fetch_add(&running, 1, __ATOMIC_RELAXED);
event_set(&th->ready);
if (collide && (call % 2) == 0)
break;
event_timedwait(&th->done, 45);
break;
}
}
for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++)
sleep_ms(1);
close_fds();
if (!collide) {
collide = 1;
goto again;
}
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
setup_loop();
int iter;
for (iter = 0;; iter++) {
char cwdbuf[32];
sprintf(cwdbuf, "./%d", iter);
if (mkdir(cwdbuf, 0777))
exit(1);
reset_loop();
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
if (chdir(cwdbuf))
exit(1);
setup_test();
execute_one();
exit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
break;
sleep_ms(1);
if (current_time_ms() - start < 5 * 1000)
continue;
kill_and_wait(pid, &status);
break;
}
remove_dir(cwdbuf);
}
}
uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff};
void execute_call(int call)
{
intptr_t res = 0;
switch (call) {
case 0:
res = -1;
NONFAILING(res = syz_init_net_socket(0x1f, 3, 1));
if (res != -1)
r[0] = res;
break;
case 1:
syscall(__NR_bind, r[0], 0ul, 0ul);
break;
case 2:
syscall(__NR_ioctl, r[0], 0x800448d7, 0ul);
break;
case 3:
syscall(__NR_ioctl, -1, 0x5411, 0ul);
break;
case 4:
res = -1;
NONFAILING(res = syz_init_net_socket(0x1f, 3, 1));
if (res != -1)
r[1] = res;
break;
case 5:
NONFAILING(*(uint16_t*)0x20000140 = 0x1f);
NONFAILING(*(uint16_t*)0x20000142 = 0);
NONFAILING(*(uint16_t*)0x20000144 = 0);
syscall(__NR_bind, r[1], 0x20000140ul, 6ul);
break;
case 6:
syscall(__NR_ioctl, r[1], 0x800448d7, 0x20000000ul);
break;
case 7:
res = -1;
NONFAILING(res = syz_init_net_socket(0x1f, 3, 1));
if (res != -1)
r[2] = res;
break;
case 8:
syscall(__NR_bind, r[2], 0ul, 0ul);
break;
case 9:
syscall(__NR_ioctl, r[2], 0x800448d7, 0x20000000ul);
break;
case 10:
syscall(__NR_write, r[2], 0ul, 0ul);
break;
case 11:
NONFAILING(syz_init_net_socket(0x1f, 3, 1));
break;
case 12:
syscall(__NR_bind, r[1], 0ul, 0ul);
break;
case 13:
syscall(__NR_ioctl, -1, 0, 0x20000000ul);
break;
case 14:
NONFAILING(syz_emit_vhci(0, 0));
break;
case 15:
syscall(__NR_getsockopt, -1, 1, 0x41, 0ul, 0ul);
break;
}
}
int main(void)
{
syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
setup_binfmt_misc();
install_segv_handler();
for (procid = 0; procid < 6; procid++) {
if (fork() == 0) {
use_temporary_dir();
do_sandbox_none();
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/24938.c | #include <assert.h>
#include <stdio.h>
typedef struct
{
int R;
int G;
int B;
} Pixel;
static Pixel pic[1080][1920]; // 看作横向的图,所以第二个分量反而更大
// 单个16进制字符转换成十进制数字
static inline int char2int(char c)
{
return c >= '0' && c <= '9' ? c - '0' :
c >= 'a' && c <= 'f' ? c - 'a' + 10 :
c >= 'A' && c <= 'F' ? c - 'A' + 10 :
-1;
}
// 两个16进制字符转换成十进制数字
static inline int OneColor2int(char a, char b)
{
return char2int(a) * 16 + char2int(b);
}
static void FillPixel(Pixel *p, char *line)
{
if (line[2] == '\0')
{
int c = OneColor2int(line[1], line[1]);
p->R = c;
p->G = c;
p->B = c;
}
else if (line[4] == '\0')
{
p->R = OneColor2int(line[1], line[1]);
p->G = OneColor2int(line[2], line[2]);
p->B = OneColor2int(line[3], line[3]);
}
else if (line[7] == '\0')
{
p->R = OneColor2int(line[1], line[2]);
p->G = OneColor2int(line[3], line[4]);
p->B = OneColor2int(line[5], line[6]);
}
else
assert(0);
}
static void PAdd(Pixel *a, Pixel b)
{
a->R += b.R;
a->G += b.G;
a->B += b.B;
}
static void PAve(Pixel *a, int num)
{
a->R /= num;
a->G /= num;
a->B /= num;
}
static inline int PEql(Pixel a, Pixel b)
{
return a.R == b.R && a.G == b.G && a.B == b.B;
}
// 假如颜色的值是255,要看成三个**字符**输出16进制
static void OneColorPrint_BAD(int c)
{
int t = c / 100;
if (t != 0)
printf("\\x%x", t + '0');
t = c % 100 / 10;
if (t != 0) // 此处出了BUG,如果百位不为0,十位为0,仍然要输出十位的0,而此代码不会
printf("\\x%x", t + '0');
t = c % 10;
printf("\\x%x", t + '0');
// 三个全部为0已经在外面处理了,但假如其中有一个分量为0,仍然要输出0,即最后一个不能有if
}
// 修复上面的BUG
static void OneColorPrint(int c)
{
char buf[4];
sprintf(buf, "%d", c);
for (char *p = buf; *p != '\0'; p++)
printf("\\x%x", *p); // 注意不用+'0'
}
int main()
{
int m, n, p, q;
scanf("%d %d %d %d", &m, &n, &p, &q);
getchar(); // 去掉换行符
for (int i = 0; i < n; i++) // n是行指针界限(“高”)
for (int j = 0; j < m; j++) // m是纵坐标界限(“宽”)
{
char line[8];
gets(line);
FillPixel(&pic[i][j], line);
}
for (int r = 0; r < n; r += q)
{
Pixel pipre = {0}; // 每次换行,值初始化为黑色
for (int c = 0; c < m; c += p) // (r,c)即一个块的起始坐标
{
Pixel pi = {0};
for (int i = r; i < r + q; i++)
for (int j = c; j < c + p; j++)
PAdd(&pi, pic[i][j]);
PAve(&pi, p * q);
if (!PEql(pi, pipre)) // 和前一个颜色一样就不用改
if (PEql(pi, (Pixel){0}))
printf("\\x1B\\x5B\\x30\\x6D"); // 题目说了如果当前颜色是纯黑,直接用重置
else
{
// 手动更改颜色
//printf("\\x1B\\x5B\\x34\\x38\\x3B\\x32\\x3B\\x%X\\x3B\\x%X\\x3B\\x%X\x6D");
printf("\\x1B\\x5B\\x34\\x38\\x3B\\x32\\x3B");
OneColorPrint(pi.R);
printf("\\x3B");
OneColorPrint(pi.G);
printf("\\x3B");
OneColorPrint(pi.B);
printf("\\x6D");
}
printf("\\x20"); // space
pipre = pi;
}
if (!PEql(pipre, (Pixel){0})) // 如果是黑色就不用输出重置的信息了
printf("\\x1B\\x5B\\x30\\x6D");
printf("\\x0A"); // 换行
}
}
|
the_stack_data/162205.c | // RUN: %clang_builtins %s %librt -o %t && %run %t
// REQUIRES: librt_has_gedf2vfp
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <math.h>
extern int __gedf2vfp(double a, double b);
#if defined(__arm__) && defined(__ARM_FP) && (__ARM_FP & 0x8)
int test__gedf2vfp(double a, double b)
{
int actual = __gedf2vfp(a, b);
int expected = (a >= b) ? 1 : 0;
if (actual != expected)
printf("error in __gedf2vfp(%f, %f) = %d, expected %d\n",
a, b, actual, expected);
return actual != expected;
}
#endif
int main()
{
#if defined(__arm__) && defined(__ARM_FP) && (__ARM_FP & 0x8)
if (test__gedf2vfp(0.0, 0.0))
return 1;
if (test__gedf2vfp(1.0, 0.0))
return 1;
if (test__gedf2vfp(-1.0, -2.0))
return 1;
if (test__gedf2vfp(-2.0, -1.0))
return 1;
if (test__gedf2vfp(HUGE_VAL, 1.0))
return 1;
if (test__gedf2vfp(1.0, HUGE_VAL))
return 1;
#else
printf("skipped\n");
#endif
return 0;
}
|
the_stack_data/178264895.c | #include <stdbool.h>
#include <stdio.h>
#define N 10
void quick_sort(int a[], int low, int high);
int split(int a[], int low, int high);
int main() {
int a[N];
printf("Enter %d numbers to be sorted: ", N);
for (int i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
quick_sort(a, 0, N - 1);
printf("In sorted order: ");
for (int i = 0; i < N; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
void quick_sort(int a[], int low, int high) {
int middle;
if (low >= high)
return;
middle = split(a, low, high);
quick_sort(a, low, middle - 1);
quick_sort(a, middle + 1, high);
}
int split(int a[], int low, int high) {
int part_element = a[low];
while (true) {
while (low < high && part_element <= a[high])
high--;
if (low >= high)
break;
a[low++] = a[high];
while (low < high && a[low] <= part_element)
low++;
if (low >= high)
break;
a[high--] = a[low];
}
a[high] = part_element;
return high;
}
// test: 9 16 47 82 4 66 12 3 25 51 |
the_stack_data/145543.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: exam <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/26 11:11:42 by exam #+# #+# */
/* Updated: 2019/07/26 11:32:51 by exam ### ########.fr */
/* */
/* ************************************************************************** */
int ft_atoi(const char *str)
{
int nb;
int is_negative;
while (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r'
|| *str == '\v' || *str == '\f'|| *str == '\r')
str++;
is_negative = 0;
if (*str == '+' || *str == '-')
{
if (*str == '-')
is_negative = 1;
str++;
}
nb = 0;
while (*str >= '0' && *str <= '9')
{
nb *= 10;
nb += *str - '0';
str++;
}
if (is_negative)
nb = -nb;
return (nb);
}
|
the_stack_data/165769511.c | /*
Write a multithreaded program that calculates the summation
of non-negative integers in a separate thread and passes the
result to the main thread.
*/
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void* summation(void *param)
{
// initializing array
int* arr = (int*)param;
long sum = 0;
int n = arr[0];
// summing and returning
for(int i = 1;i <= n;i++) {
if(arr[i] > 0)
sum += arr[i];
}
return (void*)sum;
}
int main(int argc, char const *argv[])
{
// initializing and getting the numbers
int n;
printf("Enter the no. of numbers : \n");
scanf("%d",&n);
// dynamically initializing our array
int* arr = (int*)malloc((n+1)*sizeof(int));
arr[0] = n;
// entering values
printf("Enter the numbers : \n");
for(int i= 1;i <= n;i++)
{
scanf("%d",&arr[i]);
}
int answer = 0;
// creating thread
pthread_t thread;
// running routine and passing array
pthread_create(&thread,0,&summation,(void*)arr);
// joining child threads to the main thread
pthread_join(thread,(void**)&answer);
// printing answer
printf("Summation of non-negative numbers = %d\n",answer);
return 0;
} |
the_stack_data/117329026.c | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
double x;
void
print_format_int(const char * format_string,int parameter1,int parameter2)
{
printf("\"");
printf(format_string,parameter1);
printf("\"\t");
printf("Value = % d, Format = \"%s\"\n",parameter1,format_string);
printf("\"");
printf(format_string,parameter2);
printf("\"\t");
printf("Value = % d, Format = \"%s\"\n",parameter2,format_string);
}
void
print_format_char(const char * format_string,char parameter)
{
printf("\"");
printf(format_string,parameter);
printf("\"\t");
printf("Value = '%c', Format = \"%s\"\n",parameter,format_string);
}
void
print_format_string(const char * format_string,const char *parameter1,const char *parameter2)
{
printf("\"");
printf(format_string,parameter1);
printf("\"\t");
printf("Value = \"%s\", Format = \"%s\"\n",parameter1,format_string);
printf("\"");
printf(format_string,parameter2);
printf("\"\t");
printf("Value = \"%s\", Format = \"%s\"\n",parameter2,format_string);
}
void
print_format_float(const char * format_string,double parameter1,double parameter2)
{
printf("\"");
printf(format_string,parameter1);
printf("\"\t");
printf("Value = % f, Format = \"%s\"\n",parameter1,format_string);
printf("\"");
printf(format_string,parameter2);
printf("\"\t");
printf("Value = % f, Format = \"%s\"\n",parameter2,format_string);
}
int
main(void)
{
/*
unsigned long foo[2] = { 0x41f00000, 0 };
memcpy(&x,foo,sizeof(x));
printf("%.20g\n",x);
*/
print_format_int("%12d",45,-45);
print_format_int("%012d",45,-45);
print_format_int("% 012d",45,-45);
print_format_int("%+12d",45,-45);
print_format_int("%+012d",45,-45);
print_format_int("%-12d",45,-45);
print_format_int("%- 12d",45,-45);
print_format_int("%-+12d",45,-45);
print_format_int("%12.4d",45,-45);
print_format_int("%-12.4d",45,-45);
print_format_int("%12.0d",45,-45);
printf("\n");
print_format_int("%14u",45,-45);
print_format_int("%014u",45,-45);
print_format_int("%#14u",45,-45);
print_format_int("%#014u",45,-45);
print_format_int("%-14u",45,-45);
print_format_int("%-#14u",45,-45);
print_format_int("%14.4u",45,-45);
print_format_int("%-14.4u",45,-45);
print_format_int("%14.0u",45,-45);
printf("\n");
print_format_int("%14o",45,-45);
print_format_int("%014o",45,-45);
print_format_int("%#14o",45,-45);
print_format_int("%#014o",45,-45);
print_format_int("%-14o",45,-45);
print_format_int("%-#14o",45,-45);
print_format_int("%14.4o",45,-45);
print_format_int("%-14.4o",45,-45);
print_format_int("%14.0o",45,-45);
printf("\n");
print_format_int("%12x",45,-45);
print_format_int("%012x",45,-45);
print_format_int("%#12X",45,-45);
print_format_int("%#012X",45,-45);
print_format_int("%-12x",45,-45);
print_format_int("%-#12x",45,-45);
print_format_int("%12.4x",45,-45);
print_format_int("%-12.4x",45,-45);
print_format_int("%12.0x",45,-45);
printf("\n");
print_format_char("%12c",'*');
print_format_char("%012c",'*');
print_format_char("%-12c",'*');
print_format_char("%12.0c",'*');
printf("\n");
print_format_string("%12s","zap","longish");
print_format_string("%12.5s","zap","longish");
print_format_string("%012s","zap","longish");
print_format_string("%-12s","zap","longish");
print_format_string("%12.0s","zap","longish");
printf("\n");
print_format_float("%10.2f",12.678,-12.678);
print_format_float("%010.2f",12.678,-12.678);
print_format_float("% 010.2f",12.678,-12.678);
print_format_float("%+10.2f",12.678,-12.678);
print_format_float("%+010.2f",12.678,-12.678);
print_format_float("%-10.2f",12.678,-12.678);
print_format_float("%- 10.2f",12.678,-12.678);
print_format_float("%-+10.4f",12.678,-12.678);
print_format_float("%f",12.678,-12.678);
print_format_float("%10f",12.678,-12.678);
print_format_float("%10.0f",12.678,-12.678);
printf("\n");
print_format_float("%10.2e",12.678,-12.678);
print_format_float("%010.2e",12.678,-12.678);
print_format_float("% 010.2e",12.678,-12.678);
print_format_float("%+10.2E",12.678,-12.678);
print_format_float("%+010.2E",12.678,-12.678);
print_format_float("%-10.2e",12.678,-12.678);
print_format_float("%- 10.2e",12.678,-12.678);
print_format_float("%-+10.2e",12.678,-12.678);
print_format_float("%e",12.678,-12.678);
print_format_float("%10e",12.678,-12.678);
print_format_float("%10.0e",12.678,-12.678);
printf("\n");
print_format_float("%10.2a",12.678,-12.678);
print_format_float("%010.2a",12.678,-12.678);
print_format_float("% 010.2a",12.678,-12.678);
print_format_float("%+10.2A",12.678,-12.678);
print_format_float("%+010.2A",12.678,-12.678);
print_format_float("%-10.2a",12.678,-12.678);
print_format_float("%- 10.2a",12.678,-12.678);
print_format_float("%-+10.2a",12.678,-12.678);
print_format_float("%a",12.678,-12.678);
print_format_float("%10a",12.678,-12.678);
print_format_float("%10.0a",12.678,-12.678);
printf("\n");
print_format_float("%10.2g",12.678,-12.678);
print_format_float("%010.2g",12.678,-12.678);
print_format_float("% 010.2g",12.678,-12.678);
print_format_float("%+10.2G",12.678,-12.678);
print_format_float("%+010.2G",12.678,-12.678);
print_format_float("%-10.2g",12.678,-12.678);
print_format_float("%- 10.2g",12.678,-12.678);
print_format_float("%-+10.2g",12.678,-12.678);
print_format_float("%g",12.678,-12.678);
print_format_float("%10g",12.678,-12.678);
print_format_float("%10.0g",12.678,-12.678);
printf("\n");
print_format_float("%10.2g",0.678,-0.678);
print_format_float("%010.2g",0.678,-0.678);
print_format_float("% 010.2g",0.678,-0.678);
print_format_float("%+10.2G",0.678,-0.678);
print_format_float("%+010.2G",0.678,-0.678);
print_format_float("%-10.2g",0.678,-0.678);
print_format_float("%- 10.2g",0.678,-0.678);
print_format_float("%-+10.2g",0.678,-0.678);
print_format_float("%g",0.678,-0.678);
print_format_float("%10g",0.678,-0.678);
print_format_float("%10.0g",0.678,-0.678);
printf("\n");
print_format_float("%10.2g",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("%010.2g",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("% 010.2g",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("%+10.2G",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("%+010.2G",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("%-10.2g",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("%- 10.2g",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("%-+10.2g",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("%g",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("%10g",strtod("infinity",NULL),strtod("-infinity",NULL));
print_format_float("%10.0g",strtod("infinity",NULL),strtod("-infinity",NULL));
printf("\n");
print_format_float("%10.2g",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("%010.2g",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("% 010.2g",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("%+10.2G",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("%+010.2G",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("%-10.2g",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("%- 10.2g",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("%-+10.2g",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("%g",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("%10g",strtod("nan",NULL),strtod("-nan",NULL));
print_format_float("%10.0g",strtod("nan",NULL),strtod("-nan",NULL));
return(0);
}
|
the_stack_data/26700555.c | // RUN: %ucc -c %s -o %t
f();
main()
{
const int x = 0;
if(!!f() != x)
;
}
|
the_stack_data/86075428.c | // RUN: touch %t.o
//
// RUN: %clang -target x86_64-unknown-linux -### %t.o -flto 2>&1 \
// RUN: -Wl,-plugin-opt=foo -O3 \
// RUN: | FileCheck %s --check-prefix=CHECK-X86-64-BASIC
// CHECK-X86-64-BASIC: "-plugin" "{{.*}}/LLVMgold.so"
// CHECK-X86-64-BASIC: "-plugin-opt=O3"
// CHECK-X86-64-BASIC: "-plugin-opt=foo"
//
// RUN: %clang -target x86_64-unknown-linux -### %t.o -flto 2>&1 \
// RUN: -march=corei7 -Wl,-plugin-opt=foo -Ofast \
// RUN: | FileCheck %s --check-prefix=CHECK-X86-64-COREI7
// CHECK-X86-64-COREI7: "-plugin" "{{.*}}/LLVMgold.so"
// CHECK-X86-64-COREI7: "-plugin-opt=mcpu=corei7"
// CHECK-X86-64-COREI7: "-plugin-opt=O3"
// CHECK-X86-64-COREI7: "-plugin-opt=foo"
//
// RUN: %clang -target arm-unknown-linux -### %t.o -flto 2>&1 \
// RUN: -march=armv7a -Wl,-plugin-opt=foo -O0 \
// RUN: | FileCheck %s --check-prefix=CHECK-ARM-V7A
// CHECK-ARM-V7A: "-plugin" "{{.*}}/LLVMgold.so"
// CHECK-ARM-V7A: "-plugin-opt=mcpu=generic"
// CHECK-ARM-V7A: "-plugin-opt=O0"
// CHECK-ARM-V7A: "-plugin-opt=foo"
//
// RUN: %clang -target i686-linux-android -### %t.o -flto 2>&1 \
// RUN: | FileCheck %s --check-prefix=CHECK-X86-ANDROID
// CHECK-X86-ANDROID: "-plugin" "{{.*}}/LLVMgold.so"
|
the_stack_data/31386452.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAXTAM 65536
typedef struct {
int indice;
int forca;
} TItem;
TItem dados(int indice, int forca){
TItem competidor;
competidor.indice = indice;
competidor.forca = forca;
return competidor;
}
typedef struct {
TItem Item[MAXTAM];
int Frente, Tras;
int tamanho;
} TFila;
void TFila_Inicia(TFila *pFila)
{
pFila->Frente = 0;
pFila->Tras = 0;
pFila->tamanho = 0;
} /* TFila_Inicia */
int TFila_EhVazia(TFila *pFila)
{
return (pFila->Frente == pFila->Tras);
} /* TFila_EhVazia */
int TFila_Enfileira(TFila *pFila, TItem x)
{
pFila->Item[pFila->Tras] = x;
pFila->Tras = (pFila->Tras + 1) % MAXTAM;
pFila->tamanho++;
return 1;
} /* TFila_Enfileira */
int TFila_Desenfileira(TFila *pFila, TItem *pX)
{
if (TFila_EhVazia(pFila))
return 0;
*pX = pFila->Item[pFila->Frente];
pFila->Frente = (pFila->Frente + 1) % MAXTAM;
pFila->tamanho--;
return 1;
} /* TFila_Desenfileira */
int main(){
TFila pFila;
int n, k, ncompetidores, i=0;
int forca1;
TItem a, b;
TFila_Inicia(&pFila);
scanf("%d %d", &n, &k);
ncompetidores = pow(2,n);
for (i=0; i<ncompetidores; i++){
scanf("%d",&forca1);
TFila_Enfileira(&pFila, dados(i+1, forca1));
}
while(pFila.tamanho > 1){
TFila_Desenfileira(&pFila, &a);
TFila_Desenfileira(&pFila, &b);
if (a.forca >= b.forca){
forca1 = a.forca - b.forca;
forca1 = forca1 + k;
TFila_Enfileira(&pFila, dados(a.indice, forca1));
}
else{
forca1 = b.forca - a.forca;
forca1 = forca1 + k;
TFila_Enfileira(&pFila, dados(b.indice, forca1));
}
}
TFila_Desenfileira(&pFila, &a);
printf("%d",a.indice);
return 0;
} |
the_stack_data/25137632.c | /*Exercise 1-10, replace tabs with \t, backspaces with \b, and backslashes by \\ */
#include <stdio.h>
int main(){
int c;
while((c = getchar()) != EOF){
if(c == '\t'){
printf("%s","\\t");
getchar(); //we call getchar() to move to next char
}
if(c =='\b'){
printf("%s","\\b");
getchar(); //
}
if(c == '\\'){
printf("%s","\\");
getchar();
}
putchar(c);
}
}
|
the_stack_data/69824.c | void assert(int cond) { if (!cond) { ERROR: return; } }
extern int __VERIFIER_nondet_int();
int main() {
int x = 0;
int p;
int z = __VERIFIER_nondet_int();
if (z > 100) {
p = 0;
} else {
p = 1;
}
while (__VERIFIER_nondet_int()) {
x++;
}
// todo: for some reason CPAchecker gets confused in the absence of brackets.
assert((z > 100 && p == 0)
|| (z <= 100 && p == 1));
}
|
the_stack_data/153268728.c | int b[3] = {4, 5, 6};
int j = 1, k;
void main()
{
k = b[j]--;
print("k 5");
printid(k);
}
|
the_stack_data/26520.c | /* Arithmetic instruction */
#include <stdint.h>
void main(void)
{
volatile int32_t a = 0xd32a9455, b = 0xa369974e, c;
c = a + b;
c = 0; //$ch.c
return; //$bre
}
|
the_stack_data/212642141.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct people_tag{
char firtsname[16];
char lastname[16];
unsigned int age;
struct people_tag *next;
}people_t;
int main(int argc, char *argv[])
{
people_t *head = NULL;
people_t *new;
people_t *list;
char *name[]={"Andy", "John", "Peter", "Raul", NULL};
char *last[]={"Mans", "Doe", "Mars", "Gonzales", NULL};
unsigned int age[]= {22, 34, 24, 18, 0};
int i = 0;
while(name[i])
{
new = (people_t *) malloc(sizeof(people_t));
if(new == NULL)
{
fprintf(stderr, "Unable to allocate memory.\n");
exit(1);
}
strcpy(new->firtsname, name[i]);
strcpy(new->lastname, last[i]);
new->age = age[i];
new->next = head;
head = new;
i++;
}
list = head;
while(list != NULL)
{
printf("Firstname: %s\n", list->firtsname );
printf("Lastname: %s\n", list->lastname);
printf("Age: %d\n\n", list->age);
list = list->next;
}
/* Free Memory before exit the program */
list = head;
while(list != NULL)
{
head = list->next;
free(list);
list = head;
}
return 0;
}
|
the_stack_data/150142146.c | #include <stdio.h>
int main(void) {
int t;
scanf("%d", &t);
while(t--)
{
float i, j, k;
scanf("%f %f %f", &i, &j, &k);
if((i>50) && (j<0.7) && (k>5600)){
printf("10\n");
}
else if((i>50) && (j<0.7)){
printf("9\n");
}
else if((j<0.7) && (k>5600)){
printf("8\n");
}
else if((i>50) && (k>5600)){
printf("7\n");
}
else if((i>50) || (j<0.7) || (k>5600)){
printf("6\n");
}
else if((i<=50) && (j>=0.7) && (k<=5600)){
printf("5\n");
}
}
return 0;
}
|
the_stack_data/618218.c | #include <stdio.h>
int main()
{
char c1, c2;
c1 = getchar();
c2 = getchar();
putchar(c1);
putchar(c2);
printf("\n%c %c", c1, c2);
return 0;
} |
the_stack_data/117513.c | #include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0)
printf("Fizz");
if (i % 5 == 0)
printf("Buzz");
if (i % 3 != 0 && i % 5 != 0)
printf("%d", i);
printf("\n");
}
return 0;
}
|
the_stack_data/130255.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <getopt.h>
#include <errno.h>
#include <sys/time.h>
struct timespec nanosleep_ts = { 1, 0 };
unsigned long long cpumask = 0;
int flag_accumulation = 0;
int flag_tick = 0;
int flag_wide = 0;
int flag_period = 0;
unsigned int period_sec = 0;
double delay_sec = 1.0;
struct cpu_stat {
unsigned long user;
unsigned long nice;
unsigned long sys;
unsigned long idle;
unsigned long iowait;
unsigned long irq;
unsigned long softirq;
};
const struct cpu_stat INITIAL_CPU_STAT = {0};
struct cpu_stat last_cpu_stat = {0};
struct cpu_stat accum_cpu_stat = {0};
struct cpu_stat last_each_cpu_stat[64] = {{0}};
const char STR_STAT_HEADER_TIMESTAMP[] = "date time ";
const char STR_STAT_HEADER[] = "user% nice% sys% idle%";
const char STR_STAT_HEADER_WIDE[] = "iowait% irq% softirq%";
const char STR_STAT_HEADER_TICK[] = "user nice sys idle iowait irq softirq total";
void usage(int argc, char * const argv[])
{
fprintf(stderr, "Usage:\n %s [OPTION]...\n\n", argv[0]);
fprintf(stderr, "Options:\n");
fprintf(stderr, " -d, --delay=SEC delay-time interval\n");
fprintf(stderr, " -c, --cpumask=MASK specify cpu-mask\n");
fprintf(stderr, " -a, --accumulation accumulate each cpus if cpu-mask is specified\n");
fprintf(stderr, " -w, --wide show cpu rate of iowait, irq and softirq\n");
fprintf(stderr, " -t, --tick show tick instead of cpu rate\n");
fprintf(stderr, " -p, --period=SEC measurement time\n");
fprintf(stderr, " -h, --help display this help\n");
exit(-1);
}
int parse_opt(int argc, char * const argv[])
{
int c;
long nsec;
char *endptr;
while (1) {
int option_index = 0;
static const struct option long_options[] = {
{"delay", required_argument, 0, 'd' },
{"cpumask", required_argument, 0, 'c' },
{"accumulation", no_argument, 0, 'a' },
{"wide", no_argument, 0, 'w' },
{"tick", no_argument, 0, 't' },
{"help", no_argument, 0, 'h' },
{"period", no_argument, 0, 'p' },
{0, 0, 0, 0 }
};
c = getopt_long(argc, argv, "c:d:awtp:h",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'a':
flag_accumulation = 1;
break;
case 'c':
cpumask = strtoull(optarg, NULL, 16);
if ( 0 == cpumask )
{
fprintf(stderr, "cpumask should not be zero.\n");
usage(argc, argv);
}
break;
case 'd':
nanosleep_ts.tv_sec = (time_t)strtoul(optarg,&endptr,10);
if( endptr )
{
delay_sec = strtod(endptr, NULL);
nsec = (long)(1000*1000*1000*strtod(endptr, NULL));
if( nsec > 999999999 ) nsec = 999999999;
nanosleep_ts.tv_nsec = nsec;
}
sscanf(optarg, "%lf", &delay_sec);
break;
case 'w':
flag_wide = 1;
break;
case 't':
flag_tick = 1;
break;
case 'p':
flag_period = 1;
sscanf(optarg, "%u", &period_sec);
break;
case 'h':
case '?':
default:
usage(argc, argv);
}
}
return 0;
}
void accumulate_cpu_stat( struct cpu_stat * const accum, const struct cpu_stat * const current )
{
accum->user += current->user;
accum->nice += current->nice;
accum->sys += current->sys;
accum->idle += current->idle;
accum->iowait += current->iowait;
accum->irq += current->irq;
accum->softirq += current->softirq;
return;
}
void show_timestamp(void)
{
struct timeval tv;
struct tm tm;
gettimeofday(&tv, NULL);
localtime_r(&tv.tv_sec, &tm);
printf("%04d/%02d/%02d %02d:%02d:%02d.%06d",
tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec, (int)tv.tv_usec);
return;
}
void show_cpu_rate( const struct cpu_stat * const last, const struct cpu_stat * const current)
{
unsigned long total;
show_timestamp();
total = current->user - last->user +
current->nice - last->nice +
current->sys - last->sys +
current->idle - last->idle +
current->iowait - last->iowait +
current->irq - last->irq +
current->softirq - last->softirq;
if( 0 == total )
{
printf("- - - -\n");
return;
}
if ( !flag_tick )
{
printf(" %ld.%02ld%% %ld.%02ld%% %ld.%02ld%% %ld.%02ld%%",
(((current->user - last->user)*10000)/total)/100,
(((current->user - last->user)*10000)/total)%100,
(((current->nice - last->nice)*10000)/total)/100,
(((current->nice - last->nice)*10000)/total)%100,
(((current->sys - last->sys)*10000)/total)/100,
(((current->sys - last->sys)*10000)/total)%100,
(((current->idle - last->idle)*10000)/total)/100,
(((current->idle - last->idle)*10000)/total)%100);
if( flag_wide )
{
printf(" %ld.%02ld%% %ld.%02ld%% %ld.%02ld%%",
(((current->iowait - last->iowait)*10000)/total)/100,
(((current->iowait - last->iowait)*10000)/total)%100,
(((current->irq - last->irq)*10000)/total)/100,
(((current->irq - last->irq)*10000)/total)%100,
(((current->softirq - last->softirq)*10000)/total)/100,
(((current->softirq - last->softirq)*10000)/total)%100);
}
}
else
{
printf(" %ld %ld %ld %ld %ld %ld %ld %ld",
current->user - last->user,
current->nice - last->nice,
current->sys - last->sys,
current->idle - last->idle,
current->iowait - last->iowait,
current->irq - last->irq,
current->softirq - last->softirq,
total);
}
printf("\n");
return;
}
void show_header(void)
{
if ( cpumask && !flag_accumulation ) printf("cpu# ");
printf("%s", STR_STAT_HEADER_TIMESTAMP);
if ( !flag_tick )
{
printf(" %s", STR_STAT_HEADER);
if ( flag_wide ) printf(" %s", STR_STAT_HEADER_WIDE);
}
else
{
printf(" %s", STR_STAT_HEADER_TICK);
}
printf("\n");
return;
}
void monitor_each_cpu(void)
{
FILE *fp;
struct cpu_stat cpu;
int n;
unsigned int maxbit=0;
unsigned long long b, cpuno;
char buf[1024];
unsigned int loop_count = 0;
unsigned int max_loop_count = period_sec * (unsigned int)(1.0/delay_sec);
for(b = cpumask ; b!=0 ; b>>=1, maxbit++);
for(;;)
{
fp = fopen("/proc/stat", "r" );
if ( NULL == fp ) {
perror("fopen");
break;
}
/* skip first line */
if ( NULL == fgets(buf, sizeof(buf), fp) )
{
perror("fgets");
break;
}
for(b=0 ; b<maxbit ; b++)
{
if ( NULL == fgets(buf, sizeof(buf), fp) )
{
perror("fgets");
break;
}
if( !(cpumask & (1ULL<<b)) ) continue;
n = sscanf(buf, "cpu%llu %ld %ld %ld %ld %ld %ld %ld",
&cpuno, &cpu.user, &cpu.nice, &cpu.sys, &cpu.idle,
&cpu.iowait, &cpu.irq, &cpu.softirq );
if ( EOF == n )
{
perror("sscanf");
break;
}
if ( n != 8 )
{
fprintf(stderr, "parse error (%d)\n",n);
break;
}
if ( cpuno != b )
{
fprintf(stderr, "number error ? (line:%llu cpu%llu)\n", b+1, cpuno);
}
if ( flag_accumulation ) {
accumulate_cpu_stat( &accum_cpu_stat, &cpu);
} else {
printf("cpu%llu ",b);
show_cpu_rate(&last_each_cpu_stat[b], &cpu);
last_each_cpu_stat[b] = cpu;
}
}
fclose(fp);
if ( flag_accumulation ) {
show_cpu_rate(&last_cpu_stat, &accum_cpu_stat);
last_cpu_stat = accum_cpu_stat;
accum_cpu_stat = INITIAL_CPU_STAT;
}
fflush(stdout);
nanosleep(&nanosleep_ts, NULL);
if (flag_period) {
loop_count++;
if (loop_count >= max_loop_count)
break;
}
}
}
void monitor(void)
{
FILE *fp;
struct cpu_stat cpu;
int n;
unsigned int loop_count = 0;
unsigned int max_loop_count = period_sec * (unsigned int)(1.0/delay_sec);
for(;;)
{
fp = fopen("/proc/stat", "r" );
if ( NULL == fp ) {
perror("fopen");
break;
}
n = fscanf(fp, "cpu %ld %ld %ld %ld %ld %ld %ld",
&cpu.user, &cpu.nice, &cpu.sys, &cpu.idle, &cpu.iowait, &cpu.irq, &cpu.softirq );
if ( EOF == n )
{
perror("fscanf");
break;
}
if ( n != 7 )
{
fprintf(stderr, "parse error (%d)\n",n);
break;
}
fclose(fp);
show_cpu_rate(&last_cpu_stat, &cpu);
last_cpu_stat = cpu;
fflush(stdout);
nanosleep(&nanosleep_ts, NULL);
if (flag_period) {
loop_count++;
if (loop_count >= max_loop_count)
break;
}
}
}
int main(int argc, char * const argv[])
{
parse_opt(argc, argv);
if( cpumask ) printf("cpumask = %llx\n", cpumask);
printf("delay = %ld.%09ld sec\n", (long)nanosleep_ts.tv_sec, nanosleep_ts.tv_nsec);
show_header();
if( cpumask ) {
monitor_each_cpu();
} else {
monitor();
}
return 0;
}
|
the_stack_data/431980.c | #include <stdio.h>
struct tym
{
int hour;
int min;
int seco;
};
typedef struct tym time;
int main()
{
time a, b, c;
printf("Enter time in hour min sec.\n");
scanf("%d%d%d%d%d%d", &a.hour, &a.min, &a.seco, &b.hour, &b.min, &b.seco);
c.seco = (b.seco + 60 * b.min + 3600 * b.hour) - (a.seco + a.min * 60 + a.hour * 3600);
c.hour = c.seco / 3600;
c.seco %= 3600;
c.min = c.seco / 60;
c.seco %= 60;
printf("%d : %d : %d", c.hour, c.min, c.seco);
return 0;
} |
the_stack_data/62636955.c | //test array and struct
#include <stdio.h>
#define WriteLine() printf("\n");
#define WriteLong(x) printf(" %lld", (long)x);
#define ReadLong(a) if (fscanf(stdin, "%lld", &a) != 1) a = 0;
#define long long long
struct A {
long x, y;
struct B {
long q, r, s;
} z;
} a, b[3];
void main()
{
long i;
struct A c;
struct B qq;
c.z.r = 987654321;
a.x = 1;
a.y = 2;
c.x = 9;
c.y = 0;
b[0].x = 3;
b[0].y = 4;
b[a.x].x = 5;
b[a.x].y = 6;
b[b[a.x-1].x-1].x = 7;
b[b[a.y-2].x-1].y = 8;
WriteLong(a.x);
WriteLong(a.y);
WriteLine();
i = 0;
while (i < 3) {
WriteLong(b[i].x);
WriteLong(b[i].y);
WriteLine();
i = i + 1;
}
WriteLong(c.x);
WriteLong(c.y);
WriteLine();
WriteLong(c.z.r);
WriteLine();
}
/*
expected output:
1 2
3 4
5 6
7 8
9 0
987654321
*/
|
the_stack_data/76968.c | /*
* Copyright (c) 2011, 2012, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
*/
#include <grp.h>
#include <assert.h>
#include <string.h>
struct group *getgrgid(gid_t gid)
{
assert(!"NYI");
return NULL;
}
struct group *getgrnam(const char *name)
{
assert(!"NYI");
return NULL;
}
struct group *getgrent(void)
{
assert(!"NYI");
return NULL;
}
void setgrent(void)
{
assert(!"NYI");
return;
}
void endgrent(void)
{
assert(!"NYI");
return;
}
|
the_stack_data/7949319.c | extern void abort(void);
void reach_error(){}
extern unsigned int __VERIFIER_nondet_uint(void);
void __VERIFIER_assert(int cond) {
if (!(cond)) {
ERROR: {reach_error();abort();}
}
return;
}
int main(void) {
unsigned int x = __VERIFIER_nondet_uint();
unsigned int y = x + 1;
while (x < 1024) {
x++;
y++;
}
__VERIFIER_assert(x == y);
}
|
the_stack_data/23575066.c | /*
* Copyright (c) 2012-2017 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef OPENVX_USE_PIPELINING
#include <VX/vx.h>
#include <VX/vx_khr_pipelining.h>
#include <VX/vx_compatibility.h>
#include "vx_internal.h"
VX_API_ENTRY vx_status VX_API_CALL vxEnableEvents(vx_context context)
{
return VX_ERROR_NOT_IMPLEMENTED;
}
VX_API_ENTRY vx_status VX_API_CALL vxDisableEvents(vx_context context)
{
return VX_ERROR_NOT_IMPLEMENTED;
}
VX_API_ENTRY vx_status VX_API_CALL vxSendUserEvent(vx_context context, vx_uint32 id, void *parameter)
{
return VX_ERROR_NOT_IMPLEMENTED;
}
VX_API_ENTRY vx_status VX_API_CALL vxWaitEvent(
vx_context context, vx_event_t *event,
vx_bool do_not_block)
{
return VX_ERROR_NOT_IMPLEMENTED;
}
VX_API_ENTRY vx_status VX_API_CALL vxRegisterEvent(vx_reference ref,
enum vx_event_type_e type, vx_uint32 param, vx_uint32 app_value)
{
return VX_ERROR_NOT_IMPLEMENTED;
}
#endif
|
the_stack_data/390541.c | #include <stdio.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
static int num_dirs, num_regular;
bool is_dir(const char* path) {
struct stat buf;
stat(path, &buf);
return S_ISDIR(buf.st_mode);
/*
* Use the stat() function (try "man 2 stat") to determine if the file
* referenced by path is a directory or not. Call stat, and then use
* S_ISDIR to see if the file is a directory. Make sure you check the
* return value from stat in case there is a problem, e.g., maybe the
* the file doesn't actually exist.
*/
}
/*
* I needed this because the multiple recursion means there's no way to
* order them so that the definitions all precede the cause.
*/
void process_path(const char*);
void process_directory(const char* path) {
num_dirs++;
DIR* dir = opendir(path);
chdir(path);
//https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.bpxbd00/rtread.htm used as an example
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (!(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)) {
process_path(entry->d_name);
}
}
chdir("..");
closedir(dir);
/*
* Update the number of directories seen, use opendir() to open the
* directory, and then use readdir() to loop through the entries
* and process them. You have to be careful not to process the
* "." and ".." directory entries, or you'll end up spinning in
* (infinite) loops. Also make sure you closedir() when you're done.
*
* You'll also want to use chdir() to move into this new directory,
* with a matching call to chdir() to move back out of it when you're
* done.
*/
}
void process_file(const char* path) {
/*
* Update the number of regular files.
*/
num_regular++;
}
void process_path(const char* path) {
if (is_dir(path)) {
process_directory(path);
} else {
process_file(path);
}
}
int main (int argc, char *argv[]) {
// Ensure an argument was provided.
if (argc != 2) {
printf ("Usage: %s <path>\n", argv[0]);
printf (" where <path> is the file or root of the tree you want to summarize.\n");
return 1;
}
num_dirs = 0;
num_regular = 0;
process_path(argv[1]);
printf("There were %d directories.\n", num_dirs);
printf("There were %d regular files.\n", num_regular);
return 0;
}
|
the_stack_data/43886454.c | #include <malloc.h>
int
main()
{
malloc_trim(0);
}
|
the_stack_data/115840.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, Z. Vasicek, L. Sekanina, H. Jiang and J. Han, "Scalable Construction of Approximate Multipliers With Formally Guaranteed Worst Case Error" in IEEE Transactions on Very Large Scale Integration (VLSI) Systems, vol. 26, no. 11, pp. 2572-2576, Nov. 2018. doi: 10.1109/TVLSI.2018.2856362
* This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and wce parameters
***/
// MAE% = 0.00000086 %
// MAE = 37
// WCE% = 0.0000027 %
// WCE = 115
// WCRE% = 8300.00 %
// EP% = 97.72 %
// MRE% = 0.00013 %
// MSE = 2008
// PDK45_PWR = 2.106 mW
// PDK45_AREA = 2992.3 um2
// PDK45_DELAY = 3.09 ns
#include <stdint.h>
#include <stdlib.h>
uint16_t mul8_364(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n0 = (a >> 0) & 0x1;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n16 = (b >> 0) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n32;
uint8_t n48;
uint8_t n64;
uint8_t n82;
uint8_t n98;
uint8_t n114;
uint8_t n132;
uint8_t n149;
uint8_t n164;
uint8_t n167;
uint8_t n182;
uint8_t n198;
uint8_t n214;
uint8_t n232;
uint8_t n248;
uint8_t n264;
uint8_t n282;
uint8_t n298;
uint8_t n299;
uint8_t n314;
uint8_t n315;
uint8_t n332;
uint8_t n333;
uint8_t n348;
uint8_t n349;
uint8_t n364;
uint8_t n365;
uint8_t n382;
uint8_t n383;
uint8_t n398;
uint8_t n399;
uint8_t n414;
uint8_t n432;
uint8_t n448;
uint8_t n464;
uint8_t n482;
uint8_t n498;
uint8_t n514;
uint8_t n532;
uint8_t n548;
uint8_t n549;
uint8_t n564;
uint8_t n565;
uint8_t n582;
uint8_t n583;
uint8_t n598;
uint8_t n599;
uint8_t n614;
uint8_t n615;
uint8_t n632;
uint8_t n633;
uint8_t n648;
uint8_t n649;
uint8_t n664;
uint8_t n682;
uint8_t n698;
uint8_t n714;
uint8_t n732;
uint8_t n748;
uint8_t n764;
uint8_t n782;
uint8_t n798;
uint8_t n799;
uint8_t n814;
uint8_t n815;
uint8_t n832;
uint8_t n833;
uint8_t n848;
uint8_t n849;
uint8_t n864;
uint8_t n865;
uint8_t n882;
uint8_t n883;
uint8_t n898;
uint8_t n899;
uint8_t n914;
uint8_t n932;
uint8_t n948;
uint8_t n964;
uint8_t n982;
uint8_t n998;
uint8_t n1014;
uint8_t n1032;
uint8_t n1048;
uint8_t n1049;
uint8_t n1064;
uint8_t n1065;
uint8_t n1082;
uint8_t n1083;
uint8_t n1098;
uint8_t n1099;
uint8_t n1114;
uint8_t n1115;
uint8_t n1132;
uint8_t n1133;
uint8_t n1148;
uint8_t n1149;
uint8_t n1164;
uint8_t n1182;
uint8_t n1198;
uint8_t n1214;
uint8_t n1232;
uint8_t n1248;
uint8_t n1264;
uint8_t n1282;
uint8_t n1298;
uint8_t n1299;
uint8_t n1314;
uint8_t n1315;
uint8_t n1332;
uint8_t n1333;
uint8_t n1348;
uint8_t n1349;
uint8_t n1364;
uint8_t n1365;
uint8_t n1382;
uint8_t n1383;
uint8_t n1398;
uint8_t n1399;
uint8_t n1414;
uint8_t n1432;
uint8_t n1448;
uint8_t n1464;
uint8_t n1482;
uint8_t n1498;
uint8_t n1514;
uint8_t n1532;
uint8_t n1548;
uint8_t n1549;
uint8_t n1564;
uint8_t n1565;
uint8_t n1582;
uint8_t n1583;
uint8_t n1598;
uint8_t n1599;
uint8_t n1614;
uint8_t n1615;
uint8_t n1632;
uint8_t n1633;
uint8_t n1648;
uint8_t n1649;
uint8_t n1664;
uint8_t n1682;
uint8_t n1698;
uint8_t n1714;
uint8_t n1732;
uint8_t n1748;
uint8_t n1764;
uint8_t n1782;
uint8_t n1798;
uint8_t n1799;
uint8_t n1814;
uint8_t n1815;
uint8_t n1832;
uint8_t n1833;
uint8_t n1848;
uint8_t n1849;
uint8_t n1864;
uint8_t n1865;
uint8_t n1882;
uint8_t n1883;
uint8_t n1898;
uint8_t n1899;
uint8_t n1914;
uint8_t n1915;
uint8_t n1932;
uint8_t n1933;
uint8_t n1948;
uint8_t n1949;
uint8_t n1964;
uint8_t n1965;
uint8_t n1982;
uint8_t n1983;
uint8_t n1998;
uint8_t n1999;
uint8_t n2014;
uint8_t n2015;
n32 = n0 & n16;
n48 = n2 & n16;
n64 = n4 & n16;
n82 = n6 & n16;
n98 = n8 & n16;
n114 = n10 & n16;
n132 = n12 & n16;
n149 = n14 & n16;
n164 = n0 & n18;
n167 = n149;
n182 = n2 & n18;
n198 = n4 & n18;
n214 = n6 & n18;
n232 = n8 & n18;
n248 = n10 & n18;
n264 = n12 & n18;
n282 = n14 & n18;
n298 = n48 ^ n164;
n299 = n48 & n164;
n314 = n64 ^ n182;
n315 = n64 & n182;
n332 = n82 ^ n198;
n333 = n82 & n198;
n348 = n98 ^ n214;
n349 = n98 & n214;
n364 = n114 ^ n232;
n365 = n114 & n232;
n382 = n132 ^ n248;
n383 = n132 & n248;
n398 = n167 ^ n264;
n399 = n167 & n264;
n414 = n0 & n20;
n432 = n2 & n20;
n448 = n4 & n20;
n464 = n6 & n20;
n482 = n8 & n20;
n498 = n10 & n20;
n514 = n12 & n20;
n532 = n14 & n20;
n548 = (n314 ^ n414) ^ n299;
n549 = (n314 & n414) | (n414 & n299) | (n314 & n299);
n564 = (n332 ^ n432) ^ n315;
n565 = (n332 & n432) | (n432 & n315) | (n332 & n315);
n582 = (n348 ^ n448) ^ n333;
n583 = (n348 & n448) | (n448 & n333) | (n348 & n333);
n598 = (n364 ^ n464) ^ n349;
n599 = (n364 & n464) | (n464 & n349) | (n364 & n349);
n614 = (n382 ^ n482) ^ n365;
n615 = (n382 & n482) | (n482 & n365) | (n382 & n365);
n632 = (n398 ^ n498) ^ n383;
n633 = (n398 & n498) | (n498 & n383) | (n398 & n383);
n648 = (n282 ^ n514) ^ n399;
n649 = (n282 & n514) | (n514 & n399) | (n282 & n399);
n664 = n0 & n22;
n682 = n2 & n22;
n698 = n4 & n22;
n714 = n6 & n22;
n732 = n8 & n22;
n748 = n10 & n22;
n764 = n12 & n22;
n782 = n14 & n22;
n798 = (n564 ^ n664) ^ n549;
n799 = (n564 & n664) | (n664 & n549) | (n564 & n549);
n814 = (n582 ^ n682) ^ n565;
n815 = (n582 & n682) | (n682 & n565) | (n582 & n565);
n832 = (n598 ^ n698) ^ n583;
n833 = (n598 & n698) | (n698 & n583) | (n598 & n583);
n848 = (n614 ^ n714) ^ n599;
n849 = (n614 & n714) | (n714 & n599) | (n614 & n599);
n864 = (n632 ^ n732) ^ n615;
n865 = (n632 & n732) | (n732 & n615) | (n632 & n615);
n882 = (n648 ^ n748) ^ n633;
n883 = (n648 & n748) | (n748 & n633) | (n648 & n633);
n898 = (n532 ^ n764) ^ n649;
n899 = (n532 & n764) | (n764 & n649) | (n532 & n649);
n914 = n0 & n24;
n932 = n2 & n24;
n948 = n4 & n24;
n964 = n6 & n24;
n982 = n8 & n24;
n998 = n10 & n24;
n1014 = n12 & n24;
n1032 = n14 & n24;
n1048 = (n814 ^ n914) ^ n799;
n1049 = (n814 & n914) | (n914 & n799) | (n814 & n799);
n1064 = (n832 ^ n932) ^ n815;
n1065 = (n832 & n932) | (n932 & n815) | (n832 & n815);
n1082 = (n848 ^ n948) ^ n833;
n1083 = (n848 & n948) | (n948 & n833) | (n848 & n833);
n1098 = (n864 ^ n964) ^ n849;
n1099 = (n864 & n964) | (n964 & n849) | (n864 & n849);
n1114 = (n882 ^ n982) ^ n865;
n1115 = (n882 & n982) | (n982 & n865) | (n882 & n865);
n1132 = (n898 ^ n998) ^ n883;
n1133 = (n898 & n998) | (n998 & n883) | (n898 & n883);
n1148 = (n782 ^ n1014) ^ n899;
n1149 = (n782 & n1014) | (n1014 & n899) | (n782 & n899);
n1164 = n0 & n26;
n1182 = n2 & n26;
n1198 = n4 & n26;
n1214 = n6 & n26;
n1232 = n8 & n26;
n1248 = n10 & n26;
n1264 = n12 & n26;
n1282 = n14 & n26;
n1298 = (n1064 ^ n1164) ^ n1049;
n1299 = (n1064 & n1164) | (n1164 & n1049) | (n1064 & n1049);
n1314 = (n1082 ^ n1182) ^ n1065;
n1315 = (n1082 & n1182) | (n1182 & n1065) | (n1082 & n1065);
n1332 = (n1098 ^ n1198) ^ n1083;
n1333 = (n1098 & n1198) | (n1198 & n1083) | (n1098 & n1083);
n1348 = (n1114 ^ n1214) ^ n1099;
n1349 = (n1114 & n1214) | (n1214 & n1099) | (n1114 & n1099);
n1364 = (n1132 ^ n1232) ^ n1115;
n1365 = (n1132 & n1232) | (n1232 & n1115) | (n1132 & n1115);
n1382 = (n1148 ^ n1248) ^ n1133;
n1383 = (n1148 & n1248) | (n1248 & n1133) | (n1148 & n1133);
n1398 = (n1032 ^ n1264) ^ n1149;
n1399 = (n1032 & n1264) | (n1264 & n1149) | (n1032 & n1149);
n1414 = n0 & n28;
n1432 = n2 & n28;
n1448 = n4 & n28;
n1464 = n6 & n28;
n1482 = n8 & n28;
n1498 = n10 & n28;
n1514 = n12 & n28;
n1532 = n14 & n28;
n1548 = (n1314 ^ n1414) ^ n1299;
n1549 = (n1314 & n1414) | (n1414 & n1299) | (n1314 & n1299);
n1564 = (n1332 ^ n1432) ^ n1315;
n1565 = (n1332 & n1432) | (n1432 & n1315) | (n1332 & n1315);
n1582 = (n1348 ^ n1448) ^ n1333;
n1583 = (n1348 & n1448) | (n1448 & n1333) | (n1348 & n1333);
n1598 = (n1364 ^ n1464) ^ n1349;
n1599 = (n1364 & n1464) | (n1464 & n1349) | (n1364 & n1349);
n1614 = (n1382 ^ n1482) ^ n1365;
n1615 = (n1382 & n1482) | (n1482 & n1365) | (n1382 & n1365);
n1632 = (n1398 ^ n1498) ^ n1383;
n1633 = (n1398 & n1498) | (n1498 & n1383) | (n1398 & n1383);
n1648 = (n1282 ^ n1514) ^ n1399;
n1649 = (n1282 & n1514) | (n1514 & n1399) | (n1282 & n1399);
n1664 = n0 & n30;
n1682 = n2 & n30;
n1698 = n4 & n30;
n1714 = n6 & n30;
n1732 = n8 & n30;
n1748 = n10 & n30;
n1764 = n12 & n30;
n1782 = n14 & n30;
n1798 = (n1564 ^ n1664) ^ n1549;
n1799 = (n1564 & n1664) | (n1664 & n1549) | (n1564 & n1549);
n1814 = (n1582 ^ n1682) ^ n1565;
n1815 = (n1582 & n1682) | (n1682 & n1565) | (n1582 & n1565);
n1832 = (n1598 ^ n1698) ^ n1583;
n1833 = (n1598 & n1698) | (n1698 & n1583) | (n1598 & n1583);
n1848 = (n1614 ^ n1714) ^ n1599;
n1849 = (n1614 & n1714) | (n1714 & n1599) | (n1614 & n1599);
n1864 = (n1632 ^ n1732) ^ n1615;
n1865 = (n1632 & n1732) | (n1732 & n1615) | (n1632 & n1615);
n1882 = (n1648 ^ n1748) ^ n1633;
n1883 = (n1648 & n1748) | (n1748 & n1633) | (n1648 & n1633);
n1898 = (n1532 ^ n1764) ^ n1649;
n1899 = (n1532 & n1764) | (n1764 & n1649) | (n1532 & n1649);
n1914 = n1814 ^ n1799;
n1915 = n1814 & n1799;
n1932 = (n1832 ^ n1815) ^ n1915;
n1933 = (n1832 & n1815) | (n1815 & n1915) | (n1832 & n1915);
n1948 = (n1848 ^ n1833) ^ n1933;
n1949 = (n1848 & n1833) | (n1833 & n1933) | (n1848 & n1933);
n1964 = (n1864 ^ n1849) ^ n1949;
n1965 = (n1864 & n1849) | (n1849 & n1949) | (n1864 & n1949);
n1982 = (n1882 ^ n1865) ^ n1965;
n1983 = (n1882 & n1865) | (n1865 & n1965) | (n1882 & n1965);
n1998 = (n1898 ^ n1883) ^ n1983;
n1999 = (n1898 & n1883) | (n1883 & n1983) | (n1898 & n1983);
n2014 = (n1782 ^ n1899) ^ n1999;
n2015 = (n1782 & n1899) | (n1899 & n1999) | (n1782 & n1999);
c |= (n32 & 0x1) << 0;
c |= (n298 & 0x1) << 1;
c |= (n548 & 0x1) << 2;
c |= (n798 & 0x1) << 3;
c |= (n1048 & 0x1) << 4;
c |= (n1298 & 0x1) << 5;
c |= (n1548 & 0x1) << 6;
c |= (n1798 & 0x1) << 7;
c |= (n1914 & 0x1) << 8;
c |= (n1932 & 0x1) << 9;
c |= (n1948 & 0x1) << 10;
c |= (n1964 & 0x1) << 11;
c |= (n1982 & 0x1) << 12;
c |= (n1998 & 0x1) << 13;
c |= (n2014 & 0x1) << 14;
c |= (n2015 & 0x1) << 15;
return c;
}
uint64_t mult8_cgp14_wc115_5_csamrca(const uint64_t B,const uint64_t A)
{
uint64_t O, dout_22, dout_23, dout_28, dout_29, dout_30, dout_31, dout_40, dout_41, dout_42, dout_43, dout_44, dout_45, dout_49, dout_50, dout_51, dout_52, dout_53, dout_70, dout_74, dout_75, dout_76, dout_77, dout_78, dout_79, dout_80, dout_81, dout_82, dout_83, dout_84, dout_85, dout_87, dout_88, dout_92, dout_93, dout_94, dout_95, dout_96, dout_108, dout_112, dout_113, dout_114, dout_115, dout_116, dout_117, dout_118, dout_119, dout_120, dout_121, dout_122, dout_123, dout_124, dout_125, dout_126, dout_127, dout_128, dout_129, dout_130, dout_131, dout_134, dout_135, dout_136, dout_137, dout_138, dout_139, dout_150, dout_151, dout_152, dout_153, dout_154, dout_155, dout_156, dout_157, dout_158, dout_159, dout_160, dout_161, dout_162, dout_163, dout_164, dout_165, dout_166, dout_167, dout_168, dout_169, dout_170, dout_171, dout_172, dout_173, dout_174, dout_176, dout_177, dout_178, dout_179, dout_180, dout_181, dout_182, dout_189, dout_190, dout_192, dout_193, dout_194, dout_195, dout_196, dout_197, dout_198, dout_199, dout_200, dout_201, dout_202, dout_203, dout_204, dout_205, dout_206, dout_207, dout_208, dout_209, dout_210, dout_211, dout_212, dout_213, dout_214, dout_215, dout_216, dout_217, dout_218, dout_219, dout_220, dout_221, dout_222, dout_223, dout_224, dout_225, dout_229, dout_231, dout_232, dout_233, dout_234, dout_235, dout_236, dout_237, dout_238, dout_239, dout_240, dout_241, dout_242, dout_243, dout_244, dout_245, dout_246, dout_247, dout_248, dout_249, dout_250, dout_251, dout_252, dout_253, dout_254, dout_255, dout_256, dout_257, dout_258, dout_259, dout_260, dout_261, dout_262, dout_263, dout_264, dout_265, dout_266, dout_267, dout_268, dout_269, dout_270, dout_271, dout_272, dout_273, dout_274, dout_275, dout_276, dout_277, dout_278, dout_279, dout_280, dout_281, dout_282, dout_283, dout_284, dout_285, dout_286, dout_287, dout_288, dout_289, dout_290, dout_291, dout_292, dout_293, dout_294, dout_295, dout_296, dout_297, dout_298, dout_299, dout_300, dout_301, dout_302, dout_303, dout_304, dout_305, dout_306, dout_307, dout_308, dout_309, dout_310, dout_311, dout_312, dout_313, dout_314, dout_315, dout_316, dout_317, dout_318, dout_319, dout_320, dout_321, dout_322, dout_323, dout_324, dout_325, dout_326, dout_327, dout_328, dout_329, dout_330, dout_331, dout_332, dout_333, dout_334, dout_335; int avg=0;
dout_22=((B >> 6)&1)&((A >> 0)&1);
dout_23=((B >> 7)&1)&((A >> 0)&1);
dout_28=((B >> 4)&1)&((A >> 1)&1);
dout_29=((B >> 5)&1)&((A >> 1)&1);
dout_30=((B >> 6)&1)&((A >> 1)&1);
dout_31=((B >> 7)&1)&((A >> 1)&1);
dout_40=((A >> 0)&1)|((A >> 1)&1);
dout_41=((A >> 0)&1)&dout_28;
dout_42=dout_22^dout_29;
dout_43=dout_22&dout_29;
dout_44=dout_23^dout_30;
dout_45=dout_23&dout_30;
dout_49=((B >> 3)&1)&((A >> 2)&1);
dout_50=((B >> 4)&1)&((A >> 2)&1);
dout_51=((B >> 5)&1)&((A >> 2)&1);
dout_52=((B >> 6)&1)&((A >> 2)&1);
dout_53=((B >> 7)&1)&((A >> 2)&1);
dout_70=dout_40&dout_49;
dout_74=dout_42^dout_50;
dout_75=dout_42&dout_50;
dout_76=dout_74&dout_41;
dout_77=dout_74^dout_41;
dout_78=dout_75|dout_76;
dout_79=dout_44^dout_51;
dout_80=dout_44&dout_51;
dout_81=dout_79&dout_43;
dout_82=dout_79^dout_43;
dout_83=dout_80|dout_81;
dout_84=dout_31^dout_52;
dout_85=dout_31&dout_52;
dout_87=dout_84^dout_45;
dout_88=dout_85|dout_45;
dout_92=((B >> 3)&1)&((A >> 3)&1);
dout_93=((B >> 4)&1)&((A >> 3)&1);
dout_94=((B >> 5)&1)&((A >> 3)&1);
dout_95=((B >> 6)&1)&((A >> 3)&1);
dout_96=((B >> 7)&1)&((A >> 3)&1);
dout_108=((A >> 3)&1)&((B >> 2)&1);
dout_112=dout_77^dout_92;
dout_113=dout_77&dout_92;
dout_114=dout_112&dout_70;
dout_115=dout_112^dout_70;
dout_116=dout_113|dout_114;
dout_117=dout_82^dout_93;
dout_118=dout_82&dout_93;
dout_119=dout_117&dout_78;
dout_120=dout_117^dout_78;
dout_121=dout_118|dout_119;
dout_122=dout_87^dout_94;
dout_123=dout_87&dout_94;
dout_124=dout_122&dout_83;
dout_125=dout_122^dout_83;
dout_126=dout_123|dout_124;
dout_127=dout_53^dout_95;
dout_128=dout_53&dout_95;
dout_129=dout_127&dout_88;
dout_130=dout_127^dout_88;
dout_131=dout_128|dout_129;
dout_134=((B >> 2)&1)&((A >> 4)&1);
dout_135=((B >> 3)&1)&((A >> 4)&1);
dout_136=((B >> 4)&1)&((A >> 4)&1);
dout_137=((B >> 5)&1)&((A >> 4)&1);
dout_138=((B >> 6)&1)&((A >> 4)&1);
dout_139=((B >> 7)&1)&((A >> 4)&1);
dout_150=dout_115|dout_134;
dout_151=dout_115&dout_134;
dout_152=dout_150&dout_108;
dout_153=dout_150^dout_108;
dout_154=dout_151|dout_152;
dout_155=dout_120^dout_135;
dout_156=dout_120&dout_135;
dout_157=dout_155&dout_116;
dout_158=dout_155^dout_116;
dout_159=dout_156|dout_157;
dout_160=dout_125^dout_136;
dout_161=dout_125&dout_136;
dout_162=dout_160&dout_121;
dout_163=dout_160^dout_121;
dout_164=dout_161|dout_162;
dout_165=dout_130^dout_137;
dout_166=dout_130&dout_137;
dout_167=dout_165&dout_126;
dout_168=dout_165^dout_126;
dout_169=dout_166|dout_167;
dout_170=dout_96^dout_138;
dout_171=dout_96&dout_138;
dout_172=dout_170&dout_131;
dout_173=dout_170^dout_131;
dout_174=dout_171|dout_172;
dout_176=((B >> 1)&1)&((A >> 5)&1);
dout_177=((B >> 2)&1)&((A >> 5)&1);
dout_178=((B >> 3)&1)&((A >> 5)&1);
dout_179=((B >> 4)&1)&((A >> 5)&1);
dout_180=((B >> 5)&1)&((A >> 5)&1);
dout_181=((B >> 6)&1)&((A >> 5)&1);
dout_182=((B >> 7)&1)&((A >> 5)&1);
dout_189=dout_153&dout_176;
dout_190=dout_176&((A >> 4)&1);
dout_192=dout_189|dout_190;
dout_193=dout_158^dout_177;
dout_194=dout_158&dout_177;
dout_195=dout_193&dout_154;
dout_196=dout_193^dout_154;
dout_197=dout_194|dout_195;
dout_198=dout_163^dout_178;
dout_199=dout_163&dout_178;
dout_200=dout_198&dout_159;
dout_201=dout_198^dout_159;
dout_202=dout_199|dout_200;
dout_203=dout_168^dout_179;
dout_204=dout_168&dout_179;
dout_205=dout_203&dout_164;
dout_206=dout_203^dout_164;
dout_207=dout_204|dout_205;
dout_208=dout_173^dout_180;
dout_209=dout_173&dout_180;
dout_210=dout_208&dout_169;
dout_211=dout_208^dout_169;
dout_212=dout_209|dout_210;
dout_213=dout_139^dout_181;
dout_214=dout_139&dout_181;
dout_215=dout_213&dout_174;
dout_216=dout_213^dout_174;
dout_217=dout_214|dout_215;
dout_218=((B >> 0)&1)&((A >> 6)&1);
dout_219=((B >> 1)&1)&((A >> 6)&1);
dout_220=((B >> 2)&1)&((A >> 6)&1);
dout_221=((B >> 3)&1)&((A >> 6)&1);
dout_222=((B >> 4)&1)&((A >> 6)&1);
dout_223=((B >> 5)&1)&((A >> 6)&1);
dout_224=((B >> 6)&1)&((A >> 6)&1);
dout_225=((B >> 7)&1)&((A >> 6)&1);
dout_229=dout_218^0xFFFFFFFFFFFFFFFFU;
dout_231=dout_196^dout_219;
dout_232=dout_196&dout_219;
dout_233=dout_231&dout_192;
dout_234=dout_231^dout_192;
dout_235=dout_232|dout_233;
dout_236=dout_201^dout_220;
dout_237=dout_201&dout_220;
dout_238=dout_236&dout_197;
dout_239=dout_236^dout_197;
dout_240=dout_237|dout_238;
dout_241=dout_206^dout_221;
dout_242=dout_206&dout_221;
dout_243=dout_241&dout_202;
dout_244=dout_241^dout_202;
dout_245=dout_242|dout_243;
dout_246=dout_211^dout_222;
dout_247=dout_211&dout_222;
dout_248=dout_246&dout_207;
dout_249=dout_246^dout_207;
dout_250=dout_247|dout_248;
dout_251=dout_216^dout_223;
dout_252=dout_216&dout_223;
dout_253=dout_251&dout_212;
dout_254=dout_251^dout_212;
dout_255=dout_252|dout_253;
dout_256=dout_182^dout_224;
dout_257=dout_182&dout_224;
dout_258=dout_256&dout_217;
dout_259=dout_256^dout_217;
dout_260=dout_257|dout_258;
dout_261=((B >> 0)&1)&((A >> 7)&1);
dout_262=((B >> 1)&1)&((A >> 7)&1);
dout_263=((B >> 2)&1)&((A >> 7)&1);
dout_264=((B >> 3)&1)&((A >> 7)&1);
dout_265=((B >> 4)&1)&((A >> 7)&1);
dout_266=((B >> 5)&1)&((A >> 7)&1);
dout_267=((B >> 6)&1)&((A >> 7)&1);
dout_268=((B >> 7)&1)&((A >> 7)&1);
dout_269=dout_234^dout_261;
dout_270=dout_234&dout_261;
dout_271=dout_269&dout_218;
dout_272=dout_269^dout_218;
dout_273=dout_270|dout_271;
dout_274=dout_239^dout_262;
dout_275=dout_239&dout_262;
dout_276=dout_274&dout_235;
dout_277=dout_274^dout_235;
dout_278=dout_275|dout_276;
dout_279=dout_244^dout_263;
dout_280=dout_244&dout_263;
dout_281=dout_279&dout_240;
dout_282=dout_279^dout_240;
dout_283=dout_280|dout_281;
dout_284=dout_249^dout_264;
dout_285=dout_249&dout_264;
dout_286=dout_284&dout_245;
dout_287=dout_284^dout_245;
dout_288=dout_285|dout_286;
dout_289=dout_254^dout_265;
dout_290=dout_254&dout_265;
dout_291=dout_289&dout_250;
dout_292=dout_289^dout_250;
dout_293=dout_290|dout_291;
dout_294=dout_259^dout_266;
dout_295=dout_259&dout_266;
dout_296=dout_294&dout_255;
dout_297=dout_294^dout_255;
dout_298=dout_295|dout_296;
dout_299=dout_225^dout_267;
dout_300=dout_225&dout_267;
dout_301=dout_299&dout_260;
dout_302=dout_299^dout_260;
dout_303=dout_300|dout_301;
dout_304=dout_277^dout_273;
dout_305=dout_277&dout_273;
dout_306=dout_282^dout_278;
dout_307=dout_282&dout_278;
dout_308=dout_306&dout_305;
dout_309=dout_306^dout_305;
dout_310=dout_307|dout_308;
dout_311=dout_287^dout_283;
dout_312=dout_287&dout_283;
dout_313=dout_311&dout_310;
dout_314=dout_311^dout_310;
dout_315=dout_312|dout_313;
dout_316=dout_292^dout_288;
dout_317=dout_292&dout_288;
dout_318=dout_316&dout_315;
dout_319=dout_316^dout_315;
dout_320=dout_317|dout_318;
dout_321=dout_297^dout_293;
dout_322=dout_297&dout_293;
dout_323=dout_321&dout_320;
dout_324=dout_321^dout_320;
dout_325=dout_322|dout_323;
dout_326=dout_302^dout_298;
dout_327=dout_302&dout_298;
dout_328=dout_326&dout_325;
dout_329=dout_326^dout_325;
dout_330=dout_327|dout_328;
dout_331=dout_268^dout_303;
dout_332=((A >> 7)&1)&dout_303;
dout_333=dout_331&dout_330;
dout_334=dout_331^dout_330;
dout_335=dout_332|dout_333;
O = 0;
O |= (dout_75&1) << 0;
O |= (dout_137&1) << 1;
O |= (((B >> 0)&1)&1) << 2;
O |= (dout_172&1) << 3;
O |= (((B >> 0)&1)&1) << 4;
O |= (0&1) << 5;
O |= (dout_229&1) << 6;
O |= (dout_272&1) << 7;
O |= (dout_304&1) << 8;
O |= (dout_309&1) << 9;
O |= (dout_314&1) << 10;
O |= (dout_319&1) << 11;
O |= (dout_324&1) << 12;
O |= (dout_329&1) << 13;
O |= (dout_334&1) << 14;
O |= (dout_335&1) << 15;
return O;
}
uint32_t mul16u_4YJ (uint16_t a, uint16_t b) {
static uint16_t * cacheLL = NULL;
static uint16_t * cacheLH = NULL;
static uint16_t * cacheHL = NULL;
static uint16_t * cacheHH = NULL;
int fillData = cacheLL == NULL || cacheLH == NULL || cacheHL == NULL || cacheHH == NULL;
if(!cacheLL) cacheLL = (uint16_t *)malloc(256 * 256 * sizeof(uint16_t));
if(!cacheLH) cacheLH = (uint16_t *)malloc(256 * 256 * sizeof(uint16_t));
if(!cacheHL) cacheHL = (uint16_t *)malloc(256 * 256 * sizeof(uint16_t));
if(!cacheHH) cacheHH = (uint16_t *)malloc(256 * 256 * sizeof(uint16_t));
if(fillData) {
for(int i = 0; i < 256; i++) {
for(int j = 0; j < 256; j++) {
cacheLL[i * 256 + j] = mult8_cgp14_wc115_5_csamrca(i, j);
cacheLH[i * 256 + j] = mul8_364(i, j);
cacheHL[i * 256 + j] = mul8_364(i, j);
cacheHH[i * 256 + j] = mul8_364(i, j);
}
}
}
uint32_t opt = 0;
opt += (uint32_t)cacheLL[(a & 0xFF ) * 256 + (b & 0xFF )];
opt += (uint32_t)cacheLH[(a & 0xFF ) * 256 + ((b >> 8) & 0xFF )] << 8;
opt += (uint32_t)cacheHL[((a >> 8) & 0xFF) * 256 + (b & 0xFF )] << 8;
opt += (uint32_t)cacheHH[((a >> 8) & 0xFF) * 256 + ((b >> 8) & 0xFF )] << 16;
return opt;
}
|
the_stack_data/734878.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_is_prime.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: juolivei <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/16 19:56:55 by juolivei #+# #+# */
/* Updated: 2019/10/16 20:03:50 by juolivei ### ########.fr */
/* */
/* ************************************************************************** */
int ft_is_prime(int nb)
{
int number;
number = 2;
if (nb <= 1)
return (0);
if (nb == 2)
return (1);
while (number <= (nb / 2))
{
if (nb % number == 0)
return (0);
number++;
}
return (1);
}
|
the_stack_data/170451710.c | /*
** Code to implement a d2q9-bgk lattice boltzmann scheme.
** 'd2' inidates a 2-dimensional grid, and
** 'q9' indicates 9 velocities per grid cell.
** 'bgk' refers to the Bhatnagar-Gross-Krook collision step.
**
** The 'speeds' in each cell are numbered as follows:
**
** 6 2 5
** \|/
** 3-0-1
** /|\
** 7 4 8
**
** A 2D grid:
**
** cols
** --- --- ---
** | D | E | F |
** rows --- --- ---
** | A | B | C |
** --- --- ---
**
** 'unwrapped' in row major order to give a 1D array:
**
** --- --- --- --- --- ---
** | A | B | C | D | E | F |
** --- --- --- --- --- ---
**
** Grid indicies are:
**
** ny
** ^ cols(jj)
** | ----- ----- -----
** | | ... | ... | etc |
** | ----- ----- -----
** rows(ii) | | 1,0 | 1,1 | 1,2 |
** | ----- ----- -----
** | | 0,0 | 0,1 | 0,2 |
** | ----- ----- -----
** ----------------------> nx
**
** Note the names of the input parameter and obstacle files
** are passed on the command line, e.g.:
**
** d2q9-bgk.exe input.params obstacles.dat
**
** Be sure to adjust the grid dimensions in the parameter file
** if you choose a different obstacle file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <omp.h>
#define NSPEEDS 9
#define FINALSTATEFILE "final_state.dat"
#define AVVELSFILE "av_vels.dat"
/* struct to hold the parameter values */
typedef struct
{
int nx; /* no. of cells in x-direction */
int ny; /* no. of cells in y-direction */
int maxIters; /* no. of iterations */
int tot_cells;
int reynolds_dim; /* dimension for Reynolds number */
double density; /* density per link */
double accel; /* density redistribution */
double omega; /* relaxation parameter */
} t_param;
/* struct to hold the 'speed' values */
typedef struct
{
double speeds[NSPEEDS];
} t_speed;
/*
** function prototypes
*/
/* load params, allocate memory, load obstacles & initialise fluid particle densities */
int initialise(const char* paramfile, const char* obstaclefile,
t_param* params, t_speed** cells_ptr, t_speed** tmp_cells_ptr,
int** obstacles_ptr, double** av_vels_ptr);
/*
** The main calculation methods.
** timestep calls, in order, the functions:
** accelerate_flow(), propagate(), rebound() & collision()
*/
double timestep(const t_param params, t_speed* cells, t_speed* tmp_cells, int* obstacles);
int accelerate_flow(const t_param params, t_speed* cells, int* obstacles);
int propagate(const t_param params, t_speed* cells, t_speed* tmp_cells);
int rebound(const t_param params, t_speed* cells, t_speed* tmp_cells, int* obstacles);
double collision(const t_param params, t_speed* cells, t_speed* tmp_cells, int* obstacles);
int write_values(const t_param params, t_speed* cells, int* obstacles, double* av_vels);
/* finalise, including freeing up allocated memory */
int finalise(const t_param* params, t_speed** cells_ptr, t_speed** tmp_cells_ptr,
int** obstacles_ptr, double** av_vels_ptr);
/* Sum all the densities in the grid.
** The total should remain constant from one timestep to the next. */
double total_density(const t_param params, t_speed* cells);
/* compute average velocity */
double av_velocity(const t_param params, t_speed* cells, int* obstacles, int ii);
/* calculate Reynolds number */
double calc_reynolds(const t_param params, t_speed* cells, int* obstacles);
/* utility functions */
void die(const char* message, const int line, const char* file);
void usage(const char* exe);
/*
** main program:
** initialise, timestep loop, finalise
*/
int main(int argc, char* argv[])
{
char* paramfile = NULL; /* name of the input parameter file */
char* obstaclefile = NULL; /* name of a the input obstacle file */
t_param params; /* struct to hold parameter values */
t_speed* cells = NULL; /* grid containing fluid densities */
t_speed* tmp_cells = NULL; /* scratch space */
int* obstacles = NULL; /* grid indicating which cells are blocked */
double* av_vels = NULL; /* a record of the av. velocity computed for each timestep */
struct timeval timstr; /* structure to hold elapsed time */
struct rusage ru; /* structure to hold CPU time--system and user */
double tic, toc; /* floating point numbers to calculate elapsed wallclock time */
double usrtim; /* floating point number to record elapsed user CPU time */
double systim; /* floating point number to record elapsed system CPU time */
double tot_u;
/* parse the command line */
if (argc != 3)
{
usage(argv[0]);
}
else
{
paramfile = argv[1];
obstaclefile = argv[2];
}
/* initialise our data structures and load values from file */
initialise(paramfile, obstaclefile, ¶ms, &cells, &tmp_cells, &obstacles, &av_vels);
/* iterate for maxIters timesteps */
gettimeofday(&timstr, NULL);
tic = timstr.tv_sec + (timstr.tv_usec / 1000000.0);
for (int tt = 0; tt < params.maxIters; tt++)
{
//prob with tot_cells
tot_u = timestep(params, cells, tmp_cells, obstacles);
av_vels[tt] = tot_u/(double)params.tot_cells;
#ifdef DEBUG
printf("==timestep: %d==\n", tt);
printf("av velocity: %.12E\n", av_vels[tt]);
printf("tot density: %.12E\n", total_density(params, cells));
#endif
}
gettimeofday(&timstr, NULL);
toc = timstr.tv_sec + (timstr.tv_usec / 1000000.0);
getrusage(RUSAGE_SELF, &ru);
timstr = ru.ru_utime;
usrtim = timstr.tv_sec + (timstr.tv_usec / 1000000.0);
timstr = ru.ru_stime;
systim = timstr.tv_sec + (timstr.tv_usec / 1000000.0);
/* write final values and free memory */
printf("==done==\n");
printf("Reynolds number:\t\t%.12E\n", calc_reynolds(params, cells, obstacles));
printf("Elapsed time:\t\t\t%.6lf (s)\n", toc - tic);
printf("Elapsed user CPU time:\t\t%.6lf (s)\n", usrtim);
printf("Elapsed system CPU time:\t%.6lf (s)\n", systim);
write_values(params, cells, obstacles, av_vels);
finalise(¶ms, &cells, &tmp_cells, &obstacles, &av_vels);
return EXIT_SUCCESS;
}
double timestep(const t_param params, t_speed* cells, t_speed* tmp_cells, int* obstacles)
{
double tot_u;
#pragma omp parallel proc_bind(master) num_threads(16)
{
accelerate_flow(params, cells, obstacles);
propagate(params, cells, tmp_cells);
rebound(params, cells, tmp_cells, obstacles);
}
tot_u = collision(params, cells, tmp_cells, obstacles);
return tot_u;
}
int accelerate_flow(const t_param params, t_speed* cells, int* obstacles)
{
/* compute weighting factors */
double w1 = params.density * params.accel / 9.0;
double w2 = params.density * params.accel / 36.0;
/* modify the 2nd row of the grid */
int ii = params.ny - 2;
#pragma omp for
for (int jj = 0; jj < params.nx; jj++)
{
/* if the cell is not occupied and
** we don't send a negative density */
if (!obstacles[ii * params.nx + jj]
&& (cells[ii * params.nx + jj].speeds[3] - w1) > 0.0
&& (cells[ii * params.nx + jj].speeds[6] - w2) > 0.0
&& (cells[ii * params.nx + jj].speeds[7] - w2) > 0.0)
{
/* increase 'east-side' densities */
cells[ii * params.nx + jj].speeds[1] += w1;
cells[ii * params.nx + jj].speeds[5] += w2;
cells[ii * params.nx + jj].speeds[8] += w2;
/* decrease 'west-side' densities */
cells[ii * params.nx + jj].speeds[3] -= w1;
cells[ii * params.nx + jj].speeds[6] -= w2;
cells[ii * params.nx + jj].speeds[7] -= w2;
}
}
return EXIT_SUCCESS;
}
int propagate(const t_param params, t_speed* cells, t_speed* tmp_cells)
{
/* loop over _all_ cells */
#pragma omp for
for (int ii = 0; ii < params.ny; ii++)
{
int y_n,y_s;
y_n = (ii + 1) % params.ny;
y_s = (ii != 0) ? (ii - 1) : (ii + params.ny - 1);
for (int jj = 0; jj < params.nx; jj++)
{
int x_e,x_w;
/* determine indices of axis-direction neighbours
** respecting periodic boundary conditions (wrap around) */
x_e = (jj + 1) % params.nx;
x_w = (jj != 0) ? (jj - 1) : (jj + params.nx - 1);
/* propagate densities to neighbouring cells, following
** appropriate directions of travel and writing into
** scratch space grid */
tmp_cells[ii * params.nx + jj].speeds[0] = cells[ii * params.nx + jj].speeds[0]; /* central cell, no movement */
tmp_cells[ii * params.nx + x_e].speeds[1] = cells[ii * params.nx + jj].speeds[1]; /* east */
tmp_cells[y_n * params.nx + jj].speeds[2] = cells[ii * params.nx + jj].speeds[2]; /* north */
tmp_cells[ii * params.nx + x_w].speeds[3] = cells[ii * params.nx + jj].speeds[3]; /* west */
tmp_cells[y_s * params.nx + jj].speeds[4] = cells[ii * params.nx + jj].speeds[4]; /* south */
tmp_cells[y_n * params.nx + x_e].speeds[5] = cells[ii * params.nx + jj].speeds[5]; /* north-east */
tmp_cells[y_n * params.nx + x_w].speeds[6] = cells[ii * params.nx + jj].speeds[6]; /* north-west */
tmp_cells[y_s * params.nx + x_w].speeds[7] = cells[ii * params.nx + jj].speeds[7]; /* south-west */
tmp_cells[y_s * params.nx + x_e].speeds[8] = cells[ii * params.nx + jj].speeds[8]; /* south-east */
}
}
return EXIT_SUCCESS;
}
int rebound(const t_param params, t_speed* cells, t_speed* tmp_cells, int* obstacles)
{
/* loop over the cells in the grid */
#pragma omp for nowait
for (int ii = 0; ii < params.ny; ii++)
{
for (int jj = 0; jj < params.nx; jj++)
{
/* if the cell contains an obstacle */
if (obstacles[ii * params.nx + jj])
{
/* called after propagate, so taking values from scratch space
** mirroring, and writing into main grid */
cells[ii * params.nx + jj].speeds[1] = tmp_cells[ii * params.nx + jj].speeds[3];
cells[ii * params.nx + jj].speeds[2] = tmp_cells[ii * params.nx + jj].speeds[4];
cells[ii * params.nx + jj].speeds[3] = tmp_cells[ii * params.nx + jj].speeds[1];
cells[ii * params.nx + jj].speeds[4] = tmp_cells[ii * params.nx + jj].speeds[2];
cells[ii * params.nx + jj].speeds[5] = tmp_cells[ii * params.nx + jj].speeds[7];
cells[ii * params.nx + jj].speeds[6] = tmp_cells[ii * params.nx + jj].speeds[8];
cells[ii * params.nx + jj].speeds[7] = tmp_cells[ii * params.nx + jj].speeds[5];
cells[ii * params.nx + jj].speeds[8] = tmp_cells[ii * params.nx + jj].speeds[6];
}
}
}
return EXIT_SUCCESS;
}
double collision(const t_param params, t_speed* cells, t_speed* tmp_cells, int* obstacles)
{
const double c_sq = 1.0 / 3.0; /* square of speed of sound*/
const double inv_c_sq = 3.0 / 1.0; /* inverse of square of speed of sound */
const double w0 = 4.0 / 9.0; /* weighting factor */
const double w1 = 1.0 / 9.0; /* weighting factor */
const double w2 = 1.0 / 36.0; /* weighting factor */
const double inv_double_c_sq = 1.0/(2.0 * c_sq); /*double of square of speed*/
const double inv_sq_c_sq = 1.0/(2.0 * c_sq * c_sq);
double temp_u = 0.0;
/* loop over the cells in the grid
** NB the collision step is called after
** the propagate step and so values of interest
** are in the scratch-space grid */
#pragma omp parallel for reduction(+:temp_u)
for (int ii = 0; ii < params.ny; ii++)
{
for (int jj = 0; jj < params.nx; jj++)
{
/* don't consider occupied cells */
if (!obstacles[ii * params.nx + jj])
{
/* compute local density total */
double local_density = 0.0;
for (int kk = 0; kk < NSPEEDS; kk++)
{
local_density += tmp_cells[ii * params.nx + jj].speeds[kk];
}
double inv_local_density = 1.0 / local_density;
/* compute x velocity component */
double u_x = (tmp_cells[ii * params.nx + jj].speeds[1]
+ tmp_cells[ii * params.nx + jj].speeds[5]
+ tmp_cells[ii * params.nx + jj].speeds[8]
- (tmp_cells[ii * params.nx + jj].speeds[3]
+ tmp_cells[ii * params.nx + jj].speeds[6]
+ tmp_cells[ii * params.nx + jj].speeds[7]))
* inv_local_density;
/* compute y velocity component */
double u_y = (tmp_cells[ii * params.nx + jj].speeds[2]
+ tmp_cells[ii * params.nx + jj].speeds[5]
+ tmp_cells[ii * params.nx + jj].speeds[6]
- (tmp_cells[ii * params.nx + jj].speeds[4]
+ tmp_cells[ii * params.nx + jj].speeds[7]
+ tmp_cells[ii * params.nx + jj].speeds[8]))
* inv_local_density;
/* velocity squared */
double u_sq = u_x * u_x + u_y * u_y;
//velocity
temp_u += sqrt(u_sq);
/* directional velocity components */
double u[NSPEEDS];
u[1] = u_x; /* east */
u[2] = u_y; /* north */
u[3] = - u_x; /* west */
u[4] = - u_y; /* south */
u[5] = u_x + u_y; /* north-east */
u[6] = - u_x + u_y; /* north-west */
u[7] = - u_x - u_y; /* south-west */
u[8] = u_x - u_y; /* south-east */
/* equilibrium densities */
double d_equ;
/* zero velocity density: weight w0 */
d_equ = w0 * local_density
* (1.0 - u_sq * inv_double_c_sq);
cells[ii * params.nx + jj].speeds[0] = tmp_cells[ii * params.nx + jj].speeds[0]
+ params.omega
* (d_equ - tmp_cells[ii * params.nx + jj].speeds[0]);
/* axis speeds: weight w1 */
for(int kk = 1; kk < 5; kk++){
d_equ = w1 * local_density * (1.0 + u[kk] * inv_c_sq
+ (u[kk] * u[kk]) * inv_sq_c_sq
- u_sq * inv_double_c_sq);
cells[ii * params.nx + jj].speeds[kk] = tmp_cells[ii * params.nx + jj].speeds[kk]
+ params.omega
* (d_equ - tmp_cells[ii * params.nx + jj].speeds[kk]);
}
/* diagonal speeds: weight w2 */
for(int kk = 5; kk < 9; kk++){
d_equ = w2 * local_density * (1.0 + u[kk] * inv_c_sq
+ (u[kk] * u[kk]) * inv_sq_c_sq
- u_sq * inv_double_c_sq);
cells[ii * params.nx + jj].speeds[kk] = tmp_cells[ii * params.nx + jj].speeds[kk]
+ params.omega
* (d_equ - tmp_cells[ii * params.nx + jj].speeds[kk]);
}
}
}
}
return temp_u;
}
double av_velocity(const t_param params, t_speed* cells, int* obstacles, int k)
{
int tot_cells = 0; /* no. of cells used in calculation */
double tot_u; /* accumulated magnitudes of velocity for each cell */
/* initialise */
tot_u = 0.0;
/* loop over all non-blocked cells */
for (int ii = 0; ii < params.ny; ii++)
{
for (int jj = 0; jj < params.nx; jj++)
{
/* ignore occupied cells */
if (!obstacles[ii * params.nx + jj])
{
/* local density total */
double local_density = 0.0;
for (int kk = 0; kk < NSPEEDS; kk++)
{
local_density += cells[ii * params.nx + jj].speeds[kk];
}
/* x-component of velocity */
double u_x = (cells[ii * params.nx + jj].speeds[1]
+ cells[ii * params.nx + jj].speeds[5]
+ cells[ii * params.nx + jj].speeds[8]
- (cells[ii * params.nx + jj].speeds[3]
+ cells[ii * params.nx + jj].speeds[6]
+ cells[ii * params.nx + jj].speeds[7]))
/ local_density;
/* compute y velocity component */
double u_y = (cells[ii * params.nx + jj].speeds[2]
+ cells[ii * params.nx + jj].speeds[5]
+ cells[ii * params.nx + jj].speeds[6]
- (cells[ii * params.nx + jj].speeds[4]
+ cells[ii * params.nx + jj].speeds[7]
+ cells[ii * params.nx + jj].speeds[8]))
/ local_density;
/* accumulate the norm of x- and y- velocity components */
tot_u += sqrt((u_x * u_x) + (u_y * u_y));
/* increase counter of inspected cells */
++tot_cells;
}
}
}
return tot_u / (double)tot_cells;
}
int initialise(const char* paramfile, const char* obstaclefile,
t_param* params, t_speed** cells_ptr, t_speed** tmp_cells_ptr,
int** obstacles_ptr, double** av_vels_ptr)
{
char message[1024]; /* message buffer */
FILE* fp; /* file pointer */
int xx, yy; /* generic array indices */
int blocked; /* indicates whether a cell is blocked by an obstacle */
int retval; /* to hold return value for checking */
/* open the parameter file */
fp = fopen(paramfile, "r");
if (fp == NULL)
{
sprintf(message, "could not open input parameter file: %s", paramfile);
die(message, __LINE__, __FILE__);
}
/* read in the parameter values */
retval = fscanf(fp, "%d\n", &(params->nx));
if (retval != 1) die("could not read param file: nx", __LINE__, __FILE__);
retval = fscanf(fp, "%d\n", &(params->ny));
if (retval != 1) die("could not read param file: ny", __LINE__, __FILE__);
retval = fscanf(fp, "%d\n", &(params->maxIters));
if (retval != 1) die("could not read param file: maxIters", __LINE__, __FILE__);
retval = fscanf(fp, "%d\n", &(params->reynolds_dim));
if (retval != 1) die("could not read param file: reynolds_dim", __LINE__, __FILE__);
retval = fscanf(fp, "%lf\n", &(params->density));
if (retval != 1) die("could not read param file: density", __LINE__, __FILE__);
retval = fscanf(fp, "%lf\n", &(params->accel));
if (retval != 1) die("could not read param file: accel", __LINE__, __FILE__);
retval = fscanf(fp, "%lf\n", &(params->omega));
if (retval != 1) die("could not read param file: omega", __LINE__, __FILE__);
/* and close up the file */
fclose(fp);
/*
** Allocate memory.
**
** Remember C is pass-by-value, so we need to
** pass pointers into the initialise function.
**
** NB we are allocating a 1D array, so that the
** memory will be contiguous. We still want to
** index this memory as if it were a (row major
** ordered) 2D array, however. We will perform
** some arithmetic using the row and column
** coordinates, inside the square brackets, when
** we want to access elements of this array.
**
** Note also that we are using a structure to
** hold an array of 'speeds'. We will allocate
** a 1D array of these structs.
*/
/* main grid */
*cells_ptr = (t_speed*)malloc(sizeof(t_speed) * (params->ny * params->nx));
if (*cells_ptr == NULL) die("cannot allocate memory for cells", __LINE__, __FILE__);
/* 'helper' grid, used as scratch space */
*tmp_cells_ptr = (t_speed*)malloc(sizeof(t_speed) * (params->ny * params->nx));
if (*tmp_cells_ptr == NULL) die("cannot allocate memory for tmp_cells", __LINE__, __FILE__);
/* the map of obstacles */
*obstacles_ptr = malloc(sizeof(int) * (params->ny * params->nx));
if (*obstacles_ptr == NULL) die("cannot allocate column memory for obstacles", __LINE__, __FILE__);
/* initialise densities */
double w0 = params->density * 4.0 / 9.0;
double w1 = params->density / 9.0;
double w2 = params->density / 36.0;
for (int ii = 0; ii < params->ny; ii++)
{
for (int jj = 0; jj < params->nx; jj++)
{
/* centre */
(*cells_ptr)[ii * params->nx + jj].speeds[0] = w0;
/* axis directions */
(*cells_ptr)[ii * params->nx + jj].speeds[1] = w1;
(*cells_ptr)[ii * params->nx + jj].speeds[2] = w1;
(*cells_ptr)[ii * params->nx + jj].speeds[3] = w1;
(*cells_ptr)[ii * params->nx + jj].speeds[4] = w1;
/* diagonals */
(*cells_ptr)[ii * params->nx + jj].speeds[5] = w2;
(*cells_ptr)[ii * params->nx + jj].speeds[6] = w2;
(*cells_ptr)[ii * params->nx + jj].speeds[7] = w2;
(*cells_ptr)[ii * params->nx + jj].speeds[8] = w2;
}
}
/* first set all cells in obstacle array to zero */
for (int ii = 0; ii < params->ny; ii++)
{
for (int jj = 0; jj < params->nx; jj++)
{
(*obstacles_ptr)[ii * params->nx + jj] = 0;
}
}
/* open the obstacle data file */
fp = fopen(obstaclefile, "r");
if (fp == NULL)
{
sprintf(message, "could not open input obstacles file: %s", obstaclefile);
die(message, __LINE__, __FILE__);
}
/* read-in the blocked cells list */
while ((retval = fscanf(fp, "%d %d %d\n", &xx, &yy, &blocked)) != EOF)
{
/* some checks */
if (retval != 3) die("expected 3 values per line in obstacle file", __LINE__, __FILE__);
if (xx < 0 || xx > params->nx - 1) die("obstacle x-coord out of range", __LINE__, __FILE__);
if (yy < 0 || yy > params->ny - 1) die("obstacle y-coord out of range", __LINE__, __FILE__);
if (blocked != 1) die("obstacle blocked value should be 1", __LINE__, __FILE__);
/* assign to array */
(*obstacles_ptr)[yy * params->nx + xx] = blocked;
//params->tot_cells--;
}
params->tot_cells = 0;
for(int ii = 0; ii < params->nx*params->ny; ii++)
if(!(*obstacles_ptr)[ii])
params->tot_cells++;
/* and close the file */
fclose(fp);
/*
** allocate space to hold a record of the avarage velocities computed
** at each timestep
*/
*av_vels_ptr = (double*)malloc(sizeof(double) * params->maxIters);
return EXIT_SUCCESS;
}
int finalise(const t_param* params, t_speed** cells_ptr, t_speed** tmp_cells_ptr,
int** obstacles_ptr, double** av_vels_ptr)
{
/*
** free up allocated memory
*/
free(*cells_ptr);
*cells_ptr = NULL;
free(*tmp_cells_ptr);
*tmp_cells_ptr = NULL;
free(*obstacles_ptr);
*obstacles_ptr = NULL;
free(*av_vels_ptr);
*av_vels_ptr = NULL;
return EXIT_SUCCESS;
}
double calc_reynolds(const t_param params, t_speed* cells, int* obstacles)
{
const double viscosity = 1.0 / 6.0 * (2.0 / params.omega - 1.0);
double av_vel = 0;
// for(int ii = 0; ii < params.ny*params.nx; ii++)
av_vel = av_velocity(params, cells, obstacles, 0);
return av_vel * params.reynolds_dim / viscosity;
}
double total_density(const t_param params, t_speed* cells)
{
double total = 0.0; /* accumulator */
for (int ii = 0; ii < params.ny; ii++)
{
for (int jj = 0; jj < params.nx; jj++)
{
for (int kk = 0; kk < NSPEEDS; kk++)
{
total += cells[ii * params.nx + jj].speeds[kk];
}
}
}
return total;
}
int write_values(const t_param params, t_speed* cells, int* obstacles, double* av_vels)
{
FILE* fp; /* file pointer */
const double c_sq = 1.0 / 3.0; /* sq. of speed of sound */
double local_density; /* per grid cell sum of densities */
double pressure; /* fluid pressure in grid cell */
double u_x; /* x-component of velocity in grid cell */
double u_y; /* y-component of velocity in grid cell */
double u; /* norm--root of summed squares--of u_x and u_y */
fp = fopen(FINALSTATEFILE, "w");
if (fp == NULL)
{
die("could not open file output file", __LINE__, __FILE__);
}
for (int ii = 0; ii < params.ny; ii++)
{
for (int jj = 0; jj < params.nx; jj++)
{
/* an occupied cell */
if (obstacles[ii * params.nx + jj])
{
u_x = u_y = u = 0.0;
pressure = params.density * c_sq;
}
/* no obstacle */
else
{
local_density = 0.0;
for (int kk = 0; kk < NSPEEDS; kk++)
{
local_density += cells[ii * params.nx + jj].speeds[kk];
}
/* compute x velocity component */
u_x = (cells[ii * params.nx + jj].speeds[1]
+ cells[ii * params.nx + jj].speeds[5]
+ cells[ii * params.nx + jj].speeds[8]
- (cells[ii * params.nx + jj].speeds[3]
+ cells[ii * params.nx + jj].speeds[6]
+ cells[ii * params.nx + jj].speeds[7]))
/ local_density;
/* compute y velocity component */
u_y = (cells[ii * params.nx + jj].speeds[2]
+ cells[ii * params.nx + jj].speeds[5]
+ cells[ii * params.nx + jj].speeds[6]
- (cells[ii * params.nx + jj].speeds[4]
+ cells[ii * params.nx + jj].speeds[7]
+ cells[ii * params.nx + jj].speeds[8]))
/ local_density;
/* compute norm of velocity */
u = sqrt((u_x * u_x) + (u_y * u_y));
/* compute pressure */
pressure = local_density * c_sq;
}
/* write to file */
fprintf(fp, "%d %d %.12E %.12E %.12E %.12E %d\n", jj, ii, u_x, u_y, u, pressure, obstacles[ii * params.nx + jj]);
}
}
fclose(fp);
fp = fopen(AVVELSFILE, "w");
if (fp == NULL)
{
die("could not open file output file", __LINE__, __FILE__);
}
for (int ii = 0; ii < params.maxIters; ii++)
{
fprintf(fp, "%d:\t%.12E\n", ii, av_vels[ii]);
}
fclose(fp);
return EXIT_SUCCESS;
}
void die(const char* message, const int line, const char* file)
{
fprintf(stderr, "Error at line %d of file %s:\n", line, file);
fprintf(stderr, "%s\n", message);
fflush(stderr);
exit(EXIT_FAILURE);
}
void usage(const char* exe)
{
fprintf(stderr, "Usage: %s <paramfile> <obstaclefile>\n", exe);
exit(EXIT_FAILURE);
}
|
the_stack_data/156393377.c | int ob_strlen(const char *str) {
int i=0;
const char *c = str;
while(*c++ != 0) {
i++;
}
return i;
}
|
the_stack_data/234025.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_utility.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpop <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/02 19:59:18 by gpop #+# #+# */
/* Updated: 2017/08/02 20:41:33 by gpop ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
int ft_max(int a, int b)
{
if (a > b)
return (a);
else
return (b);
}
char *ft_strncpy(char *dest, char *src, unsigned int n)
{
unsigned int i;
i = 0;
while (i < n && src[i] != '\0')
{
dest[i] = src[i];
i++;
}
while (i < n)
{
dest[i] = '\0';
i++;
}
return (dest);
}
int ft_min(int a, int b, int c)
{
if (a < b)
{
if (a < c)
return (a);
else
return (c);
}
else
{
if (b < c)
return (b);
else
return (c);
}
}
|
the_stack_data/144780.c | #include <stdio.h>
int main(void)
{
int itemNo, qty;
float price, total = 0.00;
printf("Enter Item\t: ");
scanf("%d", &itemNo);
while (itemNo != -99)
{
printf("Enter Quantity\t: ");
scanf("%d", &qty);
puts("");
switch (itemNo)
{
case 1:
price = 30.00 * qty;
total += price;
break;
case 2:
price = 45.00 * qty;
total += price;
break;
case 3:
price = 55.00 * qty;
total += price;
break;
default:
printf("Invalid Item number!\n");
break;
}
printf("Enter Item\t: ");
scanf("%d", &itemNo);
}
printf("Total Price to pay Rs: %.2f\n", total);
return 0;
}
|
the_stack_data/323294.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int cont,n,num,somapar,somaimpar; //>> variáveis inteiras (int) para armazenar o número N, cada número da lista de Num números,
//>> a soma dos pares e a soma dos ímpares
somapar=0;
somaimpar=0;
printf ("Digite a quantidade de números da lista: "); //>> quantidade de numeros que ira entrar na contagem
scanf("%d",&n);
for (cont=1;cont<=n;cont++)
{
printf ("Digite um número: "); //>> ler os números
scanf("%d",&num);
if (num%2==0) //>> Se o resto da divisão do número da lista por 2 = 0;
somapar=somapar+num; //>> Somapar = somapar + número da lista
else
somaimpar=somaimpar+num; //>> Senão somaimpar = somaimpar + número da lista
}
printf ("A soma dos números pares = %d\n",somapar); //>> Exibir o conteúdo das variáveis somapar e somaimpar.
printf ("A soma dos números ímpares = %d\n",somaimpar);
return 0;
}
|
the_stack_data/67324064.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2013-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <string.h>
struct s
{
int m;
};
struct ss
{
struct s a;
struct s b;
};
void
init_s (struct s *s, int m)
{
s->m = m;
}
void
init_ss (struct ss *s, int a, int b)
{
init_s (&s->a, a);
init_s (&s->b, b);
}
void
foo (int x, struct ss ss)
{
return; /* break-here */
}
int
main ()
{
struct ss ss;
init_ss (&ss, 1, 2);
foo (42, ss);
return 0;
}
|
the_stack_data/24873.c | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#if !defined(__MINGW32__)
#include <sys/wait.h>
#endif
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <assert.h>
#ifdef __EMX__
# define SHELL_CMD "sh"
# define GEN_EXPORTS "emxexp"
# define DEF2IMPLIB_CMD "emximp"
# define SHARE_SW "-Zdll -Zmtd"
# define USE_OMF 1
# define TRUNCATE_DLL_NAME
# define DYNAMIC_LIB_EXT "dll"
# define EXE_EXT ".exe"
# if USE_OMF
/* OMF is the native format under OS/2 */
# define STATIC_LIB_EXT "lib"
# define OBJECT_EXT "obj"
# define LIBRARIAN "emxomfar"
# define LIBRARIAN_OPTS "cr"
# else
/* but the alternative, a.out, can fork() which is sometimes necessary */
# define STATIC_LIB_EXT "a"
# define OBJECT_EXT "o"
# define LIBRARIAN "ar"
# define LIBRARIAN_OPTS "cr"
# endif
#endif
#if defined(__APPLE__)
# define SHELL_CMD "/bin/sh"
# define DYNAMIC_LIB_EXT "dylib"
# define MODULE_LIB_EXT "bundle"
# define STATIC_LIB_EXT "a"
# define OBJECT_EXT "o"
# define LIBRARIAN "ar"
# define LIBRARIAN_OPTS "cr"
/* man libtool(1) documents ranlib option of -c. */
# define RANLIB "ranlib"
# define PIC_FLAG "-fPIC -fno-common"
# define SHARED_OPTS "-dynamiclib"
# define MODULE_OPTS "-bundle -dynamic"
# define DYNAMIC_LINK_OPTS "-flat_namespace"
# define DYNAMIC_LINK_UNDEFINED "-undefined suppress"
# define dynamic_link_version_func darwin_dynamic_link_function
# define DYNAMIC_INSTALL_NAME "-install_name"
# define DYNAMIC_LINK_NO_INSTALL "-dylib_file"
# define HAS_REALPATH
/*-install_name /Users/jerenk/apache-2.0-cvs/lib/libapr.0.dylib -compatibility_version 1 -current_version 1.0 */
# define LD_LIBRARY_PATH "DYLD_LIBRARY_PATH"
#endif
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
# define SHELL_CMD "/bin/sh"
# define DYNAMIC_LIB_EXT "so"
# define MODULE_LIB_EXT "so"
# define STATIC_LIB_EXT "a"
# define OBJECT_EXT "o"
# define LIBRARIAN "ar"
# define LIBRARIAN_OPTS "cr"
# define RANLIB "ranlib"
# define PIC_FLAG "-fPIC"
# define RPATH "-rpath"
# define SHARED_OPTS "-shared"
# define MODULE_OPTS "-shared"
# define DYNAMIC_LINK_OPTS "-export-dynamic"
# define LINKER_FLAG_PREFIX "-Wl,"
# define ADD_MINUS_L
# define LD_RUN_PATH "LD_RUN_PATH"
# define LD_LIBRARY_PATH "LD_LIBRARY_PATH"
#endif
#if defined(sun)
# define SHELL_CMD "/bin/sh"
# define DYNAMIC_LIB_EXT "so"
# define MODULE_LIB_EXT "so"
# define STATIC_LIB_EXT "a"
# define OBJECT_EXT "o"
# define LIBRARIAN "ar"
# define LIBRARIAN_OPTS "cr"
# define RANLIB "ranlib"
# define PIC_FLAG "-KPIC"
# define RPATH "-R"
# define SHARED_OPTS "-G"
# define MODULE_OPTS "-G"
# define DYNAMIC_LINK_OPTS ""
# define LINKER_FLAG_NO_EQUALS
# define ADD_MINUS_L
# define HAS_REALPATH
# define LD_RUN_PATH "LD_RUN_PATH"
# define LD_LIBRARY_PATH "LD_LIBRARY_PATH"
#endif
#if defined(_OSD_POSIX)
# define SHELL_CMD "/usr/bin/sh"
# define DYNAMIC_LIB_EXT "so"
# define MODULE_LIB_EXT "so"
# define STATIC_LIB_EXT "a"
# define OBJECT_EXT "o"
# define LIBRARIAN "ar"
# define LIBRARIAN_OPTS "cr"
# define SHARED_OPTS "-G"
# define MODULE_OPTS "-G"
# define LINKER_FLAG_PREFIX "-Wl,"
# define NEED_SNPRINTF
#endif
#if defined(sinix) && defined(mips) && defined(__SNI_TARG_UNIX)
# define SHELL_CMD "/usr/bin/sh"
# define DYNAMIC_LIB_EXT "so"
# define MODULE_LIB_EXT "so"
# define STATIC_LIB_EXT "a"
# define OBJECT_EXT "o"
# define LIBRARIAN "ar"
# define LIBRARIAN_OPTS "cr"
# define RPATH "-Brpath"
# define SHARED_OPTS "-G"
# define MODULE_OPTS "-G"
# define DYNAMIC_LINK_OPTS "-Wl,-Blargedynsym"
# define LINKER_FLAG_PREFIX "-Wl,"
# define NEED_SNPRINTF
# define LD_RUN_PATH "LD_RUN_PATH"
# define LD_LIBRARY_PATH "LD_LIBRARY_PATH"
#endif
#if defined(__MINGW32__)
# define SHELL_CMD "sh"
# define DYNAMIC_LIB_EXT "dll"
# define MODULE_LIB_EXT "dll"
# define STATIC_LIB_EXT "a"
# define OBJECT_EXT "o"
# define LIBRARIAN "ar"
# define LIBRARIAN_OPTS "cr"
# define RANLIB "ranlib"
# define LINKER_FLAG_PREFIX "-Wl,"
# define SHARED_OPTS "-shared"
# define MODULE_OPTS "-shared"
# define MKDIR_NO_UMASK
# define EXE_EXT ".exe"
#endif
#ifndef SHELL_CMD
#error Unsupported platform: Please add defines for SHELL_CMD etc. for your platform.
#endif
#ifdef NEED_SNPRINTF
#include <stdarg.h>
#endif
#ifdef __EMX__
#include <process.h>
#endif
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
/* We want to say we are libtool 1.4 for shlibtool compatibility. */
#define VERSION "1.4"
enum tool_mode_t {
mUnknown,
mCompile,
mLink,
mInstall,
};
enum output_t {
otGeneral,
otObject,
otProgram,
otLibrary,
otStaticLibraryOnly,
otDynamicLibraryOnly,
otModule,
};
enum pic_mode_e {
pic_UNKNOWN,
pic_PREFER,
pic_AVOID,
};
enum shared_mode_e {
share_UNSET,
share_STATIC,
share_SHARED,
};
enum lib_type {
type_UNKNOWN,
type_DYNAMIC_LIB,
type_STATIC_LIB,
type_MODULE_LIB,
type_OBJECT,
};
typedef struct {
const char **vals;
int num;
} count_chars;
typedef struct {
const char *normal;
const char *install;
} library_name;
typedef struct {
count_chars *normal;
count_chars *install;
count_chars *dependencies;
} library_opts;
typedef struct {
int silent;
enum shared_mode_e shared;
int export_all;
int dry_run;
enum pic_mode_e pic_mode;
int export_dynamic;
int no_install;
} options_t;
typedef struct {
enum tool_mode_t mode;
enum output_t output;
options_t options;
char *output_name;
char *fake_output_name;
char *basename;
const char *install_path;
const char *compiler;
const char *program;
count_chars *program_opts;
count_chars *arglist;
count_chars *tmp_dirs;
count_chars *obj_files;
count_chars *dep_rpaths;
count_chars *rpaths;
library_name static_name;
library_name shared_name;
library_name module_name;
library_opts static_opts;
library_opts shared_opts;
const char *version_info;
const char *undefined_flag;
} command_t;
#ifdef RPATH
void add_rpath(count_chars *cc, const char *path);
#endif
#if defined(NEED_SNPRINTF)
/* Write at most n characters to the buffer in str, return the
* number of chars written or -1 if the buffer would have been
* overflowed.
*
* This is portable to any POSIX-compliant system has /dev/null
*/
static FILE *f=NULL;
static int vsnprintf( char *str, size_t n, const char *fmt, va_list ap )
{
int res;
if (f == NULL)
f = fopen("/dev/null","w");
if (f == NULL)
return -1;
setvbuf( f, str, _IOFBF, n );
res = vfprintf( f, fmt, ap );
if ( res > 0 && res < n ) {
res = vsprintf( str, fmt, ap );
}
return res;
}
static int snprintf( char *str, size_t n, const char *fmt, ... )
{
va_list ap;
int res;
va_start( ap, fmt );
res = vsnprintf( str, n, fmt, ap );
va_end( ap );
return res;
}
#endif
void init_count_chars(count_chars *cc)
{
cc->vals = (const char**)malloc(PATH_MAX*sizeof(char*));
cc->num = 0;
}
void clear_count_chars(count_chars *cc)
{
int i;
for (i = 0; i < cc->num; i++) {
cc->vals[i] = 0;
}
cc->num = 0;
}
void push_count_chars(count_chars *cc, const char *newval)
{
cc->vals[cc->num++] = newval;
}
void pop_count_chars(count_chars *cc)
{
cc->num--;
}
void insert_count_chars(count_chars *cc, const char *newval, int position)
{
int i;
for (i = cc->num; i > position; i--) {
cc->vals[i] = cc->vals[i-1];
}
cc->vals[position] = newval;
cc->num++;
}
void append_count_chars(count_chars *cc, count_chars *cctoadd)
{
int i;
for (i = 0; i < cctoadd->num; i++) {
if (cctoadd->vals[i]) {
push_count_chars(cc, cctoadd->vals[i]);
}
}
}
const char *flatten_count_chars(count_chars *cc, int space)
{
int i, size;
char *newval;
size = 0;
for (i = 0; i < cc->num; i++) {
if (cc->vals[i]) {
size += strlen(cc->vals[i]) + 1;
if (space) {
size++;
}
}
}
newval = (char*)malloc(size + 1);
newval[0] = 0;
for (i = 0; i < cc->num; i++) {
if (cc->vals[i]) {
strcat(newval, cc->vals[i]);
if (space) {
strcat(newval, " ");
}
}
}
return newval;
}
char *shell_esc(const char *str)
{
int in_quote = 0;
char *cmd;
unsigned char *d;
const unsigned char *s;
cmd = (char *)malloc(2 * strlen(str) + 3);
d = (unsigned char *)cmd;
s = (const unsigned char *)str;
#ifdef __MINGW32__
*d++ = '\"';
#endif
for (; *s; ++s) {
if (*s == '"') {
*d++ = '\\';
in_quote++;
}
else if (*s == '\\' || (*s == ' ' && (in_quote % 2))) {
*d++ = '\\';
}
*d++ = *s;
}
#ifdef __MINGW32__
*d++ = '\"';
#endif
*d = '\0';
return cmd;
}
int external_spawn(command_t *cmd, const char *file, const char **argv)
{
if (!cmd->options.silent) {
const char **argument = argv;
printf("Executing: ");
while (*argument) {
printf("%s ", *argument);
argument++;
}
puts("");
}
if (cmd->options.dry_run) {
return 0;
}
#if defined(__EMX__) || defined(__MINGW32__)
return spawnvp(P_WAIT, argv[0], argv);
#else
{
pid_t pid;
pid = fork();
if (pid == 0) {
return execvp(argv[0], (char**)argv);
}
else {
int statuscode;
waitpid(pid, &statuscode, 0);
if (WIFEXITED(statuscode)) {
return WEXITSTATUS(statuscode);
}
return 0;
}
}
#endif
}
int run_command(command_t *cmd_data, count_chars *cc)
{
char *command;
const char *spawn_args[4];
count_chars tmpcc;
init_count_chars(&tmpcc);
if (cmd_data->program) {
push_count_chars(&tmpcc, cmd_data->program);
}
append_count_chars(&tmpcc, cmd_data->program_opts);
append_count_chars(&tmpcc, cc);
command = shell_esc(flatten_count_chars(&tmpcc, 1));
spawn_args[0] = SHELL_CMD;
spawn_args[1] = "-c";
spawn_args[2] = command;
spawn_args[3] = NULL;
return external_spawn(cmd_data, spawn_args[0], (const char**)spawn_args);
}
/*
* print configuration
* shlibpath_var is used in configure.
*/
void print_config()
{
#ifdef LD_RUN_PATH
printf("runpath_var=%s\n", LD_RUN_PATH);
#endif
#ifdef LD_LIBRARY_PATH
printf("shlibpath_var=%s\n", LD_LIBRARY_PATH);
#endif
#ifdef SHELL_CMD
printf("SHELL=\"%s\"\n", SHELL_CMD);
#endif
}
/*
* Add a directory to the runtime library search path.
*/
void add_runtimedirlib(char *arg, command_t *cmd_data)
{
#ifdef RPATH
add_rpath(cmd_data->shared_opts.dependencies, arg);
#else
#endif
}
int parse_long_opt(char *arg, command_t *cmd_data)
{
char *equal_pos = strchr(arg, '=');
char var[50];
char value[500];
if (equal_pos) {
strncpy(var, arg, equal_pos - arg);
var[equal_pos - arg] = 0;
strcpy(value, equal_pos + 1);
} else {
strcpy(var, arg);
}
if (strcmp(var, "silent") == 0) {
cmd_data->options.silent = 1;
} else if (strcmp(var, "mode") == 0) {
if (strcmp(value, "compile") == 0) {
cmd_data->mode = mCompile;
cmd_data->output = otObject;
}
if (strcmp(value, "link") == 0) {
cmd_data->mode = mLink;
cmd_data->output = otLibrary;
}
if (strcmp(value, "install") == 0) {
cmd_data->mode = mInstall;
}
} else if (strcmp(var, "shared") == 0) {
if (cmd_data->mode == mLink) {
cmd_data->output = otDynamicLibraryOnly;
}
cmd_data->options.shared = share_SHARED;
} else if (strcmp(var, "export-all") == 0) {
cmd_data->options.export_all = 1;
} else if (strcmp(var, "dry-run") == 0) {
printf("Dry-run mode on!\n");
cmd_data->options.dry_run = 1;
} else if (strcmp(var, "version") == 0) {
printf("Version " VERSION "\n");
} else if (strcmp(var, "help") == 0) {
printf("Sorry. No help available.\n");
} else if (strcmp(var, "config") == 0) {
print_config();
} else if (strcmp(var, "tag") == 0) {
if (strcmp(value, "CC") == 0) {
/* Do nothing. */
}
if (strcmp(value, "CXX") == 0) {
/* Do nothing. */
}
} else {
return 0;
}
return 1;
}
/* Return 1 if we eat it. */
int parse_short_opt(char *arg, command_t *cmd_data)
{
if (strcmp(arg, "export-dynamic") == 0) {
cmd_data->options.export_dynamic = 1;
return 1;
}
if (strcmp(arg, "module") == 0) {
cmd_data->output = otModule;
return 1;
}
if (strcmp(arg, "shared") == 0) {
if (cmd_data->mode == mLink) {
cmd_data->output = otDynamicLibraryOnly;
}
cmd_data->options.shared = share_SHARED;
return 1;
}
if (strcmp(arg, "Zexe") == 0) {
return 1;
}
if (strcmp(arg, "avoid-version") == 0) {
return 1;
}
if (strcmp(arg, "prefer-pic") == 0) {
cmd_data->options.pic_mode = pic_PREFER;
return 1;
}
if (strcmp(arg, "prefer-non-pic") == 0) {
cmd_data->options.pic_mode = pic_AVOID;
return 1;
}
if (strcmp(arg, "static") == 0) {
cmd_data->options.shared = share_STATIC;
return 1;
}
if (cmd_data->mode == mLink) {
if (strcmp(arg, "no-install") == 0) {
cmd_data->options.no_install = 1;
return 1;
}
if (arg[0] == 'L' || arg[0] == 'l') {
/* Hack... */
arg--;
push_count_chars(cmd_data->shared_opts.dependencies, arg);
return 1;
} else if (arg[0] == 'R' && arg[1]) {
/* -Rdir Add dir to runtime library search path. */
add_runtimedirlib(&arg[1], cmd_data);
return 1;
}
}
return 0;
}
char *truncate_dll_name(char *path)
{
/* Cut DLL name down to 8 characters after removing any mod_ prefix */
char *tmppath = strdup(path);
char *newname = strrchr(tmppath, '/') + 1;
char *ext = strrchr(tmppath, '.');
int len;
if (ext == NULL)
return tmppath;
len = ext - newname;
if (strncmp(newname, "mod_", 4) == 0) {
strcpy(newname, newname + 4);
len -= 4;
}
if (len > 8) {
strcpy(newname + 8, strchr(newname, '.'));
}
return tmppath;
}
long safe_strtol(const char *nptr, const char **endptr, int base)
{
long rv;
errno = 0;
rv = strtol(nptr, (char**)endptr, 10);
if (errno == ERANGE) {
return 0;
}
return rv;
}
void safe_mkdir(const char *path)
{
mode_t old_umask;
old_umask = umask(0);
umask(old_umask);
#ifdef MKDIR_NO_UMASK
mkdir(path);
#else
mkdir(path, ~old_umask);
#endif
}
/* returns just a file's name without the path */
const char *jlibtool_basename(const char *fullpath)
{
const char *name = strrchr(fullpath, '/');
if (name == NULL) {
name = strrchr(fullpath, '\\');
}
if (name == NULL) {
name = fullpath;
} else {
name++;
}
return name;
}
/* returns just a file's name without path or extension */
const char *nameof(const char *fullpath)
{
const char *name;
const char *ext;
name = jlibtool_basename(fullpath);
ext = strrchr(name, '.');
if (ext) {
char *trimmed;
trimmed = malloc(ext - name + 1);
strncpy(trimmed, name, ext - name);
trimmed[ext-name] = 0;
return trimmed;
}
return name;
}
/* version_info is in the form of MAJOR:MINOR:PATCH */
const char *darwin_dynamic_link_function(const char *version_info)
{
char *newarg;
long major, minor, patch;
major = 0;
minor = 0;
patch = 0;
if (version_info) {
major = safe_strtol(version_info, &version_info, 10);
if (version_info) {
if (version_info[0] == ':') {
version_info++;
}
minor = safe_strtol(version_info, &version_info, 10);
if (version_info) {
if (version_info[0] == ':') {
version_info++;
}
patch = safe_strtol(version_info, &version_info, 10);
}
}
}
/* Avoid -dylib_compatibility_version must be greater than zero errors. */
if (major == 0) {
major = 1;
}
newarg = (char*)malloc(100);
snprintf(newarg, 99,
"-compatibility_version %ld -current_version %ld.%ld",
major, major, minor);
return newarg;
}
/* genlib values
* 0 - static
* 1 - dynamic
* 2 - module
*/
char *gen_library_name(const char *name, int genlib)
{
char *newarg, *newext;
newarg = (char *)malloc(strlen(name) + 11);
strcpy(newarg, ".libs/");
if (genlib == 2 && strncmp(name, "lib", 3) == 0) {
name += 3;
}
if (genlib == 2) {
strcat(newarg, jlibtool_basename(name));
}
else {
strcat(newarg, name);
}
newext = strrchr(newarg, '.') + 1;
switch (genlib) {
case 0:
strcpy(newext, STATIC_LIB_EXT);
break;
case 1:
strcpy(newext, DYNAMIC_LIB_EXT);
break;
case 2:
strcpy(newext, MODULE_LIB_EXT);
break;
}
return newarg;
}
/* genlib values
* 0 - static
* 1 - dynamic
* 2 - module
*/
char *gen_install_name(const char *name, int genlib)
{
struct stat sb;
char *newname;
int rv;
newname = gen_library_name(name, genlib);
/* Check if it exists. If not, return NULL. */
rv = stat(newname, &sb);
if (rv) {
return NULL;
}
return newname;
}
char *check_object_exists(command_t *cmd, const char *arg, int arglen)
{
char *newarg, *ext;
int pass, rv;
newarg = (char *)malloc(arglen + 10);
memcpy(newarg, arg, arglen);
newarg[arglen] = 0;
ext = newarg + arglen;
pass = 0;
do {
struct stat sb;
switch (pass) {
case 0:
strcpy(ext, OBJECT_EXT);
break;
/*
case 1:
strcpy(ext, NO_PIC_EXT);
break;
*/
default:
break;
}
if (!cmd->options.silent) {
printf("Checking (obj): %s\n", newarg);
}
rv = stat(newarg, &sb);
}
while (rv != 0 && ++pass < 1);
if (rv == 0) {
if (pass == 1) {
cmd->options.pic_mode = pic_AVOID;
}
return newarg;
}
return NULL;
}
/* libdircheck values:
* 0 - no .libs suffix
* 1 - .libs suffix
*/
char *check_library_exists(command_t *cmd, const char *arg, int pathlen,
int libdircheck, enum lib_type *libtype)
{
char *newarg, *ext;
int pass, rv, newpathlen;
newarg = (char *)malloc(strlen(arg) + 10);
strcpy(newarg, arg);
newarg[pathlen] = 0;
newpathlen = pathlen;
if (libdircheck) {
strcat(newarg, ".libs/");
newpathlen += sizeof(".libs/") - 1;
}
strcpy(newarg+newpathlen, arg+pathlen);
ext = strrchr(newarg, '.') + 1;
pass = 0;
do {
struct stat sb;
switch (pass) {
case 0:
if (cmd->options.pic_mode != pic_AVOID &&
cmd->options.shared != share_STATIC) {
strcpy(ext, DYNAMIC_LIB_EXT);
*libtype = type_DYNAMIC_LIB;
break;
}
pass = 1;
/* Fall through */
case 1:
strcpy(ext, STATIC_LIB_EXT);
*libtype = type_STATIC_LIB;
break;
case 2:
strcpy(ext, MODULE_LIB_EXT);
*libtype = type_MODULE_LIB;
break;
case 3:
strcpy(ext, OBJECT_EXT);
*libtype = type_OBJECT;
break;
default:
*libtype = type_UNKNOWN;
break;
}
if (!cmd->options.silent) {
printf("Checking (lib): %s\n", newarg);
}
rv = stat(newarg, &sb);
}
while (rv != 0 && ++pass < 4);
if (rv == 0) {
return newarg;
}
return NULL;
}
char * load_install_path(const char *arg)
{
FILE *f;
char *path;
path = malloc(PATH_MAX);
f = fopen(arg,"r");
if (f == NULL) {
return NULL;
}
fgets(path, PATH_MAX, f);
fclose(f);
if (path[strlen(path)-1] == '\n') {
path[strlen(path)-1] = '\0';
}
/* Check that we have an absolute path.
* Otherwise the file could be a GNU libtool file.
*/
if (path[0] != '/') {
return NULL;
}
return path;
}
char * load_noinstall_path(const char *arg, int pathlen)
{
char *newarg, *expanded_path;
int newpathlen;
newarg = (char *)malloc(strlen(arg) + 10);
strcpy(newarg, arg);
newarg[pathlen] = 0;
newpathlen = pathlen;
strcat(newarg, ".libs");
newpathlen += sizeof(".libs") - 1;
newarg[newpathlen] = 0;
#ifdef HAS_REALPATH
expanded_path = malloc(PATH_MAX);
expanded_path = realpath(newarg, expanded_path);
/* Uh, oh. There was an error. Fall back on our first guess. */
if (!expanded_path) {
expanded_path = newarg;
}
#else
/* We might get ../ or something goofy. Oh, well. */
expanded_path = newarg;
#endif
return expanded_path;
}
void add_dynamic_link_opts(command_t *cmd_data, count_chars *args)
{
#ifdef DYNAMIC_LINK_OPTS
if (cmd_data->options.pic_mode != pic_AVOID) {
if (!cmd_data->options.silent) {
printf("Adding: %s\n", DYNAMIC_LINK_OPTS);
}
push_count_chars(args, DYNAMIC_LINK_OPTS);
if (cmd_data->undefined_flag) {
push_count_chars(args, "-undefined");
#if defined(__APPLE__)
/* -undefined dynamic_lookup is used by the bundled Python in
* 10.4, but if we don't set MACOSX_DEPLOYMENT_TARGET to 10.3+,
* we'll get a linker error if we pass this flag.
*/
if (strcasecmp(cmd_data->undefined_flag,
"dynamic_lookup") == 0) {
insert_count_chars(cmd_data->program_opts,
"MACOSX_DEPLOYMENT_TARGET=10.3", 0);
}
#endif
push_count_chars(args, cmd_data->undefined_flag);
}
else {
#ifdef DYNAMIC_LINK_UNDEFINED
if (!cmd_data->options.silent) {
printf("Adding: %s\n", DYNAMIC_LINK_UNDEFINED);
}
push_count_chars(args, DYNAMIC_LINK_UNDEFINED);
#endif
}
}
#endif
}
/* Read the final install location and add it to runtime library search path. */
#ifdef RPATH
void add_rpath(count_chars *cc, const char *path)
{
int size = 0;
char *tmp;
#ifdef LINKER_FLAG_PREFIX
size = strlen(LINKER_FLAG_PREFIX);
#endif
size = size + strlen(path) + strlen(RPATH) + 2;
tmp = malloc(size);
if (tmp == NULL) {
return;
}
#ifdef LINKER_FLAG_PREFIX
strcpy(tmp, LINKER_FLAG_PREFIX);
strcat(tmp, RPATH);
#else
strcpy(tmp, RPATH);
#endif
#ifndef LINKER_FLAG_NO_EQUALS
strcat(tmp, "=");
#endif
strcat(tmp, path);
push_count_chars(cc, tmp);
}
void add_rpath_file(count_chars *cc, const char *arg)
{
const char *path;
path = load_install_path(arg);
if (path) {
add_rpath(cc, path);
}
}
void add_rpath_noinstall(count_chars *cc, const char *arg, int pathlen)
{
const char *path;
path = load_noinstall_path(arg, pathlen);
if (path) {
add_rpath(cc, path);
}
}
#endif
#ifdef DYNAMIC_LINK_NO_INSTALL
void add_dylink_noinstall(count_chars *cc, const char *arg, int pathlen,
int extlen)
{
const char *install_path, *current_path, *name;
char *exp_argument;
int i_p_len, c_p_len, name_len, dyext_len, cur_len;
install_path = load_install_path(arg);
current_path = load_noinstall_path(arg, pathlen);
if (!install_path || !current_path) {
return;
}
push_count_chars(cc, DYNAMIC_LINK_NO_INSTALL);
i_p_len = strlen(install_path);
c_p_len = strlen(current_path);
name = arg+pathlen;
name_len = extlen-pathlen;
dyext_len = sizeof(DYNAMIC_LIB_EXT) - 1;
/* No, we need to replace the extension. */
exp_argument = (char *)malloc(i_p_len + c_p_len + (name_len*2) +
(dyext_len*2) + 2);
cur_len = 0;
strcpy(exp_argument, install_path);
cur_len += i_p_len;
exp_argument[cur_len++] = '/';
strncpy(exp_argument+cur_len, name, extlen-pathlen);
cur_len += name_len;
strcpy(exp_argument+cur_len, DYNAMIC_LIB_EXT);
cur_len += dyext_len;
exp_argument[cur_len++] = ':';
strcpy(exp_argument+cur_len, current_path);
cur_len += c_p_len;
exp_argument[cur_len++] = '/';
strncpy(exp_argument+cur_len, name, extlen-pathlen);
cur_len += name_len;
strcpy(exp_argument+cur_len, DYNAMIC_LIB_EXT);
cur_len += dyext_len;
push_count_chars(cc, exp_argument);
}
#endif
/* use -L -llibname to allow to use installed libraries */
void add_minus_l(count_chars *cc, const char *arg)
{
char *newarg;
char *name = strrchr(arg, '/');
char *file = strrchr(arg, '.');
char *lib = strstr(name, "lib");
if (name !=NULL && file != NULL && lib == name+1) {
*name = '\0';
*file = '\0';
file = name;
file = file+4;
push_count_chars(cc, "-L");
push_count_chars(cc, arg);
/* we need one argument like -lapr-1 */
newarg = malloc(strlen(file) + 3);
strcpy(newarg, "-l");
strcat(newarg, file);
push_count_chars(cc, newarg);
} else {
push_count_chars(cc, arg);
}
}
void add_linker_flag_prefix(count_chars *cc, const char *arg)
{
#ifndef LINKER_FLAG_PREFIX
push_count_chars(cc, arg);
#else
char *newarg;
newarg = (char*)malloc(strlen(arg) + sizeof(LINKER_FLAG_PREFIX) + 1);
strcpy(newarg, LINKER_FLAG_PREFIX);
strcat(newarg, arg);
push_count_chars(cc, newarg);
#endif
}
int explode_static_lib(command_t *cmd_data, const char *lib)
{
count_chars tmpdir_cc, libname_cc;
const char *tmpdir, *libname;
char savewd[PATH_MAX];
const char *name;
DIR *dir;
struct dirent *entry;
const char *lib_args[4];
/* Bah! */
if (cmd_data->options.dry_run) {
return 0;
}
name = jlibtool_basename(lib);
init_count_chars(&tmpdir_cc);
push_count_chars(&tmpdir_cc, ".libs/");
push_count_chars(&tmpdir_cc, name);
push_count_chars(&tmpdir_cc, ".exploded/");
tmpdir = flatten_count_chars(&tmpdir_cc, 0);
if (!cmd_data->options.silent) {
printf("Making: %s\n", tmpdir);
}
safe_mkdir(tmpdir);
push_count_chars(cmd_data->tmp_dirs, tmpdir);
getcwd(savewd, sizeof(savewd));
if (chdir(tmpdir) != 0) {
if (!cmd_data->options.silent) {
printf("Warning: could not explode %s\n", lib);
}
return 1;
}
if (lib[0] == '/') {
libname = lib;
}
else {
init_count_chars(&libname_cc);
push_count_chars(&libname_cc, "../../");
push_count_chars(&libname_cc, lib);
libname = flatten_count_chars(&libname_cc, 0);
}
lib_args[0] = LIBRARIAN;
lib_args[1] = "x";
lib_args[2] = libname;
lib_args[3] = NULL;
external_spawn(cmd_data, LIBRARIAN, lib_args);
chdir(savewd);
dir = opendir(tmpdir);
while ((entry = readdir(dir)) != NULL) {
#if defined(__APPLE__) && defined(RANLIB)
/* Apple inserts __.SYMDEF which isn't needed.
* Leopard (10.5+) can also add '__.SYMDEF SORTED' which isn't
* much fun either. Just skip them.
*/
if (strstr(entry->d_name, "__.SYMDEF") != NULL) {
continue;
}
#endif
if (entry->d_name[0] != '.') {
push_count_chars(&tmpdir_cc, entry->d_name);
name = flatten_count_chars(&tmpdir_cc, 0);
if (!cmd_data->options.silent) {
printf("Adding: %s\n", name);
}
push_count_chars(cmd_data->obj_files, name);
pop_count_chars(&tmpdir_cc);
}
}
closedir(dir);
return 0;
}
int parse_input_file_name(char *arg, command_t *cmd_data)
{
char *ext = strrchr(arg, '.');
char *name = strrchr(arg, '/');
int pathlen;
enum lib_type libtype;
char *newarg;
if (!ext) {
return 0;
}
ext++;
if (name == NULL) {
name = strrchr(arg, '\\');
if (name == NULL) {
name = arg;
} else {
name++;
}
} else {
name++;
}
pathlen = name - arg;
if (strcmp(ext, "lo") == 0) {
newarg = check_object_exists(cmd_data, arg, ext - arg);
if (!newarg) {
printf("Can not find suitable object file for %s\n", arg);
exit(1);
}
if (cmd_data->mode != mLink) {
push_count_chars(cmd_data->arglist, newarg);
}
else {
push_count_chars(cmd_data->obj_files, newarg);
}
return 1;
}
if (strcmp(ext, "la") == 0) {
switch (cmd_data->mode) {
case mLink:
/* Try the .libs dir first! */
newarg = check_library_exists(cmd_data, arg, pathlen, 1, &libtype);
if (!newarg) {
/* Try the normal dir next. */
newarg = check_library_exists(cmd_data, arg, pathlen, 0, &libtype);
if (!newarg) {
printf("Can not find suitable library for %s\n", arg);
exit(1);
}
}
/* It is not ok to just add the file: a library may added with:
1 - -L path library_name. (For *.so in Linux).
2 - library_name.
*/
#ifdef ADD_MINUS_L
if (libtype == type_DYNAMIC_LIB) {
add_minus_l(cmd_data->shared_opts.dependencies, newarg);
} else if (cmd_data->output == otLibrary &&
libtype == type_STATIC_LIB) {
explode_static_lib(cmd_data, newarg);
} else {
push_count_chars(cmd_data->shared_opts.dependencies, newarg);
}
#else
if (cmd_data->output == otLibrary && libtype == type_STATIC_LIB) {
explode_static_lib(cmd_data, newarg);
}
else {
push_count_chars(cmd_data->shared_opts.dependencies, newarg);
}
#endif
if (libtype == type_DYNAMIC_LIB) {
if (cmd_data->options.no_install) {
#ifdef RPATH
add_rpath_noinstall(cmd_data->shared_opts.dependencies,
arg, pathlen);
#endif
#ifdef DYNAMIC_LINK_NO_INSTALL
/*
* This doesn't work as Darwin's linker has no way to
* override at link-time the search paths for a
* non-installed library.
*/
/*
add_dylink_noinstall(cmd_data->shared_opts.dependencies,
arg, pathlen, ext - arg);
*/
#endif
}
else {
#ifdef RPATH
add_rpath_file(cmd_data->shared_opts.dependencies, arg);
#endif
}
}
break;
case mInstall:
/* If we've already recorded a library to install, we're most
* likely getting the .la file that we want to install as.
* The problem is that we need to add it as the directory,
* not the .la file itself. Otherwise, we'll do odd things.
*/
if (cmd_data->output == otLibrary) {
arg[pathlen] = '\0';
push_count_chars(cmd_data->arglist, arg);
}
else {
cmd_data->output = otLibrary;
cmd_data->output_name = arg;
cmd_data->static_name.install = gen_install_name(arg, 0);
cmd_data->shared_name.install = gen_install_name(arg, 1);
cmd_data->module_name.install = gen_install_name(arg, 2);
}
break;
default:
break;
}
return 1;
}
if (strcmp(ext, "c") == 0) {
/* If we don't already have an idea what our output name will be. */
if (cmd_data->basename == NULL) {
cmd_data->basename = (char *)malloc(strlen(arg) + 4);
strcpy(cmd_data->basename, arg);
strcpy(strrchr(cmd_data->basename, '.') + 1, "lo");
cmd_data->fake_output_name = strrchr(cmd_data->basename, '/');
if (cmd_data->fake_output_name) {
cmd_data->fake_output_name++;
}
else {
cmd_data->fake_output_name = cmd_data->basename;
}
}
}
return 0;
}
int parse_output_file_name(char *arg, command_t *cmd_data)
{
char *name = strrchr(arg, '/');
char *ext = strrchr(arg, '.');
char *newarg = NULL;
int pathlen;
cmd_data->fake_output_name = arg;
if (name) {
name++;
}
else {
name = strrchr(arg, '\\');
if (name == NULL) {
name = arg;
}
else {
name++;
}
}
#ifdef EXE_EXT
if (!ext || strcmp(ext, EXE_EXT) == 0) {
#else
if (!ext) {
#endif
cmd_data->basename = arg;
cmd_data->output = otProgram;
#if defined(_OSD_POSIX)
cmd_data->options.pic_mode = pic_AVOID;
#endif
newarg = (char *)malloc(strlen(arg) + 5);
strcpy(newarg, arg);
#ifdef EXE_EXT
if (!ext) {
strcat(newarg, EXE_EXT);
}
#endif
cmd_data->output_name = newarg;
return 1;
}
ext++;
pathlen = name - arg;
if (strcmp(ext, "la") == 0) {
assert(cmd_data->mode == mLink);
cmd_data->basename = arg;
cmd_data->static_name.normal = gen_library_name(arg, 0);
cmd_data->shared_name.normal = gen_library_name(arg, 1);
cmd_data->module_name.normal = gen_library_name(arg, 2);
cmd_data->static_name.install = gen_install_name(arg, 0);
cmd_data->shared_name.install = gen_install_name(arg, 1);
cmd_data->module_name.install = gen_install_name(arg, 2);
#ifdef TRUNCATE_DLL_NAME
if (shared) {
arg = truncate_dll_name(arg);
}
#endif
cmd_data->output_name = arg;
return 1;
}
if (strcmp(ext, "lo") == 0) {
cmd_data->basename = arg;
cmd_data->output = otObject;
newarg = (char *)malloc(strlen(arg) + 2);
strcpy(newarg, arg);
ext = strrchr(newarg, '.') + 1;
strcpy(ext, OBJECT_EXT);
cmd_data->output_name = newarg;
return 1;
}
return 0;
}
void parse_args(int argc, char *argv[], command_t *cmd_data)
{
int a;
char *arg;
int argused;
for (a = 1; a < argc; a++) {
arg = argv[a];
argused = 1;
if (arg[0] == '-') {
if (arg[1] == '-') {
argused = parse_long_opt(arg + 2, cmd_data);
}
else {
argused = parse_short_opt(arg + 1, cmd_data);
}
/* We haven't done anything with it yet, try some of the
* more complicated short opts... */
if (argused == 0 && a + 1 < argc) {
if (arg[1] == 'o' && !arg[2]) {
arg = argv[++a];
argused = parse_output_file_name(arg, cmd_data);
} else if (strcmp(arg+1, "MT") == 0) {
if (!cmd_data->options.silent) {
printf("Adding: %s\n", arg);
}
push_count_chars(cmd_data->arglist, arg);
arg = argv[++a];
if (!cmd_data->options.silent) {
printf(" %s\n", arg);
}
push_count_chars(cmd_data->arglist, arg);
argused = 1;
} else if (strcmp(arg+1, "rpath") == 0) {
/* Aha, we should try to link both! */
cmd_data->install_path = argv[++a];
argused = 1;
} else if (strcmp(arg+1, "release") == 0) {
/* Store for later deciphering */
cmd_data->version_info = argv[++a];
argused = 1;
} else if (strcmp(arg+1, "version-info") == 0) {
/* Store for later deciphering */
cmd_data->version_info = argv[++a];
argused = 1;
} else if (strcmp(arg+1, "export-symbols-regex") == 0) {
/* Skip the argument. */
++a;
argused = 1;
} else if (strcmp(arg+1, "release") == 0) {
/* Skip the argument. */
++a;
argused = 1;
} else if (strcmp(arg+1, "undefined") == 0) {
cmd_data->undefined_flag = argv[++a];
argused = 1;
} else if (arg[1] == 'R' && !arg[2]) {
/* -R dir Add dir to runtime library search path. */
add_runtimedirlib(argv[++a], cmd_data);
argused = 1;
}
}
} else {
argused = parse_input_file_name(arg, cmd_data);
}
if (!argused) {
if (!cmd_data->options.silent) {
printf("Adding: %s\n", arg);
}
push_count_chars(cmd_data->arglist, arg);
}
}
}
#ifdef GEN_EXPORTS
void generate_def_file(command_t *cmd_data)
{
char def_file[1024];
char implib_file[1024];
char *ext;
FILE *hDef;
char *export_args[1024];
int num_export_args = 0;
char *cmd;
int cmd_size = 0;
int a;
if (cmd_data->output_name) {
strcpy(def_file, cmd_data->output_name);
strcat(def_file, ".def");
hDef = fopen(def_file, "w");
if (hDef != NULL) {
fprintf(hDef, "LIBRARY '%s' INITINSTANCE\n", nameof(cmd_data->output_name));
fprintf(hDef, "DATA NONSHARED\n");
fprintf(hDef, "EXPORTS\n");
fclose(hDef);
for (a = 0; a < cmd_data->num_obj_files; a++) {
cmd_size += strlen(cmd_data->obj_files[a]) + 1;
}
cmd_size += strlen(GEN_EXPORTS) + strlen(def_file) + 3;
cmd = (char *)malloc(cmd_size);
strcpy(cmd, GEN_EXPORTS);
for (a=0; a < cmd_data->num_obj_files; a++) {
strcat(cmd, " ");
strcat(cmd, cmd_data->obj_files[a] );
}
strcat(cmd, ">>");
strcat(cmd, def_file);
puts(cmd);
export_args[num_export_args++] = SHELL_CMD;
export_args[num_export_args++] = "-c";
export_args[num_export_args++] = cmd;
export_args[num_export_args++] = NULL;
external_spawn(cmd_data, export_args[0], (const char**)export_args);
cmd_data->arglist[cmd_data->num_args++] = strdup(def_file);
/* Now make an import library for the dll */
num_export_args = 0;
export_args[num_export_args++] = DEF2IMPLIB_CMD;
export_args[num_export_args++] = "-o";
strcpy(implib_file, ".libs/");
strcat(implib_file, cmd_data->basename);
ext = strrchr(implib_file, '.');
if (ext)
*ext = 0;
strcat(implib_file, ".");
strcat(implib_file, STATIC_LIB_EXT);
export_args[num_export_args++] = implib_file;
export_args[num_export_args++] = def_file;
export_args[num_export_args++] = NULL;
external_spawn(cmd_data, export_args[0], (const char**)export_args);
}
}
}
#endif
const char* expand_path(const char *relpath)
{
char foo[PATH_MAX], *newpath;
getcwd(foo, PATH_MAX-1);
newpath = (char*)malloc(strlen(foo)+strlen(relpath)+2);
strcat(newpath, foo);
strcat(newpath, "/");
strcat(newpath, relpath);
return newpath;
}
void link_fixup(command_t *c)
{
/* If we were passed an -rpath directive, we need to build
* shared objects too. Otherwise, we should only create static
* libraries.
*/
if (!c->install_path && (c->output == otDynamicLibraryOnly ||
c->output == otModule || c->output == otLibrary)) {
c->output = otStaticLibraryOnly;
}
if (c->output == otDynamicLibraryOnly ||
c->output == otModule ||
c->output == otLibrary) {
push_count_chars(c->shared_opts.normal, "-o");
if (c->output == otModule) {
push_count_chars(c->shared_opts.normal, c->module_name.normal);
}
else {
char *tmp;
push_count_chars(c->shared_opts.normal, c->shared_name.normal);
#ifdef DYNAMIC_INSTALL_NAME
push_count_chars(c->shared_opts.normal, DYNAMIC_INSTALL_NAME);
tmp = (char*)malloc(PATH_MAX);
strcat(tmp, c->install_path);
strcat(tmp, strrchr(c->shared_name.normal, '/'));
push_count_chars(c->shared_opts.normal, tmp);
#endif
}
append_count_chars(c->shared_opts.normal, c->obj_files);
append_count_chars(c->shared_opts.normal, c->shared_opts.dependencies);
if (c->options.export_all) {
#ifdef GEN_EXPORTS
generate_def_file(c);
#endif
}
}
if (c->output == otLibrary || c->output == otStaticLibraryOnly) {
push_count_chars(c->static_opts.normal, "-o");
push_count_chars(c->static_opts.normal, c->output_name);
}
if (c->output == otProgram) {
if (c->output_name) {
push_count_chars(c->arglist, "-o");
push_count_chars(c->arglist, c->output_name);
append_count_chars(c->arglist, c->obj_files);
append_count_chars(c->arglist, c->shared_opts.dependencies);
add_dynamic_link_opts(c, c->arglist);
}
}
}
void post_parse_fixup(command_t *cmd_data)
{
switch (cmd_data->mode)
{
case mCompile:
#ifdef PIC_FLAG
if (cmd_data->options.pic_mode != pic_AVOID) {
push_count_chars(cmd_data->arglist, PIC_FLAG);
}
#endif
if (cmd_data->output_name) {
push_count_chars(cmd_data->arglist, "-o");
push_count_chars(cmd_data->arglist, cmd_data->output_name);
}
break;
case mLink:
link_fixup(cmd_data);
break;
case mInstall:
if (cmd_data->output == otLibrary) {
link_fixup(cmd_data);
}
default:
break;
}
#if USE_OMF
if (cmd_data->output == otObject ||
cmd_data->output == otProgram ||
cmd_data->output == otLibrary ||
cmd_data->output == otDynamicLibraryOnly) {
push_count_chars(cmd_data->arglist, "-Zomf");
}
#endif
if (cmd_data->options.shared &&
(cmd_data->output == otObject ||
cmd_data->output == otLibrary ||
cmd_data->output == otDynamicLibraryOnly)) {
#ifdef SHARE_SW
push_count_chars(cmd_data->arglist, SHARE_SW);
#endif
}
}
int run_mode(command_t *cmd_data)
{
int rv;
count_chars *cctemp;
cctemp = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cctemp);
switch (cmd_data->mode)
{
case mCompile:
rv = run_command(cmd_data, cmd_data->arglist);
if (rv) {
return rv;
}
break;
case mInstall:
/* Well, we'll assume it's a file going to a directory... */
/* For brain-dead install-sh based scripts, we have to repeat
* the command N-times. install-sh should die.
*/
if (!cmd_data->output_name) {
rv = run_command(cmd_data, cmd_data->arglist);
if (rv) {
return rv;
}
}
if (cmd_data->output_name) {
append_count_chars(cctemp, cmd_data->arglist);
insert_count_chars(cctemp,
cmd_data->output_name,
cctemp->num - 1);
rv = run_command(cmd_data, cctemp);
if (rv) {
return rv;
}
clear_count_chars(cctemp);
}
if (cmd_data->static_name.install) {
append_count_chars(cctemp, cmd_data->arglist);
insert_count_chars(cctemp,
cmd_data->static_name.install,
cctemp->num - 1);
rv = run_command(cmd_data, cctemp);
if (rv) {
return rv;
}
#if defined(__APPLE__) && defined(RANLIB)
/* From the Apple libtool(1) manpage on Tiger/10.4:
* ----
* With the way libraries used to be created, errors were possible
* if the library was modified with ar(1) and the table of
* contents was not updated by rerunning ranlib(1). Thus the
* link editor, ld, warns when the modification date of a library
* is more recent than the creation date of its table of
* contents. Unfortunately, this means that you get the warning
* even if you only copy the library.
* ----
*
* This means that when we install the static archive, we need to
* rerun ranlib afterwards.
*/
const char *lib_args[3], *static_lib_name;
char *tmp;
size_t len1, len2;
len1 = strlen(cmd_data->arglist->vals[cmd_data->arglist->num - 1]);
static_lib_name = jlibtool_basename(cmd_data->static_name.install);
len2 = strlen(static_lib_name);
tmp = malloc(len1 + len2 + 2);
snprintf(tmp, len1 + len2 + 2, "%s/%s",
cmd_data->arglist->vals[cmd_data->arglist->num - 1],
static_lib_name);
lib_args[0] = RANLIB;
lib_args[1] = tmp;
lib_args[2] = NULL;
external_spawn(cmd_data, RANLIB, lib_args);
free(tmp);
#endif
clear_count_chars(cctemp);
}
if (cmd_data->shared_name.install) {
append_count_chars(cctemp, cmd_data->arglist);
insert_count_chars(cctemp,
cmd_data->shared_name.install,
cctemp->num - 1);
rv = run_command(cmd_data, cctemp);
if (rv) {
return rv;
}
clear_count_chars(cctemp);
}
if (cmd_data->module_name.install) {
append_count_chars(cctemp, cmd_data->arglist);
insert_count_chars(cctemp,
cmd_data->module_name.install,
cctemp->num - 1);
rv = run_command(cmd_data, cctemp);
if (rv) {
return rv;
}
clear_count_chars(cctemp);
}
break;
case mLink:
if (!cmd_data->options.dry_run) {
/* Check first to see if the dir already exists! */
safe_mkdir(".libs");
}
if (cmd_data->output == otStaticLibraryOnly ||
cmd_data->output == otLibrary) {
#ifdef RANLIB
const char *lib_args[3];
#endif
/* Removes compiler! */
cmd_data->program = LIBRARIAN;
push_count_chars(cmd_data->program_opts, LIBRARIAN_OPTS);
push_count_chars(cmd_data->program_opts,
cmd_data->static_name.normal);
rv = run_command(cmd_data, cmd_data->obj_files);
if (rv) {
return rv;
}
#ifdef RANLIB
lib_args[0] = RANLIB;
lib_args[1] = cmd_data->static_name.normal;
lib_args[2] = NULL;
external_spawn(cmd_data, RANLIB, lib_args);
#endif
}
if (cmd_data->output == otDynamicLibraryOnly ||
cmd_data->output == otModule ||
cmd_data->output == otLibrary) {
cmd_data->program = NULL;
clear_count_chars(cmd_data->program_opts);
append_count_chars(cmd_data->program_opts, cmd_data->arglist);
if (cmd_data->output == otModule) {
#ifdef MODULE_OPTS
push_count_chars(cmd_data->program_opts, MODULE_OPTS);
#endif
} else {
#ifdef SHARED_OPTS
push_count_chars(cmd_data->program_opts, SHARED_OPTS);
#endif
#ifdef dynamic_link_version_func
push_count_chars(cmd_data->program_opts,
dynamic_link_version_func(cmd_data->version_info));
#endif
}
add_dynamic_link_opts(cmd_data, cmd_data->program_opts);
rv = run_command(cmd_data, cmd_data->shared_opts.normal);
if (rv) {
return rv;
}
}
if (cmd_data->output == otProgram) {
rv = run_command(cmd_data, cmd_data->arglist);
if (rv) {
return rv;
}
}
break;
default:
break;
}
return 0;
}
void cleanup_tmp_dir(const char *dirname)
{
DIR *dir;
struct dirent *entry;
char fullname[1024];
dir = opendir(dirname);
if (dir == NULL)
return;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] != '.') {
strcpy(fullname, dirname);
strcat(fullname, "/");
strcat(fullname, entry->d_name);
remove(fullname);
}
}
rmdir(dirname);
}
void cleanup_tmp_dirs(command_t *cmd_data)
{
int d;
for (d = 0; d < cmd_data->tmp_dirs->num; d++) {
cleanup_tmp_dir(cmd_data->tmp_dirs->vals[d]);
}
}
int ensure_fake_uptodate(command_t *cmd_data)
{
/* FIXME: could do the stat/touch here, but nah... */
const char *touch_args[3];
if (cmd_data->mode == mInstall) {
return 0;
}
if (!cmd_data->fake_output_name) {
return 0;
}
touch_args[0] = "touch";
touch_args[1] = cmd_data->fake_output_name;
touch_args[2] = NULL;
return external_spawn(cmd_data, "touch", touch_args);
}
/* Store the install path in the *.la file */
int add_for_runtime(command_t *cmd_data)
{
if (cmd_data->mode == mInstall) {
return 0;
}
if (cmd_data->output == otDynamicLibraryOnly ||
cmd_data->output == otLibrary) {
FILE *f=fopen(cmd_data->fake_output_name,"w");
if (f == NULL) {
return -1;
}
fprintf(f,"%s\n", cmd_data->install_path);
fclose(f);
return(0);
} else {
return(ensure_fake_uptodate(cmd_data));
}
}
int main(int argc, char *argv[])
{
int rc;
command_t cmd_data;
memset(&cmd_data, 0, sizeof(cmd_data));
cmd_data.options.pic_mode = pic_UNKNOWN;
cmd_data.program_opts = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cmd_data.program_opts);
cmd_data.arglist = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cmd_data.arglist);
cmd_data.tmp_dirs = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cmd_data.tmp_dirs);
cmd_data.obj_files = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cmd_data.obj_files);
cmd_data.dep_rpaths = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cmd_data.dep_rpaths);
cmd_data.rpaths = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cmd_data.rpaths);
cmd_data.static_opts.normal = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cmd_data.static_opts.normal);
cmd_data.shared_opts.normal = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cmd_data.shared_opts.normal);
cmd_data.shared_opts.dependencies = (count_chars*)malloc(sizeof(count_chars));
init_count_chars(cmd_data.shared_opts.dependencies);
cmd_data.mode = mUnknown;
cmd_data.output = otGeneral;
parse_args(argc, argv, &cmd_data);
post_parse_fixup(&cmd_data);
if (cmd_data.mode == mUnknown) {
exit(0);
}
rc = run_mode(&cmd_data);
if (!rc) {
add_for_runtime(&cmd_data);
}
cleanup_tmp_dirs(&cmd_data);
return rc;
}
|
the_stack_data/61076077.c | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
int main()
{
setlocale(LC_ALL, "");
char frase[40] = "LIFE IS NOT A PROBLEM TO BE SOLVED";
int i, a, d = 10;
scanf("%d", &a);
for (i = 0; i < a; i++)
{
printf("%c", frase[i]);
}
printf("\n");
return 0;
} |
the_stack_data/145408.c | #include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_t tid[3];
void* print_something(void *arg){
printf("Threading..\n");
sleep(120);
return NULL;
}
void main()
{
int i=0;
int err;
while(i<3)
{
pthread_create(&(tid[i]), NULL,&print_something,NULL);
i++;
}
sleep(120);
return;
}
|
the_stack_data/1014362.c | /*
Database "workshop_paper" contains tables:
acceptance
submission
workshop
*/
#ifndef WORKSHOP_PAPER
#define WORKSHOP_PAPER
struct T_acceptance {
double submission_id; // --> submission.submission_id
double workshop_id; // --> workshop.workshop_id
char result[9];
};
struct T_submission {
double submission_id;
double scores;
char author[15];
char college[17];
};
struct T_workshop {
double workshop_id;
char date[17];
char venue[16];
char name[20];
};
struct T_acceptance
acceptance[] = {
{ 2, 5, "Accepted" },
{ 2, 3, "Rejected" },
{ 3, 2, "Rejected" },
{ 4, 6, "Rejected" },
{ 5, 6, "Rejected" },
{ 1, 1, "Accepted" }
};
struct T_submission
submission[] = {
{ 1, 72.0, "Steve Niehaus", "Notre Dame" },
{ 2, 79.0, "Sammy Green", "Florida" },
{ 3, 78.0, "Sherman Smith", "Miami (OH)" },
{ 4, 79.0, "Steve Raible", "Georgia Tech" },
{ 5, 82.0, "Jeff Lloyd", "West Texas State" },
{ 6, 89.0, "Rick Engles", "Tulsa" },
{ 7, 92.0, "Don Bitterlich", "Temple" },
{ 8, 93.0, "Steve Myer", "New Mexico" },
{ 9, 82.0, "Randy Johnson", "Georgia" },
{ 10, 83.0, "Andy Bolton", "Fisk" }
};
struct T_workshop
workshop[] = {
{ 1, "August 18, 2007", "London UK", "ABC 2007" },
{ 2, "August 21, 2007", "London UK", "Conference 2007" },
{ 3, "August 25, 2007", "New Jersey USA", "Workshop 2007" },
{ 4, "October 8, 2007", "New York USA", "2007 qualification" },
{ 5, "January 14, 2008", "New York USA", "2008 qualification" },
{ 6, "July 5, 2011", "Istanbul Turkey", "Anual Workshop 2011" }
};
#endif |
the_stack_data/84027.c | #if 0
/* memset and memcpy (which is actually memmove) provided by Plan9 libc */
#endif
|
the_stack_data/878384.c | /*
Copyright (c) 2013 Insollo Entertainment, LLC. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include <endian.h>
#include <stdint.h>
int mp_parse_int (const char **pbuf, int *plen, int *result) {
const char *buf;
int len;
unsigned char marker;
buf = *pbuf;
len = *plen;
if (len < 1)
return 0;
marker = (unsigned char)*buf;
buf += 1;
len -= 1;
if ((marker & 0x80) == 0) {
/* Positive fixnum */
*result = marker;
} else if ((marker & 0xe0) == 0xe0) {
/* Negative fixnum */
*result = (signed char)marker;
} else {
switch (marker) {
case 0xCC: /* 8-bit unsigned integer */
if (len < 1)
return 0;
*result = (unsigned char)*buf;
buf += 1;
len -= 1;
break;
case 0xCD: /* 16-bit unsigned integer */
if (len < 2)
return 0;
*result = (int)be16toh(*(uint16_t*)buf);
buf += 2;
len -= 2;
break;
case 0xCE: /* 32-bit unsigned integer */
if (len < 4)
return 0;
*result = (int)be32toh(*(uint32_t*)buf);
buf += 4;
len -= 4;
break;
case 0xD0: /* 8-bit signed integer */
if (len < 1)
return 0;
*result = (char)*buf;
buf += 1;
len -= 1;
break;
case 0xD1: /* 16-bit signed integer */
if (len < 2)
return 0;
*result = (int)(int16_t)be16toh(*(uint16_t*)buf);
buf += 2;
len -= 2;
break;
case 0xD2: /* 32-bit signed integer */
if (len < 4)
return 0;
*result = (int)(int32_t)be32toh(*(uint32_t*)buf);
buf += 4;
len -= 4;
break;
/* We treat 64-bit values as error */
default:
return 0;
}
}
*pbuf = buf;
*plen = len;
return 1;
}
int mp_parse_string (const char **pbuf, int *plen,
const char **result, int *reslen)
{
const char *buf;
int len;
int strlen;
unsigned char marker;
buf = *pbuf;
len = *plen;
if (len < 1)
return 0;
marker = (unsigned char)*buf;
buf += 1;
len -= 1;
if((marker & 0xe0) == 0xa0) {
strlen = marker & ~0xe0;
} else {
switch (marker) {
case 0xD9: /* 8-bit unsigned integer */
if (len < 1)
return 0;
strlen = (unsigned char)*buf;
buf += 1;
len -= 1;
break;
case 0xDA: /* 16-bit unsigned integer */
if (len < 2)
return 0;
strlen = (int)be16toh(*(uint16_t*)buf);
buf += 2;
len -= 2;
break;
case 0xDB: /* 32-bit unsigned integer */
if (len < 4)
return 0;
strlen = (int)be32toh(*(uint32_t*)buf);
buf += 4;
len -= 4;
break;
default:
return 0;
}
}
if (len < strlen)
return 0;
*result = buf;
*reslen = strlen;
*pbuf = buf + strlen;
*plen = len - strlen;
return 1;
}
int mp_parse_array (const char **pbuf, int *plen, int *arrlen) {
const char *buf;
int len;
unsigned char marker;
buf = *pbuf;
len = *plen;
if (len < 1)
return 0;
marker = (unsigned char)*buf;
buf += 1;
len -= 1;
if((marker & 0xf0) == 0x90) {
*arrlen = marker & ~0xf0;
} else {
switch (marker) {
case 0xDC: /* 16-bit unsigned integer */
if (len < 2)
return 0;
*arrlen = (int)be16toh(*(uint16_t*)buf);
buf += 2;
len -= 2;
break;
case 0xDD: /* 32-bit unsigned integer */
if (len < 4)
return 0;
*arrlen = (int)be32toh(*(uint32_t*)buf);
buf += 4;
len -= 4;
break;
default:
return 0;
}
}
*pbuf = buf;
*plen = len;
return 1;
}
int mp_parse_mapping (const char **pbuf, int *plen, int *maplen) {
const char *buf;
int len;
unsigned char marker;
buf = *pbuf;
len = *plen;
if (len < 1)
return 0;
marker = (unsigned char)*buf;
buf += 1;
len -= 1;
if((marker & 0xf0) == 0x80) {
*maplen = marker & ~0xf0;
} else {
switch (marker) {
case 0xDE: /* 16-bit unsigned integer */
if (len < 2)
return 0;
*maplen = (int)be16toh(*(uint16_t*)buf);
buf += 2;
len -= 2;
break;
case 0xDF: /* 32-bit unsigned integer */
if (len < 4)
return 0;
*maplen = (int)be32toh(*(uint32_t*)buf);
buf += 4;
len -= 4;
break;
default:
return 0;
}
}
*pbuf = buf;
*plen = len;
return 1;
}
int mp_skip_value (const char **pbuf, int *plen) {
const char *buf;
int len;
unsigned char marker;
uint32_t maplen;
uint32_t arrlen;
uint32_t strlen;
uint32_t i;
buf = *pbuf;
len = *plen;
if (len < 1)
return 0;
marker = (unsigned char)*buf;
buf += 1;
len -= 1;
if(marker < 0x80 || marker >= 0xE0) { /* fixint */
/* Marker byte is a value, do nothing */
} else if (marker >= 0x80 && marker <= 0x8F) { /* fixmapping */
maplen = marker & 0x0F;
for (i = 0; i < maplen; ++i) {
if (!mp_skip_value (&buf, &len)) /* key */
return 0;
if (!mp_skip_value (&buf, &len)) /* value */
return 0;
}
} else if (marker >= 0x90 && marker <= 0x9F) { /* fixarray */
arrlen = marker & 0x0F;
for (i = 0; i < arrlen; ++i) {
if (!mp_skip_value (&buf, &len))
return 0;
}
} else if (marker >= 0xA0 && marker <= 0xBF) { /* fixstr */
strlen = marker & 0x1F;
if (len < (int)strlen)
return 0;
len -= strlen;
buf += strlen;
} else {
switch (marker) {
case 0xC0: break; /* NIL */
case 0xC2: break; /* False */
case 0xC3: break; /* True */
case 0xC7: /* ext 8 */
len -= 1; /* skip type byte */
buf += 1;
case 0xC4: /* bin 8 */
case 0xD9: /* str 8 */
if(len < 1)
return 0;
strlen = (unsigned char)*buf;
len -= 1 + strlen;
buf += 1 + strlen;
break;
case 0xC8: /* ext 16 */
len -= 1; /* skip type byte */
buf += 1;
case 0xC5: /* bin 16 */
case 0xDA: /* str 16 */
if(len < 2)
return 0;
strlen = be16toh(*(uint16_t*)buf);
len -= 2 + strlen;
buf += 2 + strlen;
break;
case 0xC9: /* ext 32 */
len -= 1; /* skip type byte */
buf += 1;
case 0xC6: /* bin 32 */
case 0xDB: /* str 32 */
if(len < 4)
return 0;
strlen = be32toh(*(uint32_t*)buf);
len -= 4 + strlen;
buf += 4 + strlen;
break;
case 0xCA: /* float 32 */
len -= 4;
buf += 4;
break;
case 0xCB: /* float 64 */
len -= 8;
buf += 8;
break;
case 0xCC: /* uint 8 */
case 0xD0: /* int 8 */
len -= 1;
buf += 1;
break;
case 0xCD: /* uint 16 */
case 0xD1: /* int 16 */
len -= 2;
buf += 2;
break;
case 0xCE: /* uint 32 */
case 0xD2: /* int 32 */
len -= 4;
buf += 4;
break;
case 0xCF: /* uint 64 */
case 0xD3: /* int 64 */
len -= 8;
buf += 8;
break;
case 0xD4: /* fixext 1 */
len -= 2;
buf += 2;
break;
case 0xD5: /* fixext 2 */
len -= 3;
buf += 3;
break;
case 0xD6: /* fixext 4 */
len -= 5;
buf += 5;
break;
case 0xD7: /* fixext 8 */
len -= 9;
buf += 9;
break;
case 0xD8: /* fixext 16 */
len -= 17;
buf += 17;
break;
case 0xDC: /* array 16 */
if (len < 2)
return 0;
arrlen = be16toh(*(uint16_t*)buf);
len -= 2;
buf += 2;
for (i = 0; i < arrlen; ++i) {
if (!mp_skip_value (&buf, &len))
return 0;
}
break;
case 0xDD: /* array 32 */
if (len < 4)
return 0;
arrlen = be32toh(*(uint16_t*)buf);
len -= 4;
buf += 4;
for (i = 0; i < arrlen; ++i) {
if (!mp_skip_value (&buf, &len))
return 0;
}
break;
case 0xDE: /* map 16 */
if (len < 2)
return 0;
maplen = be16toh(*(uint16_t*)buf);
len -= 2;
buf += 2;
for (i = 0; i < maplen; ++i) {
if (!mp_skip_value (&buf, &len)) /* key */
return 0;
if (!mp_skip_value (&buf, &len)) /* value */
return 0;
}
break;
case 0xDF: /* map 32 */
if (len < 4)
return 0;
maplen = be32toh(*(uint16_t*)buf);
len -= 4;
buf += 4;
for (i = 0; i < maplen; ++i) {
if (!mp_skip_value (&buf, &len)) /* key */
return 0;
if (!mp_skip_value (&buf, &len)) /* value */
return 0;
}
break;
default:
return 0;
}
}
if (len < 0)
return 0;
*pbuf = buf;
*plen = len;
return 1;
}
|
the_stack_data/231393882.c | #include <stdio.h>
#include <string.h>
int patternCount();
int main()
{
int num = 0, count = 0, size = 256;
char string [size];
char tofind [size];
printf("Enter the string: ");
gets(string);
printf("\n Enter the number of patterns: ");
scanf ("%d", &num);
for (int i = 0; i <= num; i++)
{
printf("Enter pattern %d: ", i);
gets(tofind);
count = patternCount(string, tofind);
printf("\n %d \n", count);
}
}
int patternCount (char * string, char * tofind)
{
int count = 0, present;
for (int i = 0; i <= strlen(string) - strlen(tofind); i++)
{
present = 1;
for (int j = 0; j < strlen(tofind); j++)
{
if (string[i + j] != tofind[j])
{
present = 0;
break;
}
}
if (present == 1)
count++;
}
return count;
}
|
the_stack_data/48575841.c | /*
* Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* We need conformance on so that EOPNOTSUPP=102. But the routine symbol
* will still be the legacy (undecorated) one.
*/
#undef __DARWIN_UNIX03
#define __DARWIN_UNIX03 1
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
ssize_t __sendto_nocancel(int, const void *, size_t, int, const struct sockaddr *, socklen_t);
/*
* sendto stub, legacy version
*/
ssize_t
sendto(int s, const void *msg, size_t len, int flags, const struct sockaddr *to, socklen_t tolen)
{
int ret = __sendto_nocancel(s, msg, len, flags, to, tolen);
/* use ENOTSUP for legacy behavior */
if (ret < 0 && errno == EOPNOTSUPP)
errno = ENOTSUP;
return ret;
}
|
the_stack_data/64561.c | #include "strings.h"
#include <stdio.h>
#include <stdlib.h>
#define MAX_PATH 260
void input(char* str, char* delim)
{
printf("delim: ");
scanf("%c", delim);
printf("paths: ");
scanf("%s", str);
printf("\n");
}
void output(int n)
{
switch (n)
{
case 1:
printf("Incorrect way\n");
break;
case 2:
printf("Length too long\n");
break;
case 3:
printf("Incorrect way in this lab\n");
break;
case 4:
printf("Correct way\n");
break;
}
}
int check_ip(char* str)
{
char strcopy[100];
scpy(str, strcopy);
char* ptr[10];
int num_of_str;
int num;
// printf("strcopy_ip = %s\n", strcopy);
num_of_str = stok(strcopy, '.', ptr);
if (num_of_str != 4)
{
return 1;
}
for (int i = 0; i < num_of_str; i++)
{
num = atoi(ptr[i]);
// printf("number = %d\n", num);
if ((num < 0) || (num > 255))
{
return 1;
}
}
return 4;
}
int check_domain(char* str)
{
char strcopy[100];
char substr[50];
scpy(str, strcopy);
char* ptr[10];
int num_of_str;
int length;
// printf("strcopy_ip = %s\n", strcopy);
num_of_str = stok(strcopy, '.', ptr);
if (num_of_str > 4)
{
return 3;
}
for (int i = 0; i < num_of_str; i++)
{
scpy(ptr[i], substr);
length = slen(substr);
for (int j = 0; j < length; j++)
{
if ((isLowCase(substr[j]) == 1) && (isTallCase(substr[j]) == 1))
{
return 3;
}
}
}
if ((scmp(ptr[num_of_str - 1], "com") == 1) || (scmp(ptr[num_of_str - 1], "org") == 1) || (scmp(ptr[num_of_str - 1], "ru") == 1))
{
return 4;
}
return 3;
}
int check(char* substr)
{
int domain = 0, ip = 0;
int length;
char firstletter;
char ip_domain[100];
if (slen(substr) > MAX_PATH)
{
return 2;
}
if (sspn(substr, ":*?<>|") == 1)
{
return 1;
}
substring(substr, ip_domain);
// printf("ip_domain = %s\n", ip_domain);
length = slen(ip_domain);
firstletter = ip_domain[0];
for (int i = 0; i < length; i++)
{
if ((isLowCase(ip_domain[i]) == 0) || (isTallCase(ip_domain[i]) == 0))
{
domain = 1;
}
if (isDigit(ip_domain[i]) == 0)
{
ip = 1;
}
if ((ip == 0) && (domain == 0) && (ip_domain[i] != '.'))
{
return 3;
}
}
if (isDigit(firstletter) == 0)
{
return check_ip(ip_domain);
}
else
{
return check_domain(ip_domain);
}
}
void process(char* str)
{
char ip_domain[270];
char* suf = (str + 2);
int i;
int idx_of_end, idx_of_second_part;
idx_of_second_part = schr(suf, '\\');
suf = (suf + idx_of_second_part);
substring(str, ip_domain);
idx_of_end = schr(ip_domain, '\0');
ip_domain[idx_of_end] = ':';
ip_domain[idx_of_end + 1] = '\0';
strconcat(ip_domain, suf);
scpy(ip_domain, str);
while ((i = schr(str, '\\')) >= 0)
{
str[i] = '/';
}
}
int main()
{
char str[270];
char newstr[270];
newstr[0] = '\0';
char delim;
char delim_str[2];
char* ptr[10];
int num_of_str, result_of_check;
input(str, &delim);
delim_str[0] = delim;
num_of_str = stok(str, delim, ptr);
for (int i = 0; i < num_of_str; i++)
{
if ((result_of_check = check(ptr[i])) == 4)
{
if (newstr[0] != '\0')
{
strconcat(newstr, delim_str);
}
process(ptr[i]);
strconcat(newstr, ptr[i]);
}
printf("%d. ", i + 1);
output(result_of_check);
}
printf("\nnew paths: %s\n", newstr);
return 0;
} |
the_stack_data/43227.c | /*
* $Id: mouse.c,v 1.21 2015/05/13 20:56:28 tom Exp $
*
* mouse.c -- mouse support for dialog
*
* Copyright 2002-2012,2015 Thomas E. Dickey
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License, version 2.1
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to
* Free Software Foundation, Inc.
* 51 Franklin St., Fifth Floor
* Boston, MA 02110, USA.
*/
#include <dialog.h>
#include <dlg_keys.h>
#if USE_MOUSE
static int basex, basey, basecode;
static mseRegion *regionList = NULL;
/*=========== region related functions =============*/
static mseRegion *
find_region_by_code(int code)
{
mseRegion *butPtr;
for (butPtr = regionList; butPtr; butPtr = butPtr->next) {
if (code == butPtr->code)
break;
}
return butPtr;
}
void
dlg_mouse_setbase(int x, int y)
{
basex = x;
basey = y;
}
void
dlg_mouse_setcode(int code)
{
basecode = code;
}
void
dlg_mouse_mkbigregion(int y, int x,
int height, int width,
int code,
int step_y, int step_x,
int mode)
{
mseRegion *butPtr = dlg_mouse_mkregion(y, x, height, width, -DLGK_MOUSE(code));
butPtr->mode = mode;
butPtr->step_x = MAX(1, step_x);
butPtr->step_y = MAX(1, step_y);
}
void
dlg_mouse_free_regions(void)
{
while (regionList != 0) {
mseRegion *butPtr = regionList->next;
free(regionList);
regionList = butPtr;
}
}
mseRegion *
dlg_mouse_mkregion(int y, int x, int height, int width, int code)
{
mseRegion *butPtr;
if ((butPtr = find_region_by_code(basecode + code)) == 0) {
butPtr = dlg_malloc(mseRegion, 1);
assert_ptr(butPtr, "dlg_mouse_mkregion");
butPtr->next = regionList;
regionList = butPtr;
}
butPtr->mode = -1;
butPtr->step_x = 0;
butPtr->step_y = 0;
butPtr->y = basey + y;
butPtr->Y = basey + y + height;
butPtr->x = basex + x;
butPtr->X = basex + x + width;
butPtr->code = basecode + code;
return butPtr;
}
/* retrieve the frame under the pointer */
static mseRegion *
any_mouse_region(int y, int x, int small)
{
mseRegion *butPtr;
for (butPtr = regionList; butPtr; butPtr = butPtr->next) {
if (small ^ (butPtr->code >= 0)) {
continue;
}
if (y < butPtr->y || y >= butPtr->Y) {
continue;
}
if (x < butPtr->x || x >= butPtr->X) {
continue;
}
break; /* found */
}
return butPtr;
}
/* retrieve the frame under the pointer */
mseRegion *
dlg_mouse_region(int y, int x)
{
return any_mouse_region(y, x, TRUE);
}
/* retrieve the bigframe under the pointer */
mseRegion *
dlg_mouse_bigregion(int y, int x)
{
return any_mouse_region(y, x, FALSE);
}
#else
void mouse_dummy(void);
void
mouse_dummy(void)
{
}
#endif /* USE_MOUSE */
|
the_stack_data/70449708.c | /* example.c -- usage example of the zlib compression library
* Copyright (C) 1995-2006 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id: example.c,v 1.1 2011/11/22 23:35:30 rbsheth Exp $ */
#include "zlib.h"
#include <stdio.h>
#ifdef STDC
# include <string.h>
# include <stdlib.h>
#endif
#if defined(VMS) || defined(RISCOS)
# define TESTFILE "foo-gz"
#else
# define TESTFILE "foo.gz"
#endif
#define CHECK_ERR(err, msg) { \
if (err != Z_OK) { \
fprintf(stderr, "%s error: %d\n", msg, err); \
exit(1); \
} \
}
const char hello[] = "hello, hello!";
/* "hello world" would be more standard, but the repeated "hello"
* stresses the compression code better, sorry...
*/
const char dictionary[] = "hello";
uLong dictId; /* Adler32 value of the dictionary */
void test_compress OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_gzio OF((const char *fname,
Byte *uncompr, uLong uncomprLen));
void test_deflate OF((Byte *compr, uLong comprLen));
void test_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_large_deflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_large_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_flush OF((Byte *compr, uLong *comprLen));
void test_sync OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_dict_deflate OF((Byte *compr, uLong comprLen));
void test_dict_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
int main OF((int argc, char *argv[]));
/* ===========================================================================
* Test compress() and uncompress()
*/
void test_compress(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
uLong len = (uLong)strlen(hello)+1;
err = compress(compr, &comprLen, (const Bytef*)hello, len);
CHECK_ERR(err, "compress");
strcpy((char*)uncompr, "garbage");
err = uncompress(uncompr, &uncomprLen, compr, comprLen);
CHECK_ERR(err, "uncompress");
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad uncompress\n");
exit(1);
} else {
printf("uncompress(): %s\n", (char *)uncompr);
}
}
/* ===========================================================================
* Test read/write of .gz files
*/
void test_gzio(fname, uncompr, uncomprLen)
const char *fname; /* compressed file name */
Byte *uncompr;
uLong uncomprLen;
{
#ifdef NO_GZCOMPRESS
fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n");
#else
int err;
int len = (int)strlen(hello)+1;
gzFile file;
z_off_t pos;
file = gzopen(fname, "wb");
if (file == NULL) {
fprintf(stderr, "gzopen error\n");
exit(1);
}
gzputc(file, 'h');
if (gzputs(file, "ello") != 4) {
fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err));
exit(1);
}
if (gzprintf(file, ", %s!", "hello") != 8) {
fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err));
exit(1);
}
gzseek(file, 1L, SEEK_CUR); /* add one zero byte */
gzclose(file);
file = gzopen(fname, "rb");
if (file == NULL) {
fprintf(stderr, "gzopen error\n");
exit(1);
}
strcpy((char*)uncompr, "garbage");
if (gzread(file, uncompr, (unsigned)uncomprLen) != len) {
fprintf(stderr, "gzread err: %s\n", gzerror(file, &err));
exit(1);
}
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad gzread: %s\n", (char*)uncompr);
exit(1);
} else {
printf("gzread(): %s\n", (char*)uncompr);
}
pos = gzseek(file, -8L, SEEK_CUR);
if (pos != 6 || gztell(file) != pos) {
fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n",
(long)pos, (long)gztell(file));
exit(1);
}
if (gzgetc(file) != ' ') {
fprintf(stderr, "gzgetc error\n");
exit(1);
}
if (gzungetc(' ', file) != ' ') {
fprintf(stderr, "gzungetc error\n");
exit(1);
}
gzgets(file, (char*)uncompr, (int)uncomprLen);
if (strlen((char*)uncompr) != 7) { /* " hello!" */
fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err));
exit(1);
}
if (strcmp((char*)uncompr, hello + 6)) {
fprintf(stderr, "bad gzgets after gzseek\n");
exit(1);
} else {
printf("gzgets() after gzseek: %s\n", (char*)uncompr);
}
gzclose(file);
#endif
}
/* ===========================================================================
* Test deflate() with small buffers
*/
void test_deflate(compr, comprLen)
Byte *compr;
uLong comprLen;
{
z_stream c_stream; /* compression stream */
int err;
uLong len = (uLong)strlen(hello)+1;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
CHECK_ERR(err, "deflateInit");
c_stream.next_in = (Bytef*)hello;
c_stream.next_out = compr;
while (c_stream.total_in != len && c_stream.total_out < comprLen) {
c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
}
/* Finish the stream, still forcing small buffers: */
for (;;) {
c_stream.avail_out = 1;
err = deflate(&c_stream, Z_FINISH);
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "deflate");
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
}
/* ===========================================================================
* Test inflate() with small buffers
*/
void test_inflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = 0;
d_stream.next_out = uncompr;
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) {
d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "inflate");
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad inflate\n");
exit(1);
} else {
printf("inflate(): %s\n", (char *)uncompr);
}
}
/* ===========================================================================
* Test deflate() with large buffers and dynamic change of compression level
*/
void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
z_stream c_stream; /* compression stream */
int err;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_BEST_SPEED);
CHECK_ERR(err, "deflateInit");
c_stream.next_out = compr;
c_stream.avail_out = (uInt)comprLen;
/* At this point, uncompr is still mostly zeroes, so it should compress
* very well:
*/
c_stream.next_in = uncompr;
c_stream.avail_in = (uInt)uncomprLen;
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
if (c_stream.avail_in != 0) {
fprintf(stderr, "deflate not greedy\n");
exit(1);
}
/* Feed in already compressed data and switch to no compression: */
deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY);
c_stream.next_in = compr;
c_stream.avail_in = (uInt)comprLen/2;
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
/* Switch back to compressing mode: */
deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED);
c_stream.next_in = uncompr;
c_stream.avail_in = (uInt)uncomprLen;
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) {
fprintf(stderr, "deflate should report Z_STREAM_END\n");
exit(1);
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
}
/* ===========================================================================
* Test inflate() with large buffers
*/
void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = (uInt)comprLen;
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
for (;;) {
d_stream.next_out = uncompr; /* discard the output */
d_stream.avail_out = (uInt)uncomprLen;
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "large inflate");
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
if (d_stream.total_out != 2*uncomprLen + comprLen/2) {
fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out);
exit(1);
} else {
printf("large_inflate(): OK\n");
}
}
/* ===========================================================================
* Test deflate() with full flush
*/
void test_flush(compr, comprLen)
Byte *compr;
uLong *comprLen;
{
z_stream c_stream; /* compression stream */
int err;
uInt len = (uInt)strlen(hello)+1;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
CHECK_ERR(err, "deflateInit");
c_stream.next_in = (Bytef*)hello;
c_stream.next_out = compr;
c_stream.avail_in = 3;
c_stream.avail_out = (uInt)*comprLen;
err = deflate(&c_stream, Z_FULL_FLUSH);
CHECK_ERR(err, "deflate");
compr[3]++; /* force an error in first compressed block */
c_stream.avail_in = len - 3;
err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) {
CHECK_ERR(err, "deflate");
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
*comprLen = c_stream.total_out;
}
/* ===========================================================================
* Test inflateSync()
*/
void test_sync(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = 2; /* just read the zlib header */
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
d_stream.next_out = uncompr;
d_stream.avail_out = (uInt)uncomprLen;
inflate(&d_stream, Z_NO_FLUSH);
CHECK_ERR(err, "inflate");
d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */
err = inflateSync(&d_stream); /* but skip the damaged part */
CHECK_ERR(err, "inflateSync");
err = inflate(&d_stream, Z_FINISH);
if (err != Z_DATA_ERROR) {
fprintf(stderr, "inflate should report DATA_ERROR\n");
/* Because of incorrect adler32 */
exit(1);
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
printf("after inflateSync(): hel%s\n", (char *)uncompr);
}
/* ===========================================================================
* Test deflate() with preset dictionary
*/
void test_dict_deflate(compr, comprLen)
Byte *compr;
uLong comprLen;
{
z_stream c_stream; /* compression stream */
int err;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_BEST_COMPRESSION);
CHECK_ERR(err, "deflateInit");
err = deflateSetDictionary(&c_stream,
(const Bytef*)dictionary, sizeof(dictionary));
CHECK_ERR(err, "deflateSetDictionary");
dictId = c_stream.adler;
c_stream.next_out = compr;
c_stream.avail_out = (uInt)comprLen;
c_stream.next_in = (Bytef*)hello;
c_stream.avail_in = (uInt)strlen(hello)+1;
err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) {
fprintf(stderr, "deflate should report Z_STREAM_END\n");
exit(1);
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
}
/* ===========================================================================
* Test inflate() with a preset dictionary
*/
void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = (uInt)comprLen;
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
d_stream.next_out = uncompr;
d_stream.avail_out = (uInt)uncomprLen;
for (;;) {
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break;
if (err == Z_NEED_DICT) {
if (d_stream.adler != dictId) {
fprintf(stderr, "unexpected dictionary");
exit(1);
}
err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary,
sizeof(dictionary));
}
CHECK_ERR(err, "inflate with dict");
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad inflate with dict\n");
exit(1);
} else {
printf("inflate with dictionary: %s\n", (char *)uncompr);
}
}
/* ===========================================================================
* Usage: example [output.gz [input.gz]]
*/
int main(argc, argv)
int argc;
char *argv[];
{
Byte *compr, *uncompr;
uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */
uLong uncomprLen = comprLen;
static const char* myVersion = ZLIB_VERSION;
if (zlibVersion()[0] != myVersion[0]) {
fprintf(stderr, "incompatible zlib version\n");
exit(1);
} else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) {
fprintf(stderr, "warning: different zlib version\n");
}
printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n",
ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags());
compr = (Byte*)calloc((uInt)comprLen, 1);
uncompr = (Byte*)calloc((uInt)uncomprLen, 1);
/* compr and uncompr are cleared to avoid reading uninitialized
* data and to ensure that uncompr compresses well.
*/
if (compr == Z_NULL || uncompr == Z_NULL) {
printf("out of memory\n");
exit(1);
}
test_compress(compr, comprLen, uncompr, uncomprLen);
test_gzio((argc > 1 ? argv[1] : TESTFILE),
uncompr, uncomprLen);
test_deflate(compr, comprLen);
test_inflate(compr, comprLen, uncompr, uncomprLen);
test_large_deflate(compr, comprLen, uncompr, uncomprLen);
test_large_inflate(compr, comprLen, uncompr, uncomprLen);
test_flush(compr, &comprLen);
test_sync(compr, comprLen, uncompr, uncomprLen);
comprLen = uncomprLen;
test_dict_deflate(compr, comprLen);
test_dict_inflate(compr, comprLen, uncompr, uncomprLen);
free(compr);
free(uncompr);
return 0;
}
|
the_stack_data/150139485.c | /* To check behavior with a free
*
* Same as call33, but use an array in the callee
*
* Parameter i added to help debugging.
*/
#include <stdlib.h>
void call35(int i, int * q[10])
{
*q[0] = 1; // added to check effects
free(q[i]);
return;
}
int call35_caller(int * qq[10])
{
int ii = *qq[0];
call35(ii, qq);
return ii++; // To check indirect impact on memory effects
}
|
the_stack_data/72013338.c | #include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in array\n"); //Enter the number of array elements
scanf("%d", &n);
printf("Enter (%d) integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]); //Enter each of the elements in the array
printf("Enter a number to search\n");
scanf("%d", &search); //Enter the element to be searched
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
|
the_stack_data/155552.c | #include <math.h>
int add(int a, int b){
return a + b;
} |
the_stack_data/34929.c | #include <stdio.h>
int main() {
int i;
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
int int_array[5] = {1, 2, 3, 4, 5};
char *char_pointer;
int *int_pointer;
char_pointer = (char *) int_array; // Typecast into the
int_pointer = (int *) char_array; // pointer's data type
for(i=0; i < 5; i++) { // iterate through the int array with the int_pointer
printf("[integer pointer] points to %p, which contains the char '%c'\n",
int_pointer, *int_pointer);
int_pointer = (int *) ((char *) int_pointer + 1);
}
for(i=0; i < 5; i++) { // iterate through the char array with the char_pointer
printf("[char pointer] points to %p, which contains the integer %d\n",
char_pointer, *char_pointer);
char_pointer = (char *) ((int *) char_pointer + 1);
}
}
|
the_stack_data/159515982.c | #include <stdio.h>
#include <netinet/in.h> /* for htonl */
int main(int argc, char *argv[]) {
unsigned int bits,i,k,m,step, max,v,maxt;
FILE *out, *in;
unsigned long q;
bits = atoi(argv[1]);
if((bits!=2)&&(bits!=4)) {
printf("usage: gray2n bits outfile infiles ...\n");
exit(1);
}
max = (1<<bits)-1;
step = 255/max;
out = fopen(argv[2], "wb");
for(i=3;i<argc;i++) {
in = fopen(argv[i], "rb");
/* each tile has 256 bits */
for(q=0,k=0;k<256;k++) {
m = fgetc(in);
v = max - ((m+step/2)/step);
q <<= bits;
q |= v;
if((k&((32/bits)-1))==((32/bits)-1)) {
q = htonl(q);
fwrite(&q, sizeof(unsigned long), 1, out);
q=0;
}
}
fclose(in);
}
fclose(out);
return 0;
}
|
the_stack_data/599229.c | #include<stdio.h>
int main() {
printf("hello,world\n");
return 0;
}
|
the_stack_data/243893884.c | #include <stdio.h>
#include <stdlib.h>
#define LENGTH 8
//global
typedef struct Node
{
// the head node contains the length of LinkList
int value;
struct Node *next;
} Node;
typedef struct Node *LinkList;
//prototype
LinkList GetReversedLinkList(LinkList headNode);
LinkList NewLinkList_WithHeadNode(int length);
int FindIndexByValue(LinkList headNode, int value, int start_index);
LinkList ClearList(LinkList headNode);
int main()
{
//init
LinkList a = NewLinkList_WithHeadNode(LENGTH),p = a->next;
int counter = 1;
//show value
while(NULL != p)
{
printf("the value of Node %d is %d \n",counter,p->value);
p = p->next;
counter++;
}
//reverse
a = GetReversedLinkList(a);
//find first 5
int indexOf5 = FindIndexByValue(a,5,0);
printf("The index of first node with value 5 is %d \n",indexOf5);
//find second 5
indexOf5 = FindIndexByValue(a,5,indexOf5 + 1);
printf("The index of second node with value 5 is %d \n",indexOf5);
//delete linked list
a = ClearList(a);
return 0;
}
LinkList ClearList(LinkList headNode)
{
LinkList p = headNode,q = p->next;
while(p != NULL)
{
q = q->next;
free(p);
p = q;
}
return NULL;
}
int FindIndexByValue(LinkList headNode, int value, int start_index)
{
int result = -1;
LinkList p = headNode->next;
while (p != NULL)
{
if(value != p->value || result + 2 < start_index)
{
p = p->next;
result++;
continue;
}
break;
}
result += 2;
return result;
}
LinkList NewLinkList_WithHeadNode(int length)
{
//create head node
LinkList head_node = (LinkList)malloc(sizeof(Node)),p = NULL,r = NULL;
head_node->value = 0;
head_node->next = NULL;
r = head_node;
//add nodes
int i;
for(i = 0;i<length;i++)
{
//create new node
p = (LinkList)malloc(sizeof(Node));
p->value = 0;
// TODO WARNING: specific requirement for test, delete before using
{if(2 == i || 4 == i)
p->value = 5;}
//add to tail
r->next = p;
r = p;
}
r->next = NULL;
return head_node;
}
LinkList GetReversedLinkList(LinkList headNode)
{
//init
LinkList current_p = NULL,backup_p = NULL,pioneer_p = NULL;
//reverse
current_p = headNode->next;
pioneer_p = current_p;
headNode->next = NULL;
while(current_p != NULL)
{
pioneer_p = pioneer_p->next;
current_p->next = backup_p;
backup_p = current_p;
current_p = pioneer_p;
}
headNode->next = backup_p;
return headNode;
}
|
the_stack_data/140765678.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
// Beim kompilieren muss die Option 'lm' hinzugefügt werden: 'gcc ex1.c -lm -o ex1'
// Mit der Option '-v' hinter dem Dateinamen, werden alle "Fehler" ausgegeben: 'time ./ex1 ../ex1.dat -v'
/* Output of my Linux running as VM:
File: ../ex1.dat with 100001235 lines
Valid values Loc1: 50004777 with GeoMean: 36.781715
Valid values Loc2: 49994865 with GeoMean: 36.782540
real 1m14.107s
user 1m11.204s
sys 0m2.832s
*/
#define EXT_SIZE (1024*1024)
#define MAX_LINE_LEN 512
#define LOCS 2
#define DELIMITER ";"
void add_float(int loc,double fl);
void print_error_and_continue(char* line, char* error);
void validate_line(char* line);
double geom_mean_pow(const double* x, const size_t count);
// idea of realloc array was taken from TKoch. PS: using the variables as global variables is my lazy way of
size_t loc_next [LOCS]; // the index of the next number to store
size_t loc_size [LOCS]; // the size of the arrays to store the numbers
double* loc_value [LOCS]; // array to store the numbers
bool VERBOSE = false;
int len = 0;
int main(int argc, char *args[]){
if (argc < 1) return 0;
int j = argc;
while(j > 0 && !VERBOSE){
if(strcmp(args[j-1], "-v") == 0){
VERBOSE = true;
}
j--;
}
for(int i = 0; i < LOCS; i++){
loc_next [i] = 0; // we start empty
loc_size [i] = EXT_SIZE; // initial size
loc_value[i] = malloc(loc_size[i] * sizeof(loc_value[i][0]));
}
FILE * fp;
char * line = NULL;
ssize_t lineLength = 0;
int read;
fp = fopen(args[1], "r");
if (fp == NULL) exit(EXIT_FAILURE);
while ((read = getline(&line, &lineLength, fp)) != -1) {
len++;
validate_line(line);
}
printf("File: %s with %i lines\n", args[1], len);
for(int i = 0; i < LOCS; i++){
printf("Valid values Loc%i: %li with GeoMean: %lf\n", i + 1, loc_next[i], geom_mean_pow(loc_value[i],loc_next[i]));
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
return 0;
}
double geom_mean_pow(const double* x, const size_t count){
double res = 1.0;
double factor = 1.0/count;
for (int i = 0; i < count; i++){
res *= pow(x[i], factor);
}
return res;
}
void add_float(int loc,double fl){
if (loc_next[loc-1] == loc_size[loc-1]){
loc_size [loc-1] += EXT_SIZE;
loc_value[loc-1] = realloc(loc_value[loc-1], loc_size[loc-1] * sizeof(loc_value[loc-1][0]));
}
loc_value[loc-1][loc_next[loc-1]] = fl;
loc_next[loc-1]++;
}
void print_error(char* line, char* error){
if (VERBOSE == 0) return;
printf("Error [%10s,%9i]: %s", error, len, line);
}
void validate_line(char* line){
// empty line
if (strcmp(line,"\n") == 0){
print_error(line,"empty"); return;
}
char lineTMP[MAX_LINE_LEN];
strcpy(lineTMP, line);
lineTMP[MAX_LINE_LEN] = '\0';
// line starting with # is neglected
if (strncmp(lineTMP, "#",1) == 0){
print_error(line,"comment"); return;
}
strtok(lineTMP, "'#");
// splitting line
char* ptr = strtok(lineTMP, DELIMITER);
char* ptrClass = strtok(NULL, DELIMITER);
int loc = atoi(ptrClass);
// False or none location
if (loc > LOCS || loc < 1){
print_error(line,"falseLOC"); return;
}
char* ptrFloat = strtok(NULL, DELIMITER);
// no float as third argument or less than 3 arguments
if (ptrFloat == NULL){
print_error(line,"noFloat"); return;
}
double number = atof(ptrFloat);
// non-positive or NAN value
if (number <= 0.0 || !isnormal(number)){
print_error(line,"falseValue"); return;
}
add_float(loc,number);
}
|
the_stack_data/97013737.c | #include <stdio.h>
int main(void) {
int m, d, y;
char *months[12] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December"};
printf("Enter a date (mm/dd/yyyy): ");
scanf("%d / %d / %d", &m, &d, &y);
printf("You entered the date %s %.2d, %d\n", months[m-1], d, y);
return 0;
}
|
the_stack_data/159516759.c | #include <stdio.h>
#include <math.h>
#define HC(a,b,c) (((a)+(b)+(c))/2.0)
#define AREA(a,b,c,p) (sqrt((p)*((p)-a)*((p)-b)*((p)-c)))
int main() {
#ifndef ONLINE_JUDGE
freopen("1.in", "r", stdin);
freopen("1.out", "w", stdout);
freopen("1.err", "w", stderr);
#endif
double a, b, c;
scanf("%lf,%lf,%lf", &a, &b, &c);
printf("area=%.2lf", AREA(a, b, c, HC(a, b, c)));
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
fclose(stderr);
#endif
return 0;
} |
the_stack_data/118505.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
if (!fork()) {
while(1);
}
exit(0);
}
|
the_stack_data/769975.c | /*Exercise 4 - Functions
Implement the three functions minimum(), maximum() and multiply() below the main() function.
Do not change the code given in the main() function when you are implementing your solution.*/
#include <stdio.h>
int minimum(int no1,int no2);
int maximum(int no1,int no2);
int multiply(int no1,int no2);
int main() {
int no1, no2;
printf("Enter a value for no 1 : ");
scanf("%d", &no1);
printf("Enter a value for no 2 : ");
scanf("%d", &no2);
printf("Minimun: %d\n", minimum(no1, no2));
printf("Maximum: %d\n", maximum(no1, no2));
printf("multiply: %d\n", multiply(no1, no2));
return 0;
}
int minimum(int no1,int no2)
{int min;
if(no1<no2)
{
min=no1;
}
else
{
min=no2;
}
return min;
}
int maximum(int no1,int no2)
{
int max;
if(no1>no2)
{
max=no1;
}
else{
max=no2;
}
return max;
}
int multiply(int no1,int no2)
{
int multi;
return multi=no1*no2;
}
|
the_stack_data/82951248.c | #include <stdio.h>
#include <string.h>
void main (void)
{
// Declare two strings to be compared
char str1[10] = "first";
char str2[10] = "first";
// Use strcmp to compare the strings and if true, report to user
if (strcmp (str1, str2) == 0)
{
printf ("The two strings are identical.\n");
}
// If the strings are different, report to user
else
{
printf ("The two strings are different.\n");
}
}
|
the_stack_data/145454222.c | #include <stdio.h>
int main(void)
{
char a,b;
int i=0,n1,n2;
scanf("%c%c",&a,&b);
if(a>='0' && a<='9')
{
n1=(a-'0')*16;
}
else if(a>='A' && a<='F')
{
n1=(a-'A'+10)*16;
}
else
{
i++;
}
if(b>='0' && b<='9')
{
n2=(b-'0');
}
else if(b>='A' && b<='F')
{
n2=(b-'A'+10);
}
else
{
i++;
}
if(i>=1)
{
printf("%c%c=NO",a,b);
}
else
{
printf("%c%c=%d",a,b,n1+n2);
}
return 0;
}
|
the_stack_data/29536.c | int func(int a, int b)
{
int z;
while(a>b) {
z = a + b;
}
return z;
}
|
the_stack_data/90766599.c | // Bitwise Operators "https://www.hackerrank.com/challenges/bitwise-operators-in-c/problem"
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
void calculate_the_maximum(int n, int k) {
//Write your code here.
int maxAnd = 0;
int maxOr = 0;
int maxXor = 0;
for (int i=1; i<n; i++) {
for (int j=(i+1); j<=n; j++) {
if (((i & j) < k) & ((i & j) > maxAnd)) {
maxAnd = (i&j);
}
if (((i | j) < k) & ((i | j) > maxOr)) {
maxOr = (i|j);
}
if (((i ^ j) < k) & ((i ^ j) > maxXor)) {
maxXor = (i^j);
}
}
}
printf("%d\n%d\n%d", maxAnd, maxOr, maxXor);
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
calculate_the_maximum(n, k);
return 0;
}
|
the_stack_data/121087.c | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
/*
*
*/
int testIntAvg(int first, int second, int third);
int main(int argc, char** argv)
{
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = atoi(argv[3]);
testIntAvg(a, b, c);
return 1;
}
int testIntAvg(int first, int second, int third){
int avg = 20;
printf("input state:second:%d:int,avg:%d:int,third:%d:int,first:%d:int\n", second, avg, third, first);
//int sum = first + second + third;
int sum = first + second;
avg = sum / 3;
printf("output state:second:%d:int,avg:%d:int,third:%d:int,first:%d:int\n", second, avg, third, first);
return avg;
}
|
the_stack_data/168893932.c | #include <stdio.h>
int main()
{
int ida;
printf("Digite a sua idade:");
scanf("%d", &ida);
if((ida >= 5) && (ida <=13))
printf("Você está na categoria Junior");
else if(((ida >= 14) && (ida <= 17)) || ((ida >= 31) && (ida <=150)))
printf("Você está na categoria Amador");
else if((ida >= 18) && (ida <= 30))
printf("Você está na categoria Oficial");
else
printf("Está idade não se encaixa na competição!");
return 0;
}
|
the_stack_data/541165.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
long fibonacci(unsigned i) {
if (i == 0) return 0;
if (i == 1) return 1;
return fibonacci(i-1) + fibonacci(i-2);
}
void usage() {
char buffer[80];
strcpy(buffer,"fib n\n");
write(1,buffer,strlen(buffer));
exit(1);
}
void main(int argc,char *argv[]) {
unsigned n;
long f;
char buffer[80];
if (argc != 2) usage();
n = atoi(argv[1]);
f = fibonacci(n);
sprintf(buffer,"El fibonacci de %u es %ld\n",n,f);
write(1, buffer, strlen(buffer));
}
|
the_stack_data/66832.c | /*-
* BSD LICENSE
*
* Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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>
struct toto {
int x;
int y;
};
int main(int argc, char **argv)
{
struct toto t[] = {
{ .x = 1, .y = 2 },
{ .x = 1, .y = 2 },
{ .x = 1, .y = 2 },
{ .x = 1, .y = 2 },
};
struct toto u[4];
printf("%zu %zu\n", sizeof(t), sizeof(u));
return 0;
}
|
the_stack_data/25138624.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#define error_en(msg) \
do { \
perror(msg); \
exit(EXIT_FAILURE); \
} while (0)
static void signal_handler(int signal)
{
printf("SIGALRM received\n");
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
timer_t timerid;
struct sigaction act;
struct timeval tval;
struct timezone tz;
struct itimerspec tspec;
struct sigevent evt = {
.sigev_notify = SIGEV_SIGNAL,
.sigev_signo = SIGALRM
};
if (sigaction(SIGALRM, NULL, &act))
error_en("Get old act failed");
act.sa_handler = signal_handler;
if (sigaction(SIGALRM, &act, NULL))
error_en("Set new act failed");
if (timer_create(CLOCK_REALTIME, &evt, &timerid))
error_en("Create timer failed");
if (gettimeofday(&tval, &tz))
error_en("Get time failed");
tspec.it_interval.tv_sec = tval.tv_sec + 3;
tspec.it_value = tspec.it_interval;
if (timer_settime(timerid, TIMER_ABSTIME, &tspec, NULL))
error_en("Set timer failed");
pause();
return 0;
}
|
the_stack_data/107449.c | /* $Id: getopt.c,v 1.2 2007/01/07 23:19:19 mjt Exp $
* Simple getopt() implementation.
*
* Standard interface:
* extern int getopt(int argc, char *const *argv, const char *opts);
* extern int optind; current index in argv[]
* extern char *optarg; argument for the current option
* extern int optopt; the current option
* extern int opterr; to control error printing
*
* Some minor extensions:
* ignores leading `+' sign in opts[] (unemplemented GNU extension)
* handles optional arguments, in form "x::" in opts[]
* if opts[] starts with `:', will return `:' in case of missing required
* argument, instead of '?'.
*
* Compile with -DGETOPT_NO_OPTERR to never print errors internally.
* Compile with -DGETOPT_NO_STDIO to use write() calls instead of fprintf() for
* error reporting (ignored with -DGETOPT_NO_OPTERR).
* Compile with -DGETOPT_CLASS=static to get static linkage.
* Compile with -DGETOPT_MY to redefine all visible symbols to be prefixed
* with "my_", like my_getopt instead of getopt.
* Compile with -DTEST to get a test executable.
*
* Written by Michael Tokarev. Public domain.
*/
#include <string.h>
#ifndef GETOPT_CLASS
# define GETOPT_CLASS
#endif
#ifdef GETOPT_MY
# define optarg my_optarg
# define optind my_optind
# define opterr my_opterr
# define optopt my_optopt
# define getopt my_getopt
#endif
GETOPT_CLASS char *optarg /* = NULL */;
GETOPT_CLASS int optind = 1;
GETOPT_CLASS int opterr = 1;
GETOPT_CLASS int optopt;
static char *nextc /* = NULL */;
#if defined(GETOPT_NO_OPTERR)
#define printerr(argv, msg)
#elif defined(GETOPT_NO_STDIO)
extern int write(int, void *, int);
static void printerr(char *const *argv, const char *msg) {
if (opterr) {
char buf[64];
unsigned pl = strlen(argv[0]);
unsigned ml = strlen(msg);
char *p;
if (pl + /*": "*/2 + ml + /*" -- c\n"*/6 > sizeof(buf)) {
write(2, argv[0], pl);
p = buf;
}
else {
memcpy(buf, argv[0], ml);
p = buf + pl;
}
*p++ = ':'; *p++ = ' ';
memcpy(p, msg, ml); p += ml;
*p++ = ' '; *p++ = '-'; *p++ = '-'; *p++ = ' ';
*p++ = optopt;
*p++ = '\n';
write(2, buf, p - buf);
}
}
#else
#include <stdio.h>
static void printerr(char *const *argv, const char *msg) {
if (opterr)
fprintf(stderr, "%s: %s -- %c\n", argv[0], msg, optopt);
}
#endif
GETOPT_CLASS int getopt(int argc, char *const *argv, const char *opts) {
char *p = 0;
optarg = 0;
if (*opts == '+') /* GNU extension (permutation) - isn't supported */
++opts;
if (!optind) { /* a way to reset things */
nextc = 0;
optind = 1;
}
if (!nextc || !*nextc) { /* advance to the next argv element */
/* done scanning? */
if (optind >= argc)
return -1;
/* not an optional argument */
if (argv[optind][0] != '-')
return -1;
/* bare `-' */
if (argv[optind][1] == '\0')
return -1;
/* special case `--' argument */
if (argv[optind][1] == '-' && argv[optind][2] == '\0') {
++optind;
return -1;
}
nextc = argv[optind] + 1;
}
optopt = *nextc++;
if (!*nextc)
++optind;
p = (char *)strchr(opts, optopt);
if (!p || optopt == ':') {
printerr(argv, "illegal option");
return '?';
}
if (p[1] == ':') {
if (*nextc) {
optarg = nextc;
nextc = NULL;
++optind;
}
else if (p[2] != ':') { /* required argument */
if (optind >= argc) {
printerr(argv, "option requires an argument");
return *opts == ':' ? ':' : '?';
}
else
optarg = argv[optind++];
}
}
return optopt;
}
#ifdef TEST
#include <stdio.h>
int main(int argc, char **argv) {
int c;
while((c = getopt(argc, argv, "ab:c::")) != -1) switch(c) {
case 'a':
case 'b':
case 'c':
printf("option %c %s\n", c, optarg ? optarg : "(none)");
break;
default:
return -1;
}
for(c = optind; c < argc; ++c)
printf("non-opt: %s\n", argv[c]);
return 0;
}
#endif
|
the_stack_data/95449307.c | /*@ begin PerfTuning (
def build
{
arg build_command = 'gcc -O3 -fopenmp ';
arg libs = '-lm -lrt';
}
def performance_counter
{
arg repetitions = 35;
}
def performance_params
{
# param T1_I[] = [1,16,32,64,128,256,512];
# param T1_J[] = [1,16,32,64,128,256,512];
# param T1_Ia[] = [1,64,128,256,512,1024,2048];
# param T1_Ja[] = [1,64,128,256,512,1024,2048];
param T2_I[] = [1,16,32,64,128,256,512];
param T2_J[] = [1,16,32,64,128,256,512];
param T2_Ia[] = [1,64,128,256,512,1024,2048];
param T2_Ja[] = [1,64,128,256,512,1024,2048];
param T3_I[] = [1,16,32,64,128,256,512];
param T3_J[] = [1,16,32,64,128,256,512];
param T3_Ia[] = [1,64,128,256,512,1024,2048];
param T3_Ja[] = [1,64,128,256,512,1024,2048];
# param T4_I[] = [1,16,32,64,128,256,512];
# param T4_J[] = [1,16,32,64,128,256,512];
# param T4_K[] = [1,16,32,64,128,256,512];
# param T4_Ia[] = [1,64,128,256,512,1024,2048];
# param T4_Ja[] = [1,64,128,256,512,1024,2048];
# param T4_Ka[] = [1,64,128,256,512,1024,2048];
# param U1_I[] = range(1,31);
# param U1_J[] = range(1,31);
param U2_I[] = range(1,31);
param U2_J[] = range(1,31);
param U3_I[] = range(1,31);
param U3_J[] = range(1,31);
# param U4_I[] = range(1,31);
# param U4_J[] = range(1,31);
# param U4_K[] = range(1,31);
# param RT1_I[] = [1,8,32];
# param RT1_J[] = [1,8,32];
param RT2_I[] = [1,8,32];
param RT2_J[] = [1,8,32];
param RT3_I[] = [1,8,32];
param RT3_J[] = [1,8,32];
# param RT4_I[] = [1,8,32];
# param RT4_J[] = [1,8,32];
# param RT4_K[] = [1,8,32];
}
def search
{
arg algorithm = 'Randomsearch';
arg total_runs = 10000;
}
def input_params
{
param m = 500;
param n = 500;
}
def input_vars
{
decl static double data[m+10][m+10] = random;
decl static double symmat[m+10][m+10] = random;
decl static double stddev[m+10] = random;
decl static double mean[m+10] = random;
decl double float_n = 321414134.01;
decl double eps = 0.005;
}
def validation {
arg validation_file = 'validation.c';
}
) @*/
int i, j, k;
int ii, jj, kk;
int it, jt, kt;
int iii, jjj, kkk;
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
#define sqrt_of_array_cell(x,j) sqrt(x[j])
/*@ begin Loop(
for (j = 1; j <= m; j++)
{
mean[j] = 0.0;
for (i = 1; i <= n; i++)
mean[j] += data[i][j];
mean[j] /= float_n;
}
transform Composite(
tile = [('i',T2_I,'ii'),('j',T2_J,'jj'),
(('ii','i'),T2_Ia,'iii'),(('jj','j'),T2_Ja,'jjj')],
unrolljam = (['i','j'],[U2_I,U2_J]),
regtile = (['i','j'],[RT2_I,RT2_J])
)
for (j = 1; j <= m; j++)
{
stddev[j] = 0.0;
for (i = 1; i <= n; i++)
stddev[j] += (data[i][j] - mean[j]) * (data[i][j] - mean[j]);
stddev[j] /= float_n;
stddev[j] = sqrt_of_array_cell(stddev, j);
stddev[j] = 1.0;
}
transform Composite(
tile = [('i',T3_I,'ii'),('j',T3_J,'jj'),
(('ii','i'),T3_Ia,'iii'),(('jj','j'),T3_Ja,'jjj')],
unrolljam = (['i','j'],[U3_I,U3_J]),
regtile = (['i','j'],[RT3_I,RT3_J])
)
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
{
data[i][j] -= mean[j];
data[i][j] /= sqrt(float_n) * stddev[j];
}
for (k = 1; k <= m-1; k++)
{
symmat[k][k] = 1.0;
for (j = k+1; j <= m; j++)
{
symmat[k][j] = 0.0;
for (i = 1; i <= n; i++)
symmat[k][j] += (data[i][k] * data[i][j]);
symmat[j][k] = symmat[k][j];
}
}
symmat[m][m] = 1.0;
) @*/
/*@ end @*/
/*@ end @*/
|
the_stack_data/608342.c | /*#include <stdio.h>
#include "gamecharwep.h"
#define charmax 6
void starting (gamecharwep p1list, gamecharwep p2list, int xcord, int ycord, int x2cord, int y2cord)
{
for (i = 0; i < charmax; i++)
{
p1list[i].position[0] = (char)(ycord + count + 65);
p1list[i].position[1] = (char)(xcord + offset + 65);
p2list[i].position[0] = (char)(y2cord + count + 65);
p2list[i].position[1] = (char)(x2cord + offset + 65);
if (count == 3)
{
//shift over in the x direction
offset++;
//changes position back to the same height as starting y just one square over
count = 0;
}
count++
}
}*/
|
the_stack_data/87424.c | /*
* Copyright (C) 2006 Aleksey Cheusov
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee. Permission to modify the code and to distribute modified
* code is also granted without any restrictions.
*/
#include <assert.h>
#include <wchar.h>
#include <wctype.h>
int
wcscasecmp(const wchar_t *s1, const wchar_t *s2)
{
assert(s1 != NULL);
assert(s2 != NULL);
for (;;) {
int lc1 = towlower(*s1);
int lc2 = towlower(*s2);
int diff = lc1 - lc2;
if (diff != 0)
return diff;
if (!lc1)
return 0;
++s1;
++s2;
}
}
|
the_stack_data/406544.c | int main(int argc, char **argv)
{
int i = 0;
top:
{
++i;
if(i == 5)
goto top;
if(i == 6)
goto top;
if(i == 7)
goto top;
if(i == 8)
goto top;
++i;
}
if(i < 10)
goto top;
}
|
the_stack_data/9512318.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
int n_b, n_s, n_c;
int p_b, p_s, p_c;
int qtdB = 0, qtdS = 0, qtdC = 0;
long long int r, precoReceita = 0;
long long int quantidade = 0;
char receita[105];
void main(){
gets(receita);
scanf("%d %d %d\n%d %d %d\n%lld\n", &n_b, &n_s, &n_c, &p_b, &p_s, &p_c, &r);
int i;
for(i = 0; i < strlen(receita); i++){
if(receita[i] == 'B'){
precoReceita += p_b;
qtdB++;
}
else if(receita[i] == 'S'){
precoReceita += p_s;
qtdS++;
}
else if(receita[i] == 'C'){
precoReceita += p_c;
qtdC++;
}
}
if(qtdC == 0) n_c = 0;
if(qtdB == 0) n_b = 0;
if(qtdS == 0) n_s = 0;
while( (n_b > 0 && n_s > 0) && n_c > 0 ){
if( (n_b - qtdB < 0 || n_s - qtdS < 0) || n_c - qtdC < 0 ) break;
else{
n_b -= qtdB;
n_s -= qtdS;
n_c -= qtdC;
quantidade ++;
}
}
while( (n_c > 0 || n_s > 0) || n_b > 0 ){
if(n_c < qtdC){
r = r - (qtdC - n_c)*p_c;
n_c = 0;
}
if(n_b < qtdB){
r = r - (qtdB - n_b)*p_b;
n_b = 0;
}
if(n_s < qtdS){
r = r - (qtdS - n_s)*p_s;
n_s = 0;
}
if(n_s >= qtdS) n_s -= qtdS;
if(n_c >= qtdC) n_c -= qtdC;
if(n_b >= qtdB) n_b -= qtdB;
if(r >= 0) quantidade++;
if(r <= 0) break;
}
if( (!n_c && !n_s) && !n_b ){
quantidade += (long long int) r/precoReceita;
}
printf("%lld\n", quantidade);
} |
the_stack_data/1136044.c | /*
* Date: 2012-06-03
* Author: [email protected]
*
* 2-lex ranking function: f(k, a[k], a[0], a[1048]) = (k, a[k])
*
*/
#include <stdlib.h>
extern int __VERIFIER_nondet_int(void);
int main() {
int a[1048];
int k = 0;
while (a[k] >= 0 && k < 1048) {
if (__VERIFIER_nondet_int()) {
k++;
} else {
a[k]--;
}
}
return 0;
}
|
the_stack_data/126704149.c | #include <stdio.h>//printf()
#include <stdlib.h>//malloc()
#include <math.h>//abs()
#include <time.h>//clock()
/*
vector solucion en donde se guardan las posiciones
de las piezas del tablero en donde "no se atacan entre si".
*/
int* VECTOR_SOLUCION;
int NUMERO_PIEZAS;//numero de piezas del tablero
/*
parametros:
filaActual: fila en la que se intenta colocar una nueva pieza
funcion principal en donde se verifican y optienen las posiciones del tablero en donde las piezas
no se ataquen entre si
*/
void colocaPiezas( int filaActual, int* columnas );
int* eliminaColumna( int* columnas, int j, int tam )// costo: 14 + 8n
{
int* nuevoArreglo = (int*)malloc( (tam)*sizeof(int) );// costo: 6
int k = 0;// costo: 1
for(int i = 0; i <= tam; i++)// costo: 2 + n( 2 + 6 )
{
if( columnas[i] != j )// costo: 6
{
nuevoArreglo[k++] = columnas[i];//costo: 4
}
}
return nuevoArreglo;// costo: 1
}
void mostrarVector( int* list, int tam );//muestra los valores del arreglo list
void guardaResultados( int* list, int tam );//guarda los valores del arreglo list en un archivo
/*
parametros:
numeroPiezas: el numero de piezas(Reinas) con el que se realiza el problema
tiempoEjecucion: tiempo total que realizo el algoritmo para encontrar las soluciones
guarda en un archivo el tiempo total de ejecucion que realizo el algoritmo con un determinado numero de piezas
*/
void guardaTiempoEjecucion( int numeroPiezas, double tiempoEjecucion )
{
char* cad = malloc(30);
sprintf(cad,"../tiempos/Tiempos%d.txt",numeroPiezas);
FILE* f = fopen(cad,"a");
fprintf(f,"%f\n", tiempoEjecucion );
fclose(f);
//free(f);
//f = NULL;
free(cad);
cad = NULL;
}
/*
###### ###### ######## ########### ###### #####
#### #### #### #### #### ####### ####### #####
#### ## #### #### #### ##### ##############
#### #### ############ ####### ##### #######
#### #### #### #### ########### ##### #####
*/
int numeroSoluciones = 0;
int main(int argc, char const *argv[])
{
double runTime;
clock_t _start,
_end;
NUMERO_PIEZAS = 0;
int temp;
int* columnas;
while( NUMERO_PIEZAS != -1 )
{
printf("ingresa un valor mayor a cero para n: ");
scanf("%d",&NUMERO_PIEZAS);
if( NUMERO_PIEZAS != -1 )
{
numeroSoluciones=0;
VECTOR_SOLUCION = (int*)malloc(NUMERO_PIEZAS*sizeof(int));
columnas = (int*)malloc(NUMERO_PIEZAS*sizeof(int));
for(int j = 0; j < NUMERO_PIEZAS; j++)
{
columnas[j] = j;
}
_start = clock();
colocaPiezas( NUMERO_PIEZAS - 1, columnas );//costo:
_end = clock();
runTime = (double)(_end - _start)/CLOCKS_PER_SEC;
//guardaTiempoEjecucion( i, runTime);
printf("\n\n#soluciones: %d\n",numeroSoluciones);
printf("termino test%d: %f\n\n",NUMERO_PIEZAS,runTime);
free(VECTOR_SOLUCION);
VECTOR_SOLUCION = NULL;
}
}
return 0;
}
/*
*/
void colocaPiezas( int PIEZAS_FALTANTES, int* columnas )
/* ____
| 5 si n = 0
costo: |
|7 + 23n + n^2 + 7K*(n) + n*T(n-1) si n > 0
|____
*/
{
if( PIEZAS_FALTANTES == -1 )// costo: 4 + n( 23 + n + 7K + T(n-1) )
{
/*
se encontro una nueva solucion
*/
numeroSoluciones++;
//mostrarVector( VECTOR_SOLUCION, NUMERO_PIEZAS );
//guardaResultados( VECTOR_SOLUCION, NUMERO_PIEZAS );
}
else
{
/*
recorre las columnas en donde aun no existe una pieza en el tablero
*/
int j;// costo: 1
for( j = 0; j <= PIEZAS_FALTANTES; j++)// costo: n( 23 + n + 7K + T(n-1) )
{
/*
recorre el VECTOR_SOLUCION y obtiene las columnas
de las piezas que ya estan situadas en el tablero
*/
int i;// costo: 1
int col = columnas[j];// costo: 3
for( i = NUMERO_PIEZAS - 1; i > PIEZAS_FALTANTES; i--)// costo: 7( K-n )
{
/*
verifica si la pieza nueva esta situada en una misma
diagonal que alguna pieza ya existente en el tablero
*/
if( abs( i - PIEZAS_FALTANTES ) == abs( col - VECTOR_SOLUCION[ i ] ) )// costo: 7
{
break;
}
}
if( i == PIEZAS_FALTANTES )// costo: 19 + 8n + T(n-1)
{
VECTOR_SOLUCION[ PIEZAS_FALTANTES ] = col;// costo: 2
if( PIEZAS_FALTANTES > 0 )// costo: 16 + 8n + T(n-1)
{
colocaPiezas( PIEZAS_FALTANTES - 1, eliminaColumna( columnas, col, PIEZAS_FALTANTES ) );
}
else
{
colocaPiezas( PIEZAS_FALTANTES - 1, NULL );
}
}
}
free(columnas);// costo: 1
columnas = NULL;// costo: 1
}
}
/*
*/
void mostrarVector( int* list, int tam )
{
printf("-------------\n");
int count = tam-1;
for(int i = 0; i < count; i++)
{
printf("%d,%d :: ",i,list[i]);
}
printf("%d,%d",count,list[count]);
printf("\n--------------");
printf("\n\n");
}
/*
*/
void guardaResultados( int* list, int tam )
{
char* nom = malloc(30);
sprintf(nom,"../pruebas/test_%d.txt",NUMERO_PIEZAS);
FILE* f = fopen(nom,"a");
for(int i = 0; i < tam; i++)
{
fprintf(f,"%d : ",list[i]);
}
fprintf(f,"%d ::\n",list[ tam - 1 ]);
fclose(f);
free(f);
f = NULL;
free( nom );
nom = NULL;
}
|
the_stack_data/1090873.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
printf("\n\tRunning ps command with execlp\n\n");
/*
* execlp same as exec, replace memory of the caller process.
* In other words, exec replace the current image for a new image.
*
* ps will return a snapshot of the processes.
* -ax all processes
*/
execlp("ps", "ps", "-ax", NULL);
/*
* exec overwritten program with ps.
* So, after execlp nothing of our code will be running.
* Think of it in a way that our program started, stayed, and
* then exec comes in, starts a new image, and the entire program is forgotten.
*/
printf("Done.\n");
exit(0);
} |
the_stack_data/67162.c | /* Create macros so that the matrices are stored in column-major order */
#define A(i,j) a[ (j)*lda + (i) ]
#define B(i,j) b[ (j)*ldb + (i) ]
#define C(i,j) c[ (j)*ldc + (i) ]
/* Routine for computing C = A * B + C */
void AddDot1x4( int, double *, int, double *, int, double *, int );
void MY_MMult( int m, int n, int k, double *a, int lda,
double *b, int ldb,
double *c, int ldc )
{
int i, j;
for ( j=0; j<n; j+=4 ){ /* Loop over the columns of C, unrolled by 4 */
for ( i=0; i<m; i+=1 ){ /* Loop over the rows of C */
/* Update C( i,j ), C( i,j+1 ), C( i,j+2 ), and C( i,j+3 ) in
one routine (four inner products) */
AddDot1x4( k, &A( i,0 ), lda, &B( 0,j ), ldb, &C( i,j ), ldc );
}
}
}
void AddDot1x4( int k, double *a, int lda, double *b, int ldb, double *c, int ldc )
{
/* So, this routine computes four elements of C:
C( 0, 0 ), C( 0, 1 ), C( 0, 2 ), C( 0, 3 ).
Notice that this routine is called with c = C( i, j ) in the
previous routine, so these are actually the elements
C( i, j ), C( i, j+1 ), C( i, j+2 ), C( i, j+3 )
in the original matrix C.
We next use indirect addressing */
int p;
register double
/* hold contributions to
C( 0, 0 ), C( 0, 1 ), C( 0, 2 ), C( 0, 3 ) */
c_00_reg, c_01_reg, c_02_reg, c_03_reg,
/* holds A( 0, p ) */
a_0p_reg;
double
/* Point to the current elements in the four columns of B */
*bp0_pntr, *bp1_pntr, *bp2_pntr, *bp3_pntr;
bp0_pntr = &B( 0, 0 );
bp1_pntr = &B( 0, 1 );
bp2_pntr = &B( 0, 2 );
bp3_pntr = &B( 0, 3 );
c_00_reg = 0.0;
c_01_reg = 0.0;
c_02_reg = 0.0;
c_03_reg = 0.0;
for ( p=0; p<k; p+=4 ){
a_0p_reg = A( 0, p );
c_00_reg += a_0p_reg * *bp0_pntr;
c_01_reg += a_0p_reg * *bp1_pntr;
c_02_reg += a_0p_reg * *bp2_pntr;
c_03_reg += a_0p_reg * *bp3_pntr;
a_0p_reg = A( 0, p+1 );
c_00_reg += a_0p_reg * *(bp0_pntr+1);
c_01_reg += a_0p_reg * *(bp1_pntr+1);
c_02_reg += a_0p_reg * *(bp2_pntr+1);
c_03_reg += a_0p_reg * *(bp3_pntr+1);
a_0p_reg = A( 0, p+2 );
c_00_reg += a_0p_reg * *(bp0_pntr+2);
c_01_reg += a_0p_reg * *(bp1_pntr+2);
c_02_reg += a_0p_reg * *(bp2_pntr+2);
c_03_reg += a_0p_reg * *(bp3_pntr+2);
a_0p_reg = A( 0, p+3 );
c_00_reg += a_0p_reg * *(bp0_pntr+3);
c_01_reg += a_0p_reg * *(bp1_pntr+3);
c_02_reg += a_0p_reg * *(bp2_pntr+3);
c_03_reg += a_0p_reg * *(bp3_pntr+3);
bp0_pntr+=4;
bp1_pntr+=4;
bp2_pntr+=4;
bp3_pntr+=4;
}
C( 0, 0 ) += c_00_reg;
C( 0, 1 ) += c_01_reg;
C( 0, 2 ) += c_02_reg;
C( 0, 3 ) += c_03_reg;
}
|
the_stack_data/148395.c | #include <stdio.h>
#include <ctype.h>
#define MAX 5
int comparacao(char s1[], char s2[], int n) {
int contador = 0;
for (int i = 0; i < n; i++) {
if (tolower(s1[i]) == tolower(s2[i])) contador++;
else break;
}
return contador == n;
}
int main() {
char s1_m[MAX] = {'a', 'b', 'c', 'd', 'e'}, s2_m[MAX] = {'a', 'b', 'c', 'D', 'E'};
int n_m;
printf("quantos caracteres serao verificados(max 5)\n> "); scanf("%d", &n_m);
printf("os %d primeiros caracteres dos dois vetores %ssao iguais", n_m, comparacao(s1_m, s2_m, n_m) ? "" : "nao ");
}
//https://pt.stackoverflow.com/q/139712/101
|
the_stack_data/40624.c | // The next one will be reconigzed as a macro.
// struct s (a);
int (A);
MACRO(ARGS);
int *(B);
struct s *(C);
int (a[1]);
int *(b[2]);
int (c[1][2]);
int *(d[2][3]);
int *(* const volatile * e[3]);
struct s {
int *(* const volatile * f[3][3]);
int (g[3]);
} t;
int (* volatile * (*h[1]));
|
the_stack_data/9513090.c | /* this file contains the actual definitions of */
/* the IIDs and CLSIDs */
/* link this file in with the server and any clients */
/* File created by MIDL compiler version 3.01.75 */
/* at Thu Jun 11 09:55:52 1998
*/
/* Compiler settings for AxDATLCircuit.idl:
Oicf (OptLev=i2), W1, Zp8, env=Win32, ms_ext, c_ext
error checks: none
*/
//@@MIDL_FILE_HEADING( )
#ifdef __cplusplus
extern "C"{
#endif
#ifndef __IID_DEFINED__
#define __IID_DEFINED__
typedef struct _IID
{
unsigned long x;
unsigned short s1;
unsigned short s2;
unsigned char c[8];
} IID;
#endif // __IID_DEFINED__
#ifndef CLSID_DEFINED
#define CLSID_DEFINED
typedef IID CLSID;
#endif // CLSID_DEFINED
const IID IID_IIntCircuitCtl = {0x90BB18C1,0xEF5E,0x11D1,{0xB8,0x90,0xE9,0x0C,0xF0,0x92,0x81,0x2B}};
const IID LIBID_AXDATLCIRCUITLib = {0x17EEE381,0xEDCF,0x11D1,{0xB8,0x90,0xF8,0xED,0x05,0xE1,0x95,0x2C}};
const IID DIID__IntCircuitCtlEvents = {0x844AE600,0xF2F7,0x11d1,{0xB8,0x90,0xBD,0x99,0x6E,0x57,0xC3,0x29}};
const CLSID CLSID_IntCircuitCtl = {0x90BB18C2,0xEF5E,0x11D1,{0xB8,0x90,0xE9,0x0C,0xF0,0x92,0x81,0x2B}};
#ifdef __cplusplus
}
#endif
|
the_stack_data/168892062.c | // PROGRAMA p2.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
// write(STDOUT_FILENO, "1", 1);
// printf("1");
printf("1 \n");
if (fork() > 0)
{
// write(STDOUT_FILENO, "2", 1);
// printf("2");
printf("2 \n");
// write(STDOUT_FILENO, "3", 1);
// printf("3");
printf("3 \n");
}
else
{
// write(STDOUT_FILENO, "4", 1);
// printf("4");
printf("4 \n");
// write(STDOUT_FILENO, "5", 1);
// printf("5");
printf("5 \n");
}
// write(STDOUT_FILENO, "\n", 1);
return 0;
} |
the_stack_data/540835.c | #include <stdlib.h>
double atof(const char *str)
{
return strtod(str, NULL);
}
|
the_stack_data/98568.c | #include <stdio.h>
int main() {
printf("Hello, Mooshak!");
return 0;
} |
the_stack_data/156151.c | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int value;
struct node *left;
struct node *right;
struct node *prev;
};
struct tree {
int i;
struct node *parent;
};
void init(struct tree *t) {
t->parent = NULL;
}
int insert(struct tree *t, int value){
struct node *temp;
struct node* tree_new = (struct node *) malloc(sizeof(struct node));
tree_new->value=value;
tree_new->left =NULL;
tree_new->right = NULL;
if(t->parent ==NULL){
tree_new->prev =NULL;
t->parent = tree_new;
t->i=1;
return 0;
}else {
temp = t->parent;
while (3) {
if (temp->value == value) return 1;
if (temp->right == NULL && temp->left == NULL) {
if (temp->value > value) {
temp->left = tree_new;
temp->left->prev = temp;
t->i++;
return 0;
} if(temp->value < value){
temp->right = tree_new;
temp->right->prev = temp;
t->i++;
return 0;
}
} else {
if(temp->right ==NULL && temp->value < value){
temp->right = tree_new;
temp->right->prev = temp;
t->i++;
return 0;
}if(temp->left ==NULL && temp->value > value){
temp->left = tree_new;
temp->left->prev = temp;
t->i++;
return 0;
}
} if (temp->value > value) {
temp = temp->left;
continue;
} if (temp->value < value) {
temp = temp->right;
continue;
}
}
}
return 0;
}
bool print_layer(struct node *root, int n,int j) {
if(!root) return false;
if(n==0)
{
if(j == 0 )
printf("%d",root->value);
else{
printf(" %d",root->value);
}
return root->left || root->right;
}
else
{
bool l = print_layer(root->left, n-1,1);
bool r = print_layer(root->right, n-1,1);
return l || r;
}
}
void print_layers(struct node *root) {
int n = 0;
while(print_layer(root, n,0)) ++n;
}
int main(){
int number;
struct tree root;
init(&root);
for(int i=0;i<7;i++){
scanf("%d",&number);
insert(&root,number);
}
print_layers(root.parent);
printf("\n");
return 0;
}
|
the_stack_data/885005.c | /*C program to solve tower of hanoi problem*/
#include<stdio.h>
void tower(int n,char fr,char to,char spare) //Defining tower
{
if(n==1) //Base case
{
printf("Move from %c to %c\n",fr,to); //Output
return;
}
else
tower(n-1,fr,spare,to); //Moving from from to spare
tower(1,fr,to,spare); //Moving from from to to
tower(n-1,spare,to,fr); //Moving from spare to to
} //End of tower
int main()
{
int n; //Declaration
printf("There are 3 rods A,B,C\nMoving from A to B\n");
printf("Enter no. of stacks: ");
scanf("%d",&n); //input
tower(n,'A','B','C'); //Calling tower
return 0;
} //End of main
|
the_stack_data/62638013.c | /* Triply nested loops for Vivien Maisonneuve's PhD
*
* CFG version of nested04, n is assumed positive
*/
#include <stdio.h>
#include <assert.h>
int main()
{
int i=0, j, k, l=0, n /*=10*/ ;
assert(n>0);
/*
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
l++;
*/
si: if(i>=n) goto se;
j = 0;
sj: if(j<n) { k=0; goto sk; }
i++;
goto si;
sk: if(k<n) {k++, l++; goto sk;}
j++;
goto sj;
se:
printf("l=%d\n", l);
return 0;
}
|
the_stack_data/154828372.c | /* */
/* Load the metrics tables common to TTF and OTF fonts (body). */
/* */
/* Copyright 2006-2009, 2011 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */ |
the_stack_data/842205.c | #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int retval = fork();
printf("this is executing from %d\n", retval);
if (retval == 0) {
printf("Child am first\n");
} else if (retval > 0) {
wait(NULL);
printf("I was waiting for child\n");
} else {
perror("fork failed");
}
printf("%d finishing\n", retval);
return EXIT_SUCCESS;
}
|
the_stack_data/211079778.c | #include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#define STORAGE_SIZE 320000
unsigned char *mx_hmac_sha256(const void *key, int keylen,
const unsigned char *data, int datalen,
unsigned char *result, unsigned int *resultlen) {
return HMAC(EVP_sha256(), key, keylen, data, datalen, result, resultlen);
}
char *
hex2str(const unsigned char * hex, int hex_len)
{
char *str = malloc(2*hex_len + 1);
if (!str) {
printf("OH SHIT");
fflush(stdout);
return NULL;
}
char * ptr = str;
const unsigned char * hptr = hex;
const char hex_digit[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
for (int ct = 0; ct < hex_len; ct++, hptr++) {
*ptr++ = hex_digit[*hptr >> 4];
*ptr++ = hex_digit[*hptr & 0x0f];
}
*ptr = '\0';
return str;
}
int create_key(long long job_id, char * key_path, char ** key) {
struct stat secret_st;
int secret_fd;
void *secret_addr;
int job_id_len;
char *job_id_str;
unsigned char *key_bytes = NULL;
unsigned int key_bytes_len = 0;
if ((secret_fd = open(key_path, O_RDONLY, S_IRUSR)) < 0)
{
perror("Error in private key file opening");
return EXIT_FAILURE;
}
if (fstat(secret_fd, &secret_st) < 0)
{
perror("Error in fstat");
return EXIT_FAILURE;
}
secret_addr = mmap(NULL, secret_st.st_size, PROT_READ, MAP_SHARED, secret_fd, 0);
if (secret_addr == MAP_FAILED)
{
perror("mmap");
return 30;
}
// convert job_id to str
job_id_len = snprintf(NULL, 0, "%lld", job_id);
job_id_str = malloc( job_id_len + 1 );
snprintf(job_id_str, job_id_len + 1, "%lld", job_id);
key_bytes = mx_hmac_sha256((const void *)secret_addr, secret_st.st_size, (unsigned char*)job_id_str, job_id_len + 1, key_bytes, &key_bytes_len);
*key = hex2str(key_bytes, key_bytes_len);
return 0;
}
int main(int argc, char *argv[]) {
int fd, rc;
long long job_id;
char *key;
if(argc<=2) { printf("usage: [bin] job_id /path/to/key\n"); exit(1); }
job_id = atoll(argv[1]);
rc = create_key(job_id, argv[2], &key);
if (rc != 0) {
perror("create_key");
return rc;
}
// cleanup
fd = shm_unlink(key);
if (fd == -1)
{
perror("unlink");
return 100;
}
return 0;
}
|
the_stack_data/295121.c | #include <stdio.h>
#include <string.h>
int x=1;
float f=1.0;
int main() {
int *p = &x;
float *q = &f;
_Bool b = (p == q); // free of undefined behaviour?
printf("(p==q) = %s\n", b?"true":"false");
return 0;
}
|
the_stack_data/472091.c | /**********
* ZUCC Cprograming task
* Author: Takuron@github
**********/
#include <stdio.h>
int main () {
int i;
char c;
int letter = 0, blank = 0, digit = 0, other = 0;
for(i=0;i<10;i++){
c=getchar();
if(c>='A'&&c<='Z'){
letter++;
}
else if(c>='a'&&c<='z'){
letter++;
}
else if(c>='0'&&c<='9'){
digit++;
}
else if(c==' '||c=='\n'){
blank++;
}
else{
other++;
}
}
printf("letter = %d, blank = %d, digit = %d, other = %d",letter , blank , digit , other );
}
|
the_stack_data/35079.c | int main() {
return 2 > 3;
} |
the_stack_data/906227.c | //2. 输入10个雇员的信息(姓名,工资号),安工资号排序输出。要求雇员的信息用结构体,用
//两个函数分别完成10个雇员信息的输入及排序。
#include <stdio.h>
typedef struct
{
char name[20];
int no;
} Employer;
void input(Employer* list,int max)
{
int i;
for(i=0; i<max; i++)
{
printf("请输入第%d个员工的工号,姓名(用逗号隔开)",i+1);
scanf("%d,%s",&list[i].no,list[i].name);
}
}
void output(Employer* list,int max)
{
int i;
for(i=0; i<max; i++)
printf("%d\t工号:%d\t姓名:%s\n",i+1,list[i].no,list[i].name);
}
void sort(Employer* list,int max)
{
int i,j;
for(i=0; i<max-1; i++) //only need n-1 swaps to move the smallest to the front
{
for(j=0; j<max-1; j++)
{
if(list[j].no>list[j+1].no)
{
Employer t=list[j];
list[j]=list[j+1];
list[j+1]=t;
}
}
}
}
int main()
{
int max=10;
Employer list[max];
input(list,max);
sort(list,max);
output(list,max);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.