file
stringlengths 18
26
| data
stringlengths 2
1.05M
|
---|---|
the_stack_data/508718.c | #include<stdio.h>
main()
{
char name[10];
int age=0;
long long int phone;
printf("Enter the name:");
gets(name);
printf("\nEnter the age :");
scanf("%d",&age);
printf("\nEnter the phone number :");
{
scanf("\n%lld",&phone);
}
printf(" name:%s\nage:%d\nphone number:%lld\n",name,age,phone);
return 0;
}
|
the_stack_data/234517829.c | // client.c
// Author: Allen Porter <[email protected]>
#include <assert.h>
#include <arpa/inet.h>
#include <err.h>
#include <limits.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
static void log_packet(const struct sockaddr_in* name,
int received, size_t bytes) {
printf("%ld: %c %s:%d %ld\n", time(NULL), (received ? '>' : '<'),
inet_ntoa(name->sin_addr), htons(name->sin_port), bytes);
fflush(stdout);
}
static void usage(char* argv[]) {
errx(EX_USAGE, "Usage: %s <ip> <port>", argv[0]);
}
int main(int argc, char* argv[]) {
if (argc != 3) {
usage(argv);
}
const char* ip = argv[1];
uint16_t port = strtol(argv[2], (char**)NULL, 10);
struct sockaddr_in name;
socklen_t namelen = sizeof(struct sockaddr_in);
bzero(&name, namelen);
if (inet_aton(ip, &name.sin_addr) != 1) {
usage(argv);
}
name.sin_family = AF_INET;
name.sin_port = htons(port);
int sock;
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
err(1, "socket");
}
char buf[BUFSIZ];
strncpy(buf, "some payload", BUFSIZ);
ssize_t buf_len = strlen(buf);
ssize_t nsent;
if ((nsent = sendto(sock, buf, buf_len, 0,
(const struct sockaddr*)&name, namelen)) == -1) {
err(1, "sendto");
}
log_packet(&name, 0, nsent);
while (1) {
ssize_t nread;
if ((nread = recvfrom(sock, buf, BUFSIZ - 1, MSG_WAITALL,
(struct sockaddr*)&name, &namelen)) == -1) {
err(1, "recvfrom");
}
assert(nread > 0);
assert(namelen = sizeof(struct sockaddr_in));
log_packet(&name, 1, nread);
}
return 0;
}
|
the_stack_data/81585.c | /*-
* Copyright 2018 Nicola Tuveri
*
* 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.
*
*/
/*-
* `ignore` is a dumb version of `tee`/`cat`:
* it copies from stdin to stdout, ignoring all CLI arguments.
*
* This can be useful to skip stages in a long CLI pipeline of commands,
* or when it is impossible to use comments.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#define BUF_SIZE 8192
int main(int argc, char *argv[])
{
int ret = EXIT_SUCCESS;
size_t n, wbytes, bytes_read;
char *bp;
char buffer[BUF_SIZE];
while (1) {
bytes_read = read(STDIN_FILENO, buffer, sizeof buffer);
if (bytes_read < 0 && errno == EINTR)
continue;
if (bytes_read <= 0)
break;
n = bytes_read;
bp = buffer;
do {
wbytes = write(STDOUT_FILENO, bp, n);
if (wbytes == -1) {
ret = EXIT_FAILURE;
break;
}
bp += wbytes;
} while ( n -= wbytes );
}
return ret;
}
|
the_stack_data/126876.c | #include <stdint.h>
extern int32_t SDL_main(int32_t argc, char *argv[]);
int32_t main(int32_t argc, char *argv[]) { return SDL_main(argc, argv); } |
the_stack_data/93887343.c | //Ticket lock with proportional backoff
//
//From Algorithms for Scalable Synchronization on Shared-Memory Multiprocessors, 1991 (Fig. 2).
//Also available as pseudo-code here: http://www.cs.rochester.edu/research/synchronization/pseudocode/ss.html#ticket
#include <pthread.h>
#define assume(e) __VERIFIER_assume(e)
#define assert(e) { if(!(e)) { ERROR: goto ERROR; (void)0; } }
volatile unsigned next_ticket = 0;
volatile unsigned now_serving = 0;
#define FAILED 3 //this is already and the limit of what we can handle
#define NEXT(e) ((e + 1) % FAILED)
// #define NEXT(e) ((e+1 == FAILED)?0:e+1)
unsigned __VERIFIER_atomic_fetch_and_increment__next_ticket(){
unsigned value;
if(NEXT(next_ticket) == now_serving){
value = FAILED;
}
else
{
value = next_ticket;
next_ticket = NEXT(next_ticket);
}
return value;
}
inline void acquire_lock(){
unsigned my_ticket;
my_ticket = __VERIFIER_atomic_fetch_and_increment__next_ticket(); //returns old value; arithmetic overflow is harmless (Alex: it is not if we have 2^64 threads)
if(my_ticket == FAILED){
assume(0);
}else{
while(1){
//pause(my_ticket - now_serving);
// consume this many units of time
// on most machines, subtraction works correctly despite overflow
if(now_serving == my_ticket){
break;
}
}
}
return;
}
inline void release_lock(){
now_serving++;
}
int c = 0;
void* thr1(void* arg){
acquire_lock();
c++;
assert(c == 1);
c--;
release_lock();
return 0;
}
int main(){
pthread_t t;
while(1) { pthread_create(&t, 0, thr1, 0); }
}
|
the_stack_data/122015587.c | /* Copyright (C) 1995-2019 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, August 1995.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <stdlib.h>
#define TABLE_BASE 0x2e
#define TABLE_SIZE 0x4d
#define XX ((char)0x40)
static const char a64l_table[TABLE_SIZE] = {
/* 0x2e */ 0,
1,
/* 0x30 */ 2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
XX,
XX,
XX,
XX,
XX,
XX,
/* 0x40 */ XX,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
/* 0x50 */ 27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
XX,
XX,
XX,
XX,
XX,
/* 0x60 */ XX,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
/* 0x70 */ 53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63};
long int a64l(const char* string)
{
const char* ptr = string;
unsigned long int result = 0ul;
const char* end = ptr + 6;
int shift = 0;
do
{
unsigned index;
unsigned value;
index = *ptr - TABLE_BASE;
if ((unsigned int)index >= TABLE_SIZE)
break;
value = (int)a64l_table[index];
if (value == (int)XX)
break;
++ptr;
result |= value << shift;
shift += 6;
} while (ptr != end);
return (long int)result;
}
|
the_stack_data/154830017.c | /* Copyright (C) 2014 The Regents of the University of California
* See README in this or parent directory for licensing information. */
#ifdef USE_HAL
/* snakeTrack - stuff to load and display snake type tracks in browser. */
#include "common.h"
#include "hash.h"
#include "localmem.h"
#include "linefile.h"
#include "jksql.h"
#include "hdb.h"
#include "hgTracks.h"
#include "chainBlock.h"
#include "chainLink.h"
#include "chainDb.h"
#include "chainCart.h"
#include "errCatch.h"
#include "twoBit.h"
#include "bigWarn.h"
#include <pthread.h>
#include "trackHub.h"
#include "limits.h"
#include "snakeUi.h"
#include "bits.h"
#include "halBlockViz.h"
// this is the number of pixels used by the target self-align bar
#define DUP_LINE_HEIGHT 4
struct snakeFeature
{
struct snakeFeature *next;
int start, end; /* Start/end in browser coordinates. */
int qStart, qEnd; /* query start/end */
int level; /* level in snake */
int orientation; /* strand... -1 is '-', 1 is '+' */
boolean drawn; /* did we draw this feature? */
char *qSequence; /* may have sequence, or NULL */
char *tSequence; /* may have sequence, or NULL */
char *qName; /* chrom name on other species */
unsigned pixX1, pixX2; /* pixel coordinates within window */
};
static int snakeFeatureCmpTStart(const void *va, const void *vb)
/* sort by start position on the target sequence */
{
const struct snakeFeature *a = *((struct snakeFeature **)va);
const struct snakeFeature *b = *((struct snakeFeature **)vb);
int diff = a->start - b->start;
return diff;
}
static int snakeFeatureCmpQStart(const void *va, const void *vb)
/* sort by start position on the query sequence */
{
const struct snakeFeature *a = *((struct snakeFeature **)va);
const struct snakeFeature *b = *((struct snakeFeature **)vb);
int diff = a->qStart - b->qStart;
if (diff == 0)
{
diff = a->start - b->start;
}
return diff;
}
// static machinery to calculate full and pack snake
#define NUM_LEVELS 1000
struct level
{
boolean init; /* has this level been initialized */
int orientation; /* strand.. see above */
unsigned long edge; /* the leading edge of this level */
int adjustLevel; /* used to compress out the unused levels */
boolean hasBlock; /* are there any blocks in this level */
// these fields are used to compact full snakes
unsigned *connectsToLevel; /* what levels does this level connect to */
Bits *pixels; /* keep track of what pixels are used */
struct snakeFeature *blocks; /* the ungapped blocks attached to this level */
};
static struct level Levels[NUM_LEVELS]; /* for packing the snake, not re-entrant! */
static int maxLevel = 0; /* deepest level */
/* blocks that make it through the min size filter */
static struct snakeFeature *newList = NULL;
static void clearLevels()
/* clear out the data structure that we use to calculate snakes */
{
int ii;
for(ii=0; ii < sizeof(Levels) / sizeof(Levels[0]); ii++)
Levels[ii].init = FALSE;
maxLevel = 0;
}
static void calcFullSnakeHelper(struct snakeFeature *list, int level)
// calculate a full snake
// updates global newList with unsorted blocks that pass the min
// size filter.
{
struct snakeFeature *cb = list;
struct snakeFeature *proposedList = NULL;
if (level > maxLevel)
maxLevel = level;
if (level > ArraySize(Levels))
errAbort("too many levels");
if (Levels[level].init == FALSE)
{
// initialize the level if this is the first time we've seen it
Levels[level].init = TRUE;
Levels[level].orientation = list->orientation;
if (list->orientation == -1)
Levels[level].edge = LONG_MAX; // bigger than the biggest chrom
else
Levels[level].edge = 0;
}
// now we step through the blocks and assign them to levels
struct snakeFeature *next;
struct snakeFeature *insertHead = NULL;
for(; cb; cb = next)
{
// we're going to add this block to a different list
// so keep track of the next pointer
next = cb->next;
// if this block can't fit on this level add to the insert
// list and move on to the next block
if ((Levels[level].orientation != cb->orientation) ||
((cb->orientation == 1) && (Levels[level].edge > cb->start)) ||
((cb->orientation == -1) && (Levels[level].edge < cb->end)))
{
// add this to the list of an insert
slAddHead(&insertHead, cb);
continue;
}
// the current block will fit on this level
// go ahead and deal with the blocks that wouldn't
if (insertHead)
{
// we had an insert, go ahead and calculate where that goes
slReverse(&insertHead);
calcFullSnakeHelper(insertHead, level + 1);
insertHead = NULL;
}
// assign the current block to this level
cb->level = level;
if (cb->orientation == 1)
Levels[level].edge = cb->end;
else
Levels[level].edge = cb->start;
// add this block to the list of proposed blocks for this level
slAddHead(&proposedList, cb);
}
// we're at the end of the list. Deal with any blocks
// that didn't fit on this level
if (insertHead)
{
slReverse(&insertHead);
int nextLevel = level + 1;
calcFullSnakeHelper(insertHead, nextLevel);
insertHead = NULL;
}
// do we have any proposed blocks
if (proposedList == NULL)
return;
// we parsed all the blocks in the list to see if they fit in our level
// now let's see if the list of blocks for this level is big enough
// to actually add
struct snakeFeature *temp;
double scale = scaleForWindow(insideWidth, winStart, winEnd);
int start, end;
// order the blocks so lowest start position is first
if (Levels[level].orientation == 1)
slReverse(&proposedList);
start=proposedList->start;
for(temp=proposedList; temp->next; temp = temp->next)
;
end=temp->end;
// calculate how big the string of blocks is in screen coordinates
double apparentSize = scale * (end - start);
if (apparentSize < 0)
errAbort("size of a list of blocks should not be less than zero");
// check to see if the apparent size is big enough
if (apparentSize < 1)
return;
// transfer proposedList to new block list
for(temp=proposedList; temp; temp = next)
{
next = temp->next;
temp->next = NULL;
slAddHead(&newList, temp);
}
}
struct snakeInfo
{
int maxLevel;
} snakeInfo;
static void freeFullLevels()
// free the connection levels and bitmaps for each level
{
int ii;
for(ii=0; ii <= maxLevel; ii++)
{
freez(&Levels[ii].connectsToLevel);
bitFree(&Levels[ii].pixels);
}
}
static void initializeFullLevels(struct snakeFeature *sfList)
/* initialize levels for compact snakes */
{
int ii;
for(ii=0; ii <= maxLevel; ii++)
{
Levels[ii].connectsToLevel = needMem((maxLevel+1) * sizeof(unsigned));
Levels[ii].pixels = bitAlloc(insideWidth);
Levels[ii].blocks = NULL;
}
struct snakeFeature *sf, *prev = NULL, *next;
int prevLevel = -1;
double scale = scaleForWindow(insideWidth, winStart, winEnd);
for(sf=sfList; sf; prev = sf, sf = next)
{
next = sf->next;
if (positiveRangeIntersection(sf->start, sf->end, winStart, winEnd))
{
int sClp = (sf->start < winStart) ? winStart : sf->start;
sf->pixX1 = round((sClp - winStart)*scale);
int eClp = (sf->end > winEnd) ? winEnd : sf->end;
sf->pixX2 = round((eClp - winStart)*scale);
}
else
{
sf->pixX1 = sf->pixX2 = 0;
}
bitSetRange(Levels[sf->level].pixels, sf->pixX1, sf->pixX2 - sf->pixX1);
if (prevLevel != -1)
Levels[sf->level].connectsToLevel[prevLevel] = 1;
if(next != NULL)
Levels[sf->level].connectsToLevel[next->level] = 1;
prevLevel = sf->level;
slAddHead(&Levels[sf->level].blocks, sf);
}
}
static int highestLevelBelowUs(int level)
// is there a level below us that doesn't connect to us
{
int newLevel;
// find the highest level below us that we connect to
for(newLevel = level - 1; newLevel >= 0; newLevel--)
if (Levels[level].connectsToLevel[newLevel])
break;
// if the next level is more than one below us, we may
// be able to push our blocks to it.
if ((newLevel < 0) || (newLevel + 1 == level))
return -1;
return newLevel + 1;
}
// the number of pixels we need clear on either side of the blocks we push
#define EXTRASPACE 10
static boolean checkBlocksOnLevel(int level, struct snakeFeature *sfList)
// is there enough pixels on this level to hold our blocks?
{
struct snakeFeature *sf;
for(sf=sfList; sf; sf = sf->next)
{
if (bitCountRange(Levels[level].pixels, sf->pixX1 - EXTRASPACE, (sf->pixX2 - sf->pixX1) + 2*EXTRASPACE))
return FALSE;
}
return TRUE;
}
static void collapseLevel(int oldLevel, int newLevel)
// push level up to higher level
{
struct snakeFeature *sf;
struct snakeFeature *next;
for(sf=Levels[oldLevel].blocks; sf; sf = next)
{
next = sf->next;
sf->level = newLevel;
slAddHead(&Levels[newLevel].blocks, sf);
bitSetRange(Levels[sf->level].pixels, sf->pixX1, sf->pixX2 - sf->pixX1);
}
Levels[oldLevel].blocks = NULL;
Levels[oldLevel].pixels = bitAlloc(insideWidth);
}
static void remapConnections(int oldLevel, int newLevel)
// if we've moved a level, we need to remap all the connections
{
int ii, jj;
for(ii=0; ii <= maxLevel; ii++)
{
for(jj=0; jj <= maxLevel; jj++)
{
if (Levels[ii].connectsToLevel[oldLevel])
{
Levels[ii].connectsToLevel[oldLevel] = 0;
Levels[ii].connectsToLevel[newLevel] = 1;
}
}
}
}
static struct snakeFeature *compactSnakes(struct snakeFeature *sfList)
// collapse levels that will fit on a higer level
{
int ii;
initializeFullLevels(sfList);
// start with third level to see what can be compacted
for(ii=2; ii <= maxLevel; ii++)
{
int newLevel;
// is there a level below us that doesn't connect to us
if ((newLevel = highestLevelBelowUs(ii)) > 0)
{
int jj;
for (jj=newLevel; jj < ii; jj++)
{
if (checkBlocksOnLevel(jj, Levels[ii].blocks))
{
collapseLevel(ii, jj);
remapConnections(ii, jj);
break;
}
}
}
}
// reattach blocks in the levels to linkedFeature
struct snakeFeature *newList = NULL;
for(ii=0; ii <= maxLevel; ii++)
{
newList = slCat(Levels[ii].blocks, newList);
}
slSort(&newList, snakeFeatureCmpQStart);
// figure out the new max
int newMax = 0;
for(ii=0; ii <= maxLevel; ii++)
if (Levels[ii].blocks != NULL)
newMax = ii;
freeFullLevels();
maxLevel = newMax;
return newList;
}
static void calcFullSnake(struct track *tg, void *item)
// calculate a full snake
{
struct linkedFeatures *lf = (struct linkedFeatures *)item;
// if there aren't any blocks, don't bother
if (lf->components == NULL)
return;
// we use the codons field to keep track of whether we already
// calculated the height of this snake
if (lf->codons == NULL)
{
clearLevels();
struct snakeFeature *sf;
// this will destroy lf->components, and add to newList
calcFullSnakeHelper((struct snakeFeature *)lf->components, 0);
lf->components = (struct simpleFeature *)newList;
newList = NULL;
slSort(&lf->components, snakeFeatureCmpQStart);
// now we're going to compress the levels that aren't used
// to do that, we need to see which blocks are on the screen,
// or connected to something on the screen
int oldMax = maxLevel;
clearLevels();
struct snakeFeature *prev = NULL;
for(sf=(struct snakeFeature *)lf->components; sf; prev = sf, sf = sf->next)
{
if (Levels[sf->level].init == FALSE)
{
Levels[sf->level].init = TRUE;
Levels[sf->level].orientation = sf->orientation;
Levels[sf->level].hasBlock = FALSE;
}
else
{
if (Levels[sf->level].orientation != sf->orientation)
errAbort("found snakeFeature with wrong orientation");
if ((sf->orientation == 1) && (Levels[sf->level].edge > sf->start))
errAbort("found snakeFeature that violates edge");
if ((sf->orientation == -1) && (Levels[sf->level].edge < sf->end))
errAbort("found snakeFeature that violates edge");
}
if (sf->orientation == 1)
Levels[sf->level].edge = sf->end;
else
Levels[sf->level].edge = sf->start;
if (sf->level > maxLevel)
maxLevel = sf->level;
if(positiveRangeIntersection(winStart, winEnd, sf->start, sf->end))
{
Levels[sf->level].hasBlock = TRUE;
if (sf->next != NULL)
Levels[sf->next->level].hasBlock = TRUE;
if (prev != NULL)
Levels[prev->level].hasBlock = TRUE;
}
}
// now figure out how to remap the blocks
int ii;
int count = 0;
for(ii=0; ii < oldMax + 1; ii++)
{
Levels[ii].adjustLevel = count;
if ((Levels[ii].init) && (Levels[ii].hasBlock))
count++;
}
maxLevel = count;
// remap blocks
for(sf=(struct snakeFeature *)lf->components; sf; sf = sf->next)
sf->level = Levels[sf->level].adjustLevel;
// now compact the snakes
lf->components = (void *)compactSnakes((struct snakeFeature *)lf->components);
struct snakeInfo *si;
AllocVar(si);
si->maxLevel = maxLevel;
lf->codons = (struct simpleFeature *)si;
}
}
static void calcPackSnakeHelper(struct snakeFeature *list, int level)
// calculate a packed snake
// updates global newList with unsorted blocks that pass the min
// size filter.
{
struct snakeFeature *cb = list;
struct snakeFeature *proposedList = NULL;
if (level > maxLevel)
maxLevel = level;
if (level > ArraySize(Levels))
errAbort("too many levels");
if (Levels[level].init == FALSE)
{
// initialize the level if this is the first time we've seen it
Levels[level].init = TRUE;
Levels[level].edge = 0;
}
// now we step through the blocks and assign them to levels
struct snakeFeature *next;
struct snakeFeature *insertHead = NULL;
for(; cb; cb = next)
{
// we're going to add this block to a different list
// so keep track of the next pointer
next = cb->next;
// if this block can't fit on this level add to the insert
// list and move on to the next block
if ( Levels[level].edge > cb->start)
{
// add this to the list of an insert
slAddHead(&insertHead, cb);
continue;
}
// the current block will fit on this level
// go ahead and deal with the blocks that wouldn't
if (insertHead)
{
// we had an insert, go ahead and calculate where that goes
slReverse(&insertHead);
calcPackSnakeHelper(insertHead, level + 1);
insertHead = NULL;
}
// assign the current block to this level
cb->level = level;
Levels[level].edge = cb->end;
// add this block to the list of proposed blocks for this level
slAddHead(&proposedList, cb);
}
// we're at the end of the list. Deal with any blocks
// that didn't fit on this level
if (insertHead)
{
slReverse(&insertHead);
calcPackSnakeHelper(insertHead, level + 1);
insertHead = NULL;
}
// do we have any proposed blocks
if (proposedList == NULL)
return;
// we parsed all the blocks in the list to see if they fit in our level
// now let's see if the list of blocks for this level is big enough
// to actually add
struct snakeFeature *temp;
double scale = scaleForWindow(insideWidth, winStart, winEnd);
int start, end;
// order the blocks so lowest start position is first
slReverse(&proposedList);
start=proposedList->start;
for(temp=proposedList; temp->next; temp = temp->next)
;
end=temp->end;
// calculate how big the string of blocks is in screen coordinates
double apparentSize = scale * (end - start);
if (apparentSize < 0)
errAbort("size of a list of blocks should not be less than zero");
// check to see if the apparent size is big enough
if (apparentSize < 1)
return;
// transfer proposedList to new block list
for(temp=proposedList; temp; temp = next)
{
next = temp->next;
temp->next = NULL;
slAddHead(&newList, temp);
}
}
static void calcPackSnake(struct track *tg, void *item)
{
struct linkedFeatures *lf = (struct linkedFeatures *)item;
if (lf->components == NULL)
return;
// we use the codons field to keep track of whether we already
// calculated the height of this snake
if (lf->codons == NULL)
{
clearLevels();
// this will destroy lf->components, and add to newList
calcPackSnakeHelper((struct snakeFeature *)lf->components, 0);
lf->components = (struct simpleFeature *)newList;
newList = NULL;
//slSort(&lf->components, snakeFeatureCmpQStart);
struct snakeInfo *si;
AllocVar(si);
si->maxLevel = maxLevel;
lf->codons = (struct simpleFeature *)si;
}
}
static int snakeItemHeight(struct track *tg, void *item)
// return height of a single packed snake
{
if ((item == NULL) || (tg->visibility == tvSquish) || (tg->visibility == tvDense))
return 0;
struct linkedFeatures *lf = (struct linkedFeatures *)item;
if (lf->components == NULL)
return 0;
if (tg->visibility == tvFull)
calcFullSnake(tg, item);
else if (tg->visibility == tvPack)
calcPackSnake(tg, item);
struct snakeInfo *si = (struct snakeInfo *)lf->codons;
int lineHeight = tg->lineHeight ;
int multiplier = 1;
if (tg->visibility == tvFull)
multiplier = 2;
return (si->maxLevel + 1) * (multiplier * lineHeight);
}
static int linkedFeaturesCmpScore(const void *va, const void *vb)
/* Help sort linkedFeatures by score */
{
const struct linkedFeatures *a = *((struct linkedFeatures **)va);
const struct linkedFeatures *b = *((struct linkedFeatures **)vb);
if (a->score > b->score)
return -1;
else if (a->score < b->score)
return 1;
return 0;
}
static int snakeHeight(struct track *tg, enum trackVisibility vis)
/* calculate height of all the snakes being displayed */
{
if (tg->networkErrMsg != NULL)
{
// we had a parallel load failure
tg->drawItems = bigDrawWarning;
tg->totalHeight = bigWarnTotalHeight;
return bigWarnTotalHeight(tg, vis);
}
if (vis == tvDense)
return tg->lineHeight;
if (vis == tvSquish)
return tg->lineHeight/2;
int height = DUP_LINE_HEIGHT;
struct slList *item = tg->items;
item = tg->items;
for (item=tg->items;item; item = item->next)
{
height += tg->itemHeight(tg, item);
}
return height;
}
static void snakeDraw(struct track *tg, int seqStart, int seqEnd,
struct hvGfx *hvg, int xOff, int yOff, int width,
MgFont *font, Color color, enum trackVisibility vis)
/* Draw linked features items. */
{
struct slList *item;
int y;
struct linkedFeatures *lf;
double scale = scaleForWindow(width, seqStart, seqEnd);
int height = snakeHeight(tg, vis);
hvGfxSetClip(hvg, xOff, yOff, width, height);
if ((tg->visibility == tvFull) || (tg->visibility == tvPack))
{
// score snakes by how many bases they cover
for (item = tg->items; item != NULL; item = item->next)
{
lf = (struct linkedFeatures *)item;
struct snakeFeature *sf;
lf->score = 0;
for (sf = (struct snakeFeature *)lf->components; sf != NULL; sf = sf->next)
{
lf->score += sf->end - sf->start;
}
}
slSort(&tg->items, linkedFeaturesCmpScore);
}
y = yOff;
for (item = tg->items; item != NULL; item = item->next)
{
if(tg->itemColor != NULL)
color = tg->itemColor(tg, item, hvg);
tg->drawItemAt(tg, item, hvg, xOff, y, scale, font, color, vis);
if (vis == tvFull)
y += tg->itemHeight(tg, item);
}
}
// this is a 16 color palette with every other color being a lighter version of
// the color before it
static int snakePalette2[] =
{
0x1f77b4, 0xaec7e8, 0xff7f0e, 0xffbb78, 0x2ca02c, 0x98df8a, 0xd62728, 0xff9896, 0x9467bd, 0xc5b0d5, 0x8c564b, 0xc49c94, 0xe377c2, 0xf7b6d2, 0x7f7f7f, 0xc7c7c7, 0xbcbd22, 0xdbdb8d, 0x17becf, 0x9edae5
};
static int snakePalette[] =
{
0x1f77b4, 0xff7f0e, 0x2ca02c, 0xd62728, 0x9467bd, 0x8c564b, 0xe377c2, 0x7f7f7f, 0xbcbd22, 0x17becf
};
static Color hashColor(char *name)
{
bits32 hashVal = hashString(name);
unsigned int colorInt = snakePalette2[hashVal % (sizeof(snakePalette2)/sizeof(Color))];
return MAKECOLOR_32(((colorInt >> 16) & 0xff),((colorInt >> 8) & 0xff),((colorInt >> 0) & 0xff));
}
static void boundMapBox(struct hvGfx *hvg, int start, int end, int x, int y, int width, int height,
char *track, char *item, char *statusLine, char *directUrl, boolean withHgsid,
char *extra)
// make sure start x and end x position are on the screen
// otherwise the tracking box code gets confused
{
if (x > insideWidth)
return;
if (x < 0)
{
width -= -x;
x = 0;
}
if (x + width > insideWidth)
{
width -= x + width - insideWidth;
}
mapBoxHgcOrHgGene(hvg, start, end, x, y, width, height,
track, item, statusLine, directUrl, withHgsid,
extra);
}
static void snakeDrawAt(struct track *tg, void *item,
struct hvGfx *hvg, int xOff, int y, double scale,
MgFont *font, Color color, enum trackVisibility vis)
/* Draw a single simple bed item at position. */
{
unsigned showSnpWidth = cartOrTdbInt(cart, tg->tdb,
SNAKE_SHOW_SNP_WIDTH, SNAKE_DEFAULT_SHOW_SNP_WIDTH);
struct linkedFeatures *lf = (struct linkedFeatures *)item;
if (tg->visibility == tvFull)
calcFullSnake(tg, item);
else if (tg->visibility == tvPack)
calcPackSnake(tg, item);
if (lf->components == NULL)
return;
boolean isHalSnake = lf->isHalSnake;
struct snakeFeature *sf = (struct snakeFeature *)lf->components, *prevSf = NULL;
int s = tg->itemStart(tg, item);
int sClp = (s < winStart) ? winStart : s;
int x1 = round((sClp - winStart)*scale) + xOff;
int textX = x1;
int yOff = y;
boolean withLabels = (withLeftLabels && (vis == tvFull) && !tg->drawName);
unsigned labelColor = MG_BLACK;
// draw the labels
if (withLabels)
{
char *name = tg->itemName(tg, item);
int nameWidth = mgFontStringWidth(font, name);
int dotWidth = tl.nWidth/2;
boolean snapLeft = FALSE;
boolean drawNameInverted = FALSE;
textX -= nameWidth + dotWidth;
snapLeft = (textX < insideX);
/* Special tweak for expRatio in pack mode: force all labels
* left to prevent only a subset from being placed right: */
snapLeft |= (startsWith("expRatio", tg->tdb->type));
#ifdef IMAGEv2_NO_LEFTLABEL_ON_FULL
if (theImgBox == NULL && snapLeft)
#else///ifndef IMAGEv2_NO_LEFTLABEL_ON_FULL
if (snapLeft) /* Snap label to the left. */
#endif ///ndef IMAGEv2_NO_LEFTLABEL_ON_FULL
{
textX = leftLabelX;
assert(hvgSide != NULL);
hvGfxUnclip(hvgSide);
hvGfxSetClip(hvgSide, leftLabelX, yOff, insideWidth, tg->height);
if(drawNameInverted)
{
int boxStart = leftLabelX + leftLabelWidth - 2 - nameWidth;
hvGfxBox(hvgSide, boxStart, y, nameWidth+1, tg->heightPer - 1, color);
hvGfxTextRight(hvgSide, leftLabelX, y, leftLabelWidth-1, tg->heightPer,
MG_WHITE, font, name);
}
else
hvGfxTextRight(hvgSide, leftLabelX, y, leftLabelWidth-1, tg->heightPer,
labelColor, font, name);
hvGfxUnclip(hvgSide);
hvGfxSetClip(hvgSide, insideX, yOff, insideWidth, tg->height);
}
else
{
if(drawNameInverted)
{
hvGfxBox(hvg, textX - 1, y, nameWidth+1, tg->heightPer-1, color);
hvGfxTextRight(hvg, textX, y, nameWidth, tg->heightPer, MG_WHITE, font, name);
}
else
hvGfxTextRight(hvg, textX, y, nameWidth, tg->heightPer, labelColor, font, name);
}
}
// let's draw some blue bars for the duplications
struct hal_target_dupe_list_t* dupeList = lf->dupeList;
int count = 0;
if ((tg->visibility == tvFull) || (tg->visibility == tvPack))
{
for(; dupeList ; dupeList = dupeList->next, count++)
{
struct hal_target_range_t *range = dupeList->tRange;
unsigned int colorInt = snakePalette[count % (sizeof(snakePalette)/sizeof(Color))];
Color color = MAKECOLOR_32(((colorInt >> 16) & 0xff),((colorInt >> 8) & 0xff),((colorInt >> 0) & 0xff));
for(; range; range = range->next)
{
int s = range->tStart;
int e = range->tStart + range->size;
int sClp = (s < winStart) ? winStart : s;
int eClp = (e > winEnd) ? winEnd : e;
int x1 = round((sClp - winStart)*scale) + xOff;
int x2 = round((eClp - winStart)*scale) + xOff;
hvGfxBox(hvg, x1, y , x2-x1, DUP_LINE_HEIGHT - 1 , color);
}
}
y+=DUP_LINE_HEIGHT;
}
// now we're going to draw the boxes
s = sf->start;
int lastE = -1;
int lastS = -1;
int offY = y;
int lineHeight = tg->lineHeight ;
int tStart, tEnd, qStart;
int qs, qe;
int heightPer = tg->heightPer;
int lastX = -1,lastY = y;
int lastQEnd = 0;
int lastLevel = -1;
int e;
qe = lastQEnd = 0;
for (sf = (struct snakeFeature *)lf->components; sf != NULL; lastQEnd = qe, prevSf = sf, sf = sf->next)
{
qs = sf->qStart;
qe = sf->qEnd;
if (vis == tvDense)
y = offY;
else if ((vis == tvPack) || (vis == tvSquish))
y = offY + (sf->level * 1) * lineHeight;
else if (vis == tvFull)
y = offY + (sf->level * 2) * lineHeight;
s = sf->start; e = sf->end;
tEnd = sf->end;
int osx;
int sx, ex;
if (!positiveRangeIntersection(winStart, winEnd, s, e))
continue;
osx = sx = round((double)((int)s-winStart)*scale) + xOff;
ex = round((double)((int)e-winStart)*scale) + xOff;
// color by strand
static Color darkBlueColor = 0;
static Color darkRedColor = 0;
if (darkRedColor == 0)
{
//the light blue: rgb(149, 204, 252)
//the light red: rgb(232, 156, 156)
darkRedColor = hvGfxFindColorIx(hvg, 232,156,156);
darkBlueColor = hvGfxFindColorIx(hvg, 149,204,252);
}
char *colorBy = cartOrTdbString(cart, tg->tdb,
SNAKE_COLOR_BY, SNAKE_DEFAULT_COLOR_BY);
extern Color getChromColor(char *name, struct hvGfx *hvg);
if (sameString(colorBy, SNAKE_COLOR_BY_STRAND_VALUE))
color = (sf->orientation == -1) ? darkRedColor : darkBlueColor;
else if (sameString(colorBy, SNAKE_COLOR_BY_CHROM_VALUE))
color = hashColor(sf->qName);
else
color = darkBlueColor;
int w = ex - sx;
if (w == 0)
w = 1;
assert(w > 0);
char buffer[1024];
if (vis == tvFull)
safef(buffer, sizeof buffer, "%d-%d",sf->qStart,sf->qEnd);
else
safef(buffer, sizeof buffer, "%s:%d-%d",sf->qName,sf->qStart,sf->qEnd);
if (sx < insideX)
{
int olap = insideX - sx;
sx = insideX;
w -= olap;
}
char qAddress[4096];
if ((vis == tvFull) || (vis == tvPack) )
{
safef(qAddress, sizeof qAddress, "qName=%s&qs=%d&qe=%d&qWidth=%d",sf->qName, qs, qe, winEnd - winStart);
boundMapBox(hvg, s, e, sx+1, y, w-2, heightPer, tg->track,
buffer, buffer, NULL, TRUE, qAddress);
}
hvGfxBox(hvg, sx, y, w, heightPer, color);
// now draw the mismatches if we're at high enough resolution
if ((isHalSnake && sf->qSequence != NULL) && (winBaseCount < showSnpWidth) && ((vis == tvFull) || (vis == tvPack)))
{
char *twoBitString = trackDbSetting(tg->tdb, "twoBit");
static struct twoBitFile *tbf = NULL;
static char *lastTwoBitString = NULL;
static struct dnaSeq *seq = NULL;
static char *lastQName = NULL;
// sequence for chain snakes is in 2bit files which we cache
if (!isHalSnake)
{
if (twoBitString == NULL)
twoBitString = "/gbdb/hg19/hg19.2bit";
if ((lastTwoBitString == NULL) ||
differentString(lastTwoBitString, twoBitString))
{
if (tbf != NULL)
{
lastQName = NULL;
twoBitClose(&tbf);
}
tbf = twoBitOpen(twoBitString);
}
// we're reading in the whole chrom
if ((lastQName == NULL) || differentString(sf->qName, lastQName))
seq = twoBitReadSeqFrag(tbf, sf->qName, 0, 0);
lastQName = sf->qName;
lastTwoBitString = twoBitString;
}
char *ourDna;
if (isHalSnake)
ourDna = sf->qSequence;
else
ourDna = &seq->dna[sf->qStart];
int seqLen = sf->qEnd - sf->qStart;
toUpperN(ourDna, seqLen);
if (!isHalSnake && (sf->orientation == -1))
reverseComplement(ourDna,seqLen);
// get the reference sequence
char *refDna;
if (isHalSnake)
{
refDna = sf->tSequence;
}
else
{
struct dnaSeq *extraSeq = hDnaFromSeq(database, chromName, sf->start, sf->end, dnaUpper);
refDna = extraSeq->dna;
}
int si = s;
char *ptr1 = refDna;
char *ptr2 = ourDna;
for(; si < e; si++,ptr1++,ptr2++)
{
// if mismatch! If reference is N ignore, if query is N, paint yellow
if ( (*ptr1 != *ptr2) && !((*ptr1 == 'N') || (*ptr1 == 'n')))
{
int misX1 = round((double)((int)si-winStart)*scale) + xOff;
int misX2 = round((double)((int)(si+1)-winStart)*scale) + xOff;
int w1 = misX2 - misX1;
if (w1 < 1)
w1 = 1;
Color boxColor = MG_RED;
if ((*ptr2 == 'N') || (*ptr2 == 'n'))
boxColor = hvGfxFindRgb(hvg, &undefinedYellowColor);
hvGfxBox(hvg, misX1, y, w1, heightPer, boxColor);
}
}
// if we're zoomed to base level, draw sequence of mismatch
if (zoomedToBaseLevel)
{
int mysx = round((double)((int)s-winStart)*scale) + xOff;
int myex = round((double)((int)e-winStart)*scale) + xOff;
int myw = myex - mysx;
spreadAlignString(hvg, mysx, y, myw, heightPer, MG_WHITE, font, ourDna,
refDna, seqLen, TRUE, FALSE);
}
}
sf->drawn = TRUE;
tEnd = e;
tStart = s;
qStart = sf->qStart;
lastY = y;
lastLevel = sf->level;
//lastX = x;
}
if (vis != tvFull)
return;
// now we're going to draw the lines between the blocks
lastX = -1,lastY = y;
lastQEnd = 0;
lastLevel = 0;
qe = lastQEnd = 0;
prevSf = NULL;
for (sf = (struct snakeFeature *)lf->components; sf != NULL; lastQEnd = qe, prevSf = sf, sf = sf->next)
{
int y1, y2;
int sx, ex;
qs = sf->qStart;
qe = sf->qEnd;
if (lastLevel == sf->level)
{
y1 = offY + (lastLevel * 2) * lineHeight + lineHeight/2;
y2 = offY + (sf->level * 2) * lineHeight + lineHeight/2;
}
else if (lastLevel > sf->level)
{
y1 = offY + (lastLevel * 2 ) * lineHeight;
y2 = offY + (sf->level * 2 + 1) * lineHeight + lineHeight/3;
}
else
{
y1 = offY + (lastLevel * 2 + 1) * lineHeight - 1;
y2 = offY + (sf->level * 2 ) * lineHeight - lineHeight/3;;
}
s = sf->start; e = sf->end;
sx = round((double)((int)s-winStart)*scale) + xOff;
ex = round((double)((int)e-winStart)*scale) + xOff;
color = (sf->orientation == -1) ? MG_RED : MG_BLUE;
if (lastX != -1)
{
char buffer[1024];
#define MG_ORANGE 0xff0082E6
int color = MG_GRAY;
if (lastQEnd != qs)
color = MG_ORANGE;
// draw the vertical orange bars if there is an insert in the other sequence
if ((winBaseCount < showSnpWidth) )
{
if ((sf->orientation == 1) && (qs != lastQEnd) && (lastE == s))
{
hvGfxLine(hvg, sx, y2 - lineHeight/2 , sx, y2 + lineHeight/2, MG_ORANGE);
safef(buffer, sizeof buffer, "%dbp", qs - lastQEnd);
boundMapBox(hvg, s, e, sx, y2 - lineHeight/2, 1, lineHeight, tg->track,
"foo", buffer, NULL, TRUE, NULL);
}
else if ((sf->orientation == -1) && (qs != lastQEnd) && (lastS == e))
{
hvGfxLine(hvg, ex, y2 - lineHeight/2 , ex, y2 + lineHeight/2, MG_ORANGE);
safef(buffer, sizeof buffer, "%dbp", qs - lastQEnd);
boundMapBox(hvg, s, e, ex, y2 - lineHeight/2, 1, lineHeight, tg->track,
"foo", buffer, NULL, TRUE, NULL);
}
}
// now draw the lines between blocks
if ((!((lastX == sx) && (y1 == y2))) &&
(sf->drawn || ((prevSf != NULL) && (prevSf->drawn))) &&
(((lastE >= winStart) && (lastE <= winEnd)) ||
((s > winStart) && (s < winEnd))))
{
if (lastLevel == sf->level)
{
safef(buffer, sizeof buffer, "%dbp", qs - lastQEnd);
if (sf->orientation == -1)
{
if (lastX != ex)
{
hvGfxLine(hvg, ex, y1, lastX, y2, color);
boundMapBox(hvg, s, e, ex, y1, lastX-ex, 1, tg->track,
"", buffer, NULL, TRUE, NULL);
}
}
else
{
if (lastX != sx)
{
hvGfxLine(hvg, lastX, y1, sx, y2, color);
boundMapBox(hvg, s, e, lastX, y1, sx-lastX, 1, tg->track,
"", buffer, NULL, TRUE, NULL);
}
}
}
else if (lastLevel > sf->level)
{
hvGfxLine(hvg, lastX, y1, sx, y2, color);
hvGfxLine(hvg, sx, y2, sx, y2 - lineHeight - lineHeight/3, color);
char buffer[1024];
safef(buffer, sizeof buffer, "%d-%d %dbp gap",prevSf->qStart,prevSf->qEnd, qs - lastQEnd);
boundMapBox(hvg, s, e, sx, y2 - lineHeight - lineHeight/3, 2, lineHeight + lineHeight/3, tg->track,
"", buffer, NULL, TRUE, NULL);
}
else
{
char buffer[1024];
safef(buffer, sizeof buffer, "%d-%d %dbp gap",prevSf->qStart,prevSf->qEnd, qs - lastQEnd);
if (sf->orientation == -1)
{
hvGfxLine(hvg, lastX-1, y1, ex, y2, color);
hvGfxLine(hvg, ex, y2, ex, y2 + lineHeight , color);
boundMapBox(hvg, s, e, ex-1, y2, 2, lineHeight , tg->track,
"", buffer, NULL, TRUE, NULL);
}
else
{
hvGfxLine(hvg, lastX-1, y1, sx, y2, color);
hvGfxLine(hvg, sx, y2, sx, y2 + lineHeight , color);
boundMapBox(hvg, s, e, sx-1, y2, 2, lineHeight , tg->track,
"", buffer, NULL, TRUE, NULL);
}
}
}
}
tEnd = e;
tStart = s;
qStart = sf->qStart;
if (sf->orientation == -1)
lastX = sx;
else
lastX = ex;
lastS = s;
lastE = e;
lastLevel = sf->level;
lastQEnd = qe;
}
}
void halSnakeLoadItems(struct track *tg)
// load up a snake from a HAL file. This code is called in threads
// so *no* use of globals please. All but full snakes are read into a single
// linked feature.
{
unsigned showSnpWidth = cartOrTdbInt(cart, tg->tdb,
SNAKE_SHOW_SNP_WIDTH, SNAKE_DEFAULT_SHOW_SNP_WIDTH);
// if we have a network error we want to put out a message about it
struct errCatch *errCatch = errCatchNew();
if (errCatchStart(errCatch))
{
char *fileName = trackDbSetting(tg->tdb, "bigDataUrl");
char *otherSpecies = trackDbSetting(tg->tdb, "otherSpecies");
char *errString;
int handle = halOpenLOD(fileName, &errString);
if (handle < 0)
warn("HAL open error: %s\n", errString);
boolean isPackOrFull = (tg->visibility == tvFull) ||
(tg->visibility == tvPack);
hal_dup_type_t dupMode = (isPackOrFull) ? HAL_QUERY_AND_TARGET_DUPS :
HAL_QUERY_DUPS;
hal_seqmode_type_t needSeq = isPackOrFull && (winBaseCount < showSnpWidth) ? HAL_LOD0_SEQUENCE : HAL_NO_SEQUENCE;
int mapBackAdjacencies = (tg->visibility == tvFull);
char codeVarName[1024];
safef(codeVarName, sizeof codeVarName, "%s.coalescent", tg->tdb->track);
char *coalescent = cartOptionalString(cart, codeVarName);
struct hal_block_results_t *head = halGetBlocksInTargetRange(handle, otherSpecies, trackHubSkipHubName(database), chromName, winStart, winEnd, 0, needSeq, dupMode,mapBackAdjacencies, coalescent, &errString);
// did we get any blocks from HAL
if (head == NULL)
{
warn("HAL get blocks error: %s\n", errString);
errCatchEnd(errCatch);
return;
}
struct hal_block_t* cur = head->mappedBlocks;
struct linkedFeatures *lf = NULL;
struct hash *qChromHash = newHash(5);
struct linkedFeatures *lfList = NULL;
char buffer[4096];
#ifdef NOTNOW
struct hal_target_dupe_list_t* targetDupeBlocks = head->targetDupeBlocks;
for(;targetDupeBlocks; targetDupeBlocks = targetDupeBlocks->next)
{
printf("<br>id: %d qChrom %s\n", targetDupeBlocks->id, targetDupeBlocks->qChrom);
struct hal_target_range_t *range = targetDupeBlocks->tRange;
for(; range; range = range->next)
{
printf("<br> %ld : %ld\n", range->tStart, range->size);
}
}
#endif
while (cur)
{
struct hashEl* hel;
if (tg->visibility == tvFull)
safef(buffer, sizeof buffer, "%s", cur->qChrom);
else
{
// make sure the block is on the screen
if (!positiveRangeIntersection(winStart, winEnd, cur->tStart, cur->tStart + cur->size))
{
cur = cur->next;
continue;
}
safef(buffer, sizeof buffer, "allInOne");
}
if ((hel = hashLookup(qChromHash, buffer)) == NULL)
{
AllocVar(lf);
lf->isHalSnake = TRUE;
slAddHead(&lfList, lf);
lf->start = 0;
lf->end = 1000000000;
lf->grayIx = maxShade;
lf->name = cloneString(buffer);
lf->extra = cloneString(buffer);
lf->orientation = (cur->strand == '+') ? 1 : -1;
hashAdd(qChromHash, lf->name, lf);
// now figure out where the duplication bars go
struct hal_target_dupe_list_t* targetDupeBlocks = head->targetDupeBlocks;
if ((tg->visibility == tvPack) || (tg->visibility == tvFull))
for(;targetDupeBlocks; targetDupeBlocks = targetDupeBlocks->next)
{
if ((tg->visibility == tvPack) ||
((tg->visibility == tvFull) &&
(sameString(targetDupeBlocks->qChrom, cur->qChrom))))
{
struct hal_target_dupe_list_t* dupeList;
AllocVar(dupeList);
*dupeList = *targetDupeBlocks;
slAddHead(&lf->dupeList, dupeList);
// TODO: should clone the target_range structures
// rather than copying them
}
}
}
else
{
lf = hel->val;
}
struct snakeFeature *sf;
AllocVar(sf);
slAddHead(&lf->components, sf);
sf->start = cur->tStart;
sf->end = cur->tStart + cur->size;
sf->qStart = cur->qStart;
sf->qEnd = cur->qStart + cur->size;
sf->orientation = (cur->strand == '+') ? 1 : -1;
sf->tSequence = cloneString(cur->tSequence);
sf->qSequence = cloneString(cur->qSequence);
if (sf->tSequence != NULL)
toUpperN(sf->tSequence, strlen(sf->tSequence));
if (sf->qSequence != NULL)
toUpperN(sf->qSequence, strlen(sf->qSequence));
sf->qName = cur->qChrom;
cur = cur->next;
}
if (tg->visibility == tvFull)
{
for(lf=lfList; lf ; lf = lf->next)
{
slSort(&lf->components, snakeFeatureCmpQStart);
}
}
else if ((tg->visibility == tvPack) && (lfList != NULL))
{
assert(lfList->next == NULL);
slSort(&lfList->components, snakeFeatureCmpTStart);
}
//halFreeBlocks(head);
//halClose(handle, myThread);
tg->items = lfList;
}
errCatchEnd(errCatch);
if (errCatch->gotError)
{
tg->networkErrMsg = cloneString(errCatch->message->string);
tg->drawItems = bigDrawWarning;
tg->totalHeight = bigWarnTotalHeight;
}
errCatchFree(&errCatch);
}
void halSnakeDrawLeftLabels(struct track *tg, int seqStart, int seqEnd,
struct hvGfx *hvg, int xOff, int yOff, int width, int height,
boolean withCenterLabels, MgFont *font,
Color color, enum trackVisibility vis)
/* Draw left label (shortLabel) in pack and dense modes. */
{
if ((vis == tvDense) || (vis == tvPack))
{
hvGfxSetClip(hvgSide, leftLabelX, yOff + tg->lineHeight, insideWidth, tg->height);
hvGfxTextRight(hvgSide, leftLabelX, yOff + tg->lineHeight, leftLabelWidth-1, tg->lineHeight,
color, font, tg->shortLabel);
hvGfxUnclip(hvgSide);
}
}
void halSnakeMethods(struct track *tg, struct trackDb *tdb,
int wordCount, char *words[])
{
linkedFeaturesMethods(tg);
tg->canPack = tdb->canPack = TRUE;
tg->loadItems = halSnakeLoadItems;
tg->drawItems = snakeDraw;
tg->mapItemName = lfMapNameFromExtra;
tg->subType = lfSubChain;
//tg->extraUiData = (void *) chainCart;
tg->totalHeight = snakeHeight;
tg->drawLeftLabels = halSnakeDrawLeftLabels;
tg->drawItemAt = snakeDrawAt;
tg->itemHeight = snakeItemHeight;
}
#endif // USE_HAL
#ifdef NOTNOW
// from here down are routines to support the visualization of chains as snakes
// this code is currently BROKEN, and may be removed completely in the future
struct cartOptions
{
enum chainColorEnum chainColor; /* ChromColors, ScoreColors, NoColors */
int scoreFilter ; /* filter chains by score if > 0 */
};
// mySQL code to read in chains
static void doQuery(struct sqlConnection *conn, char *fullName,
struct lm *lm, struct hash *hash,
int start, int end, boolean isSplit, int chainId)
/* doQuery- check the database for chain elements between
* start and end. Use the passed hash to resolve chain
* id's and place the elements into the right
* linkedFeatures structure
*/
{
struct sqlResult *sr = NULL;
char **row;
struct linkedFeatures *lf;
struct snakeFeature *sf;
struct dyString *query = newDyString(1024);
char *force = "";
if (isSplit)
force = "force index (bin)";
if (chainId == -1)
sqlDyStringPrintf(query,
"select chainId,tStart,tEnd,qStart from %sLink %-s where ",
fullName, force);
else
sqlDyStringPrintf(query,
"select chainId, tStart,tEnd,qStart from %sLink where chainId=%d and ",
fullName, chainId);
if (!isSplit)
sqlDyStringPrintf(query, "tName='%s' and ", chromName);
hAddBinToQuery(start, end, query);
dyStringPrintf(query, "tStart<%u and tEnd>%u", end, start);
sr = sqlGetResult(conn, query->string);
/* Loop through making up simple features and adding them
* to the corresponding linkedFeature. */
while ((row = sqlNextRow(sr)) != NULL)
{
lf = hashFindVal(hash, row[0]);
if (lf != NULL)
{
struct chain *pChain = lf->extra;
lmAllocVar(lm, sf);
sf->start = sqlUnsigned(row[1]);
sf->end = sqlUnsigned(row[2]);
sf->qStart = sqlUnsigned(row[3]);
sf->qEnd = sf->qStart + (sf->end - sf->start);
if ((pChain) && pChain->qStrand == '-')
{
int temp;
temp = sf->qStart;
sf->qStart = pChain->qSize - sf->qEnd;
sf->qEnd = pChain->qSize - temp;
}
sf->orientation = lf->orientation;
slAddHead(&lf->components, sf);
}
}
sqlFreeResult(&sr);
dyStringFree(&query);
}
static void fixItems(struct linkedFeatures *lf)
// put all chain blocks from a single query chromosome into one
// linkedFeatures structure
{
struct linkedFeatures *firstLf, *next;
struct snakeFeature *sf, *nextSf;
firstLf = lf;
for (;lf; lf = next)
{
next = lf->next;
if (!sameString(firstLf->name, lf->name) && (lf->components != NULL))
{
slSort(&firstLf->components, snakeFeatureCmpQStart);
firstLf = lf;
}
for (sf = (struct snakeFeature *)lf->components; sf != NULL; sf = nextSf)
{
sf->qName = lf->name;
sf->orientation = lf->orientation;
nextSf = sf->next;
if (firstLf != lf)
{
lf->components = NULL;
slAddHead(&firstLf->components, sf);
}
}
}
if (firstLf != NULL)
{
slSort(&firstLf->components, snakeFeatureCmpQStart);
firstLf->next = 0;
}
}
static void loadLinks(struct track *tg, int seqStart, int seqEnd,
enum trackVisibility vis)
// load up the chain elements into linkedFeatures
{
int start, end, extra;
char fullName[64];
int maxOverLeft = 0, maxOverRight = 0;
int overLeft, overRight;
struct linkedFeatures *lf;
struct lm *lm;
struct hash *hash; /* Hash of chain ids. */
struct sqlConnection *conn;
lm = lmInit(1024*4);
hash = newHash(0);
conn = hAllocConn(database);
/* Make up a hash of all linked features keyed by
* id, which is held in the extras field. */
for (lf = tg->items; lf != NULL; lf = lf->next)
{
char buf[256];
struct chain *pChain = lf->extra;
safef(buf, sizeof(buf), "%d", pChain->id);
hashAdd(hash, buf, lf);
overRight = lf->end - seqEnd;
if (overRight > maxOverRight)
maxOverRight = overRight;
overLeft = seqStart - lf->start ;
if (overLeft > maxOverLeft)
maxOverLeft = overLeft;
}
if (hash->size)
{
boolean isSplit = TRUE;
/* Make up range query. */
safef(fullName, sizeof fullName, "%s_%s", chromName, tg->table);
if (!hTableExists(database, fullName))
{
strcpy(fullName, tg->table);
isSplit = FALSE;
}
/* in dense mode we don't draw the lines
* so we don't need items off the screen
*/
if (vis == tvDense)
doQuery(conn, fullName, lm, hash, seqStart, seqEnd, isSplit, -1);
else
{
/* if chains extend beyond edge of window we need to get
* elements that are off the screen
* in both directions so we know whether to draw
* one or two lines to the edge of the screen.
*/
#define STARTSLOP 0
#define MULTIPLIER 10
#define MAXLOOK 100000
extra = (STARTSLOP < maxOverLeft) ? STARTSLOP : maxOverLeft;
start = seqStart - extra;
extra = (STARTSLOP < maxOverRight) ? STARTSLOP : maxOverRight;
end = seqEnd + extra;
doQuery(conn, fullName, lm, hash, start, end, isSplit, -1);
}
}
hFreeConn(&conn);
}
void snakeLoadItems(struct track *tg)
// Load chains from a mySQL database
{
char *track = tg->table;
struct chain chain;
int rowOffset;
char **row;
struct sqlConnection *conn = hAllocConn(database);
struct sqlResult *sr = NULL;
struct linkedFeatures *list = NULL, *lf;
int qs;
char optionChr[128]; /* Option - chromosome filter */
char *optionChrStr;
char extraWhere[128] ;
struct cartOptions *chainCart;
struct chain *pChain;
chainCart = (struct cartOptions *) tg->extraUiData;
safef( optionChr, sizeof(optionChr), "%s.chromFilter", tg->table);
optionChrStr = cartUsualString(cart, optionChr, "All");
int ourStart = winStart;
int ourEnd = winEnd;
// we're grabbing everything now.. we really should be
// doing this as a preprocessing stage, rather than at run-time
ourStart = 0;
ourEnd = 500000000;
//ourStart = winStart;
//ourEnd = winEnd;
if (startsWith("chr",optionChrStr))
{
safef(extraWhere, sizeof(extraWhere),
"qName = \"%s\" and score > %d",optionChrStr,
chainCart->scoreFilter);
sr = hRangeQuery(conn, track, chromName, ourStart, ourEnd,
extraWhere, &rowOffset);
}
else
{
if (chainCart->scoreFilter > 0)
{
safef(extraWhere, sizeof(extraWhere),
"score > \"%d\"",chainCart->scoreFilter);
sr = hRangeQuery(conn, track, chromName, ourStart, ourEnd,
extraWhere, &rowOffset);
}
else
{
safef(extraWhere, sizeof(extraWhere), " ");
sr = hRangeQuery(conn, track, chromName, ourStart, ourEnd,
NULL, &rowOffset);
}
}
while ((row = sqlNextRow(sr)) != NULL)
{
chainHeadStaticLoad(row + rowOffset, &chain);
AllocVar(pChain);
*pChain = chain;
AllocVar(lf);
lf->start = lf->tallStart = chain.tStart;
lf->end = lf->tallEnd = chain.tEnd;
lf->grayIx = maxShade;
if (chainCart->chainColor == chainColorScoreColors)
{
float normScore = sqlFloat((row+rowOffset)[11]);
lf->grayIx = (int) ((float)maxShade * (normScore/100.0));
if (lf->grayIx > (maxShade+1)) lf->grayIx = maxShade+1;
lf->score = normScore;
}
else
lf->score = chain.score;
lf->filterColor = -1;
if (chain.qStrand == '-')
{
lf->orientation = -1;
qs = chain.qSize - chain.qEnd;
}
else
{
lf->orientation = 1;
qs = chain.qStart;
}
char buffer[1024];
safef(buffer, sizeof(buffer), "%s", chain.qName);
lf->name = cloneString(buffer);
lf->extra = pChain;
slAddHead(&list, lf);
}
/* Make sure this is sorted if in full mode. Sort by score when
* coloring by score and in dense */
if (tg->visibility != tvDense)
slSort(&list, linkedFeaturesCmpStart);
else if ((tg->visibility == tvDense) &&
(chainCart->chainColor == chainColorScoreColors))
slSort(&list, chainCmpScore);
else
slReverse(&list);
tg->items = list;
/* Clean up. */
sqlFreeResult(&sr);
hFreeConn(&conn);
/* now load the items */
loadLinks(tg, ourStart, ourEnd, tg->visibility);
lf=tg->items;
fixItems(lf);
} /* chainLoadItems() */
void snakeMethods(struct track *tg, struct trackDb *tdb,
int wordCount, char *words[])
/* Fill in custom parts of alignment chains. */
{
struct cartOptions *chainCart;
AllocVar(chainCart);
boolean normScoreAvailable = chainDbNormScoreAvailable(tdb);
/* what does the cart say about coloring option */
chainCart->chainColor = chainFetchColorOption(cart, tdb, FALSE);
chainCart->scoreFilter = cartUsualIntClosestToHome(cart, tdb,
FALSE, SCORE_FILTER, 0);
linkedFeaturesMethods(tg);
tg->itemColor = lfChromColor; /* default coloring option */
/* if normScore column is available, then allow coloring */
if (normScoreAvailable)
{
switch (chainCart->chainColor)
{
case (chainColorScoreColors):
tg->itemColor = chainScoreColor;
tg->colorShades = shadesOfGray;
break;
case (chainColorNoColors):
setNoColor(tg);
break;
default:
case (chainColorChromColors):
break;
}
}
else
{
char option[128]; /* Option - rainbow chromosome color */
char *optionStr; /* this old option was broken before */
safef(option, sizeof(option), "%s.color", tg->table);
optionStr = cartUsualString(cart, option, "on");
if (differentWord("on",optionStr))
{
setNoColor(tg);
chainCart->chainColor = chainColorNoColors;
}
else
chainCart->chainColor = chainColorChromColors;
}
tg->canPack = FALSE;
tg->loadItems = snakeLoadItems;
tg->drawItems = snakeDraw;
tg->mapItemName = lfMapNameFromExtra;
tg->subType = lfSubChain;
tg->extraUiData = (void *) chainCart;
tg->totalHeight = snakeHeight;
tg->drawItemAt = snakeDrawAt;
tg->itemHeight = snakeItemHeight;
}
static Color chainScoreColor(struct track *tg, void *item, struct hvGfx *hvg)
{
struct linkedFeatures *lf = (struct linkedFeatures *)item;
return(tg->colorShades[lf->grayIx]);
}
static Color chainNoColor(struct track *tg, void *item, struct hvGfx *hvg)
{
return(tg->ixColor);
}
static void setNoColor(struct track *tg)
{
tg->itemColor = chainNoColor;
tg->color.r = 0;
tg->color.g = 0;
tg->color.b = 0;
tg->altColor.r = 127;
tg->altColor.g = 127;
tg->altColor.b = 127;
tg->ixColor = MG_BLACK;
tg->ixAltColor = MG_GRAY;
}
#endif
|
the_stack_data/1095709.c | #include <math.h>
#include <stdio.h>
int
main (void)
{
double x = sqrt (2.0);
printf ("The square root of 2.0 is %f\n", x);
return 0;
} |
the_stack_data/92326547.c | /* Test whether bit field boundaries aren't advanced if bit field type
has alignment large enough. */
extern void abort (void);
extern void exit (int);
struct A {
unsigned short a : 5;
unsigned short b : 5;
unsigned short c : 6;
};
struct B {
unsigned short a : 5;
unsigned short b : 3;
unsigned short c : 8;
};
int main ()
{
/* If short is not at least 16 bits wide, don't test anything. */
if ((unsigned short) 65521 != 65521)
exit (0);
if (sizeof (struct A) != sizeof (struct B))
abort ();
exit (0);
}
|
the_stack_data/51700219.c | int main() {
char out = 0x55;
__asm__("movl $0x42, %%eax; cmpl $0x24, %%eax; setc %%al" : "=a"(out));
return out;
}
|
the_stack_data/232955143.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strlen.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aborboll <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/09 13:30:39 by aborboll #+# #+# */
/* Updated: 2019/09/10 13:18:37 by aborboll ### ########.fr */
/* */
/* ************************************************************************** */
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i] != 0)
i++;
return (i);
}
|
the_stack_data/64199358.c | ////////////////////////////////////////////////////////////////////////////
//
// Function Name : Difference()
// Description : accept string from user and return frequency of small characters and capital characters
// Input : Integer, String
// Output : Integer, String
// Author : Prasad Dangare
// Date : 23 Mar 2021
//
////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
int Difference(char *str)
{
int iCnt = 0, iCnt2 = 0;
if(str == NULL)
{
return 0;
}
while(*str != '\0')
{
if(*str >= 'A' && *str <= 'Z')
{
iCnt++;
}
else if(*str >= 'a' && *str <= 'z')
{
iCnt2++;
}
str++;
}
return iCnt2 - iCnt;
}
int main()
{
char arr[20];
int iRet = 0;
printf("Enter the string : ");
scanf("%[^'\n']s", arr);
iRet = Difference(arr);
printf(" Difference is : %d", iRet);
return 0;
} |
the_stack_data/145451780.c | /* Test generation of maclhw on 405. */
/* Origin: Joseph Myers <[email protected]> */
/* { dg-do compile } */
/* { dg-require-effective-target ilp32 } */
/* { dg-options "-O2 -mcpu=405" } */
/* { dg-final { scan-assembler "maclhw " } } */
int
f(int a, int b, int c)
{
a += (short)b * (short)c;
return a;
}
|
the_stack_data/231394073.c | // code: 0
int main() { return 0 ^ 0; } |
the_stack_data/73575405.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_sqrt.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ekutlay <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/06 22:07:29 by ekutlay #+# #+# */
/* Updated: 2021/11/06 22:22:27 by ekutlay ### ########.fr */
/* */
/* ************************************************************************** */
int ft_sqrt(int nb)
{
int i;
i = 0;
if (nb <= 0)
{
return (0);
}
while (i * i < nb && i <= 46340)
{
i++;
}
if (i * i == nb)
{
return (i);
}
else
{
return (0);
}
}
/*
#include <stdio.h>
int ft_sqrt(int nb);
int main(void)
{
printf("%d\n", ft_sqrt(81));
}
*/
|
the_stack_data/162642525.c | #include "stdio.h"
#define BUFSIZE 100
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
int getch(void) /* get a (possibly pushed-back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back on input */
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
} |
the_stack_data/103263.c | #ifdef COMPILE_FOR_TEST
#include <assert.h>
#define assume(cond) assert(cond)
#endif
void main(int argc, char* argv[]) {
int x_0_0;//sh_buf.outcnt
int x_0_1;//sh_buf.outcnt
int x_0_2;//sh_buf.outcnt
int x_0_3;//sh_buf.outcnt
int x_0_4;//sh_buf.outcnt
int x_0_5;//sh_buf.outcnt
int x_1_0;//sh_buf.outbuf[0]
int x_1_1;//sh_buf.outbuf[0]
int x_2_0;//sh_buf.outbuf[1]
int x_2_1;//sh_buf.outbuf[1]
int x_3_0;//sh_buf.outbuf[2]
int x_3_1;//sh_buf.outbuf[2]
int x_4_0;//sh_buf.outbuf[3]
int x_4_1;//sh_buf.outbuf[3]
int x_5_0;//sh_buf.outbuf[4]
int x_5_1;//sh_buf.outbuf[4]
int x_6_0;//sh_buf.outbuf[5]
int x_7_0;//sh_buf.outbuf[6]
int x_8_0;//sh_buf.outbuf[7]
int x_9_0;//sh_buf.outbuf[8]
int x_10_0;//sh_buf.outbuf[9]
int x_11_0;//LOG_BUFSIZE
int x_11_1;//LOG_BUFSIZE
int x_12_0;//CREST_scheduler::lock_0
int x_13_0;//t3 T0
int x_14_0;//t2 T0
int x_15_0;//arg T0
int x_16_0;//functioncall::param T0
int x_16_1;//functioncall::param T0
int x_17_0;//buffered T0
int x_18_0;//functioncall::param T0
int x_18_1;//functioncall::param T0
int x_19_0;//functioncall::param T0
int x_19_1;//functioncall::param T0
int x_20_0;//functioncall::param T0
int x_20_1;//functioncall::param T0
int x_21_0;//functioncall::param T0
int x_21_1;//functioncall::param T0
int x_22_0;//direction T0
int x_23_0;//functioncall::param T0
int x_23_1;//functioncall::param T0
int x_24_0;//functioncall::param T0
int x_24_1;//functioncall::param T0
int x_25_0;//functioncall::param T0
int x_25_1;//functioncall::param T0
int x_26_0;//functioncall::param T0
int x_26_1;//functioncall::param T0
int x_27_0;//functioncall::param T0
int x_27_1;//functioncall::param T0
int x_28_0;//functioncall::param T0
int x_28_1;//functioncall::param T0
int x_29_0;//functioncall::param T0
int x_29_1;//functioncall::param T0
int x_30_0;//functioncall::param T0
int x_30_1;//functioncall::param T0
int x_31_0;//functioncall::param T0
int x_31_1;//functioncall::param T0
int x_32_0;//functioncall::param T0
int x_32_1;//functioncall::param T0
int x_33_0;//functioncall::param T0
int x_33_1;//functioncall::param T0
int x_34_0;//functioncall::param T0
int x_34_1;//functioncall::param T0
int x_35_0;//functioncall::param T1
int x_35_1;//functioncall::param T1
int x_36_0;//functioncall::param T1
int x_36_1;//functioncall::param T1
int x_37_0;//i T1
int x_37_1;//i T1
int x_37_2;//i T1
int x_38_0;//rv T1
int x_39_0;//rv T1
int x_39_1;//rv T1
int x_40_0;//functioncall::param T1
int x_40_1;//functioncall::param T1
int x_41_0;//functioncall::param T1
int x_41_1;//functioncall::param T1
int x_42_0;//functioncall::param T1
int x_42_1;//functioncall::param T1
int x_43_0;//functioncall::param T1
int x_43_1;//functioncall::param T1
int x_44_0;//functioncall::param T1
int x_44_1;//functioncall::param T1
int x_45_0;//functioncall::param T1
int x_45_1;//functioncall::param T1
int x_46_0;//functioncall::param T1
int x_46_1;//functioncall::param T1
int x_47_0;//functioncall::param T1
int x_47_1;//functioncall::param T1
int x_48_0;//functioncall::param T1
int x_48_1;//functioncall::param T1
int x_49_0;//functioncall::param T2
int x_49_1;//functioncall::param T2
int x_50_0;//functioncall::param T2
int x_50_1;//functioncall::param T2
int x_51_0;//i T2
int x_51_1;//i T2
int x_51_2;//i T2
int x_51_3;//i T2
int x_52_0;//rv T2
int x_53_0;//functioncall::param T2
int x_53_1;//functioncall::param T2
int x_54_0;//functioncall::param T2
int x_54_1;//functioncall::param T2
int x_55_0;//functioncall::param T2
int x_55_1;//functioncall::param T2
int x_55_2;//functioncall::param T2
int x_56_0;//functioncall::param T2
int x_56_1;//functioncall::param T2
T_0_0_0: x_0_0 = 0;
T_0_1_0: x_1_0 = 0;
T_0_2_0: x_2_0 = 0;
T_0_3_0: x_3_0 = 0;
T_0_4_0: x_4_0 = 0;
T_0_5_0: x_5_0 = 0;
T_0_6_0: x_6_0 = 0;
T_0_7_0: x_7_0 = 0;
T_0_8_0: x_8_0 = 0;
T_0_9_0: x_9_0 = 0;
T_0_10_0: x_10_0 = 0;
T_0_11_0: x_11_0 = 0;
T_0_12_0: x_13_0 = 3483223200;
T_0_13_0: x_14_0 = 2026779232;
T_0_14_0: x_15_0 = 0;
T_0_15_0: x_16_0 = 464809686;
T_0_16_0: x_16_1 = -1;
T_0_17_0: x_17_0 = 0;
T_0_18_0: x_18_0 = 513186396;
T_0_19_0: x_18_1 = x_17_0;
T_0_20_0: x_19_0 = 1119913848;
T_0_21_0: x_19_1 = 97;
T_0_22_0: x_20_0 = 305410583;
T_0_23_0: x_20_1 = 0;
T_0_24_0: x_21_0 = 1454735385;
T_0_25_0: x_21_1 = 0;
T_0_26_0: x_22_0 = 2026774592;
T_0_27_0: x_23_0 = 1382493110;
T_0_28_0: x_23_1 = x_22_0;
T_0_29_0: x_24_0 = 1757527389;
T_0_30_0: x_24_1 = 0;
T_0_31_0: x_12_0 = -1;
T_0_32_0: x_0_1 = 5;
T_0_33_0: x_1_1 = 72;
T_0_34_0: x_2_1 = 69;
T_0_35_0: x_3_1 = 76;
T_0_36_0: x_4_1 = 76;
T_0_37_0: x_5_1 = 79;
T_0_38_0: x_25_0 = 1896992492;
T_0_39_0: x_25_1 = 83;
T_0_40_0: x_26_0 = 903146593;
T_0_41_0: x_26_1 = 1;
T_0_42_0: x_27_0 = 1066895459;
T_0_43_0: x_27_1 = 1;
T_0_44_0: x_28_0 = 500527107;
T_0_45_0: x_28_1 = 1;
T_0_46_0: x_29_0 = 2140895316;
T_0_47_0: x_29_1 = 82;
T_0_48_0: x_30_0 = 2065429300;
T_0_49_0: x_30_1 = 90;
T_0_50_0: x_31_0 = 885275723;
T_0_51_0: x_31_1 = 1;
T_0_52_0: x_32_0 = 436170462;
T_0_53_0: x_32_1 = 1;
T_0_54_0: x_33_0 = 1562597714;
T_0_55_0: x_33_1 = 2;
T_0_56_0: x_34_0 = 492494135;
T_0_57_0: x_34_1 = 2;
T_0_58_0: x_11_1 = 3;
T_1_59_1: x_35_0 = 1180344039;
T_1_60_1: x_35_1 = x_27_1;
T_1_61_1: x_36_0 = 565300007;
T_1_62_1: x_36_1 = x_28_1;
T_1_63_1: x_37_0 = 0;
T_1_64_1: x_38_0 = -2075336191;
T_1_65_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_39_0 = 2033842096;
T_1_66_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_40_0 = 1392445424;
T_1_67_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_40_1 = -1;
T_1_68_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_39_1 = x_40_1;
T_1_69_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_39_1 + 1 == 0) x_0_2 = 0;
T_1_70_1: x_49_0 = 12614832;
T_1_71_1: x_49_1 = x_33_1;
T_2_72_2: x_50_0 = 4488606;
T_2_73_2: x_50_1 = x_34_1;
T_2_74_2: x_51_0 = 0;
T_2_75_2: x_52_0 = -2077437439;
T_2_76_2: if (x_50_1 < x_11_1) x_53_0 = 1298067184;
T_2_77_2: if (x_50_1 < x_11_1) x_53_1 = 47263897564928;
T_2_78_2: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_41_0 = 1255519877;
T_2_79_2: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_41_1 = 9;
T_1_80_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_42_0 = 280313864;
T_1_81_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_42_1 = x_41_1;
T_1_82_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_0_3 = 0;
T_1_83_1: if (x_50_1 < x_11_1) x_54_0 = 55100829;
T_1_84_1: if (x_50_1 < x_11_1) x_54_1 = x_0_2 + x_50_1;
T_2_85_2: if (x_50_1 < x_11_1) x_51_1 = 0;
T_2_86_2: if (x_50_1 < x_11_1 && x_51_1 < x_49_1) x_55_0 = 87054927;
T_2_87_2: if (x_50_1 < x_11_1 && x_51_1 < x_49_1) x_55_1 = 47263897564928;
T_2_88_2: if (x_50_1 < x_11_1) x_51_2 = 1 + x_51_1;
T_2_89_2: if (x_50_1 < x_11_1 && x_51_2 < x_49_1) x_55_2 = 47263897564928;
T_2_90_2: if (x_50_1 < x_11_1) x_51_3 = 1 + x_51_2;
T_2_91_2: if (x_50_1 < x_11_1) x_56_0 = 676625409;
T_2_92_2: if (x_50_1 < x_11_1) x_56_1 = 47263897564928;
T_2_93_2: if (x_36_1 < x_11_1) x_43_0 = 1519945940;
T_1_94_1: if (x_36_1 < x_11_1) x_43_1 = 47263895463680;
T_1_95_1: if (x_36_1 < x_11_1) x_44_0 = 1005444957;
T_1_96_1: if (x_36_1 < x_11_1) x_44_1 = x_0_3 + x_36_1;
T_1_97_1: if (x_36_1 < x_11_1) x_37_1 = 0;
T_1_98_1: if (x_36_1 < x_11_1 && x_37_1 < x_35_1) x_45_0 = 1891387716;
T_1_99_1: if (x_36_1 < x_11_1 && x_37_1 < x_35_1) x_45_1 = 47263895463680;
T_1_100_1: if (x_36_1 < x_11_1) x_37_2 = 1 + x_37_1;
T_1_101_1: if (x_36_1 < x_11_1) x_46_0 = 1984755626;
T_1_102_1: if (x_36_1 < x_11_1) x_46_1 = 47263895463680;
T_1_103_1: if (x_36_1 < x_11_1) x_0_4 = x_0_3 + x_36_1;
T_1_104_1: if (x_36_1 < x_11_1) x_47_0 = 1518631353;
T_1_105_1: if (x_36_1 < x_11_1) x_47_1 = 47263895463680;
T_1_106_1: if (x_50_1 < x_11_1) x_0_5 = x_0_3 + x_50_1;
T_1_107_1: if (x_36_1 < x_11_1) x_48_0 = 863817917;
T_2_108_2: if (x_36_1 < x_11_1) x_48_1 = 47263895463680;
T_1_109_1: if (x_36_1 < x_11_1) assert(x_0_5 == x_44_1);
}
|
the_stack_data/37639045.c | /* Prints a table of compound interest */
#include <stdio.h>
#define NUM_RATES ((int) (sizeof(value) / sizeof(value[0])))
#define INITIAL_BALANCE 100.00
int main(void)
{
int i, low_rate, num_years, year;
double value[5];
printf("Enter interest rate: ");
scanf_s("%d", &low_rate);
printf("Enter number of years: ");
scanf_s("%d", &num_years);
printf("\nYears");
for (i = 0; i < NUM_RATES; i++) {
printf("%6d%%", low_rate + i);
value[i] = INITIAL_BALANCE;
}
printf("\n");
for (year = 1; year <= num_years; year++) {
printf("%3d ", year);
for (i = 0; i < NUM_RATES; i++) {
value[i] += (low_rate + i) / 100.0 * value[i];
printf("%7.2f", value[i]);
}
printf("\n");
}
return 0;
}
|
the_stack_data/124525.c | /*!
\file gd32f1x0_opa.c
\brief OPA driver
\version 2014-12-26, V1.0.0, platform GD32F1x0(x=3,5)
\version 2016-01-15, V2.0.0, platform GD32F1x0(x=3,5,7,9)
\version 2016-04-30, V3.0.0, firmware update for GD32F1x0(x=3,5,7,9)
\version 2017-06-19, V3.1.0, firmware update for GD32F1x0(x=3,5,7,9)
\version 2019-11-20, V3.2.0, firmware update for GD32F1x0(x=3,5,7,9)
\version 2020-09-21, V3.3.0, firmware update for GD32F1x0(x=3,5,7,9)
*/
/*
Copyright (c) 2020, GigaDevice Semiconductor Inc.
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 copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
#ifdef GD32F170_190
#include "gd32f1x0_opa.h"
/*!
\brief deinit the OPA register to its default reset value
\param[in] none
\param[out] none
\retval none
*/
void opa_deinit(void)
{
rcu_periph_reset_enable(RCU_OPAIVREFRST);
rcu_periph_reset_disable(RCU_OPAIVREFRST);
}
/*!
\brief enable OPA switch
\param[in] opax_swy��OPA switch
only one parameter can be selected which is shown as below:
\arg OPA_T3OPA0: T3 switch enable for OPA0
\arg OPA_S1OPA0: S1 switch enable for OPA0
\arg OPA_S2OPA0: S2 switch enable for OPA0
\arg OPA_S3OPA0: S3 switch enable for OPA0
\arg OPA_T3OPA1: T3 switch enable for OPA1
\arg OPA_S1OPA1: S1 switch enable for OPA1
\arg OPA_S2OPA1: S2 switch enable for OPA1
\arg OPA_S3OPA1: S3 switch enable for OPA1
\arg OPA_S4OPA1: S4 switch enable for OPA1
\arg OPA_T3OPA2: T3 switch enable for OPA2
\arg OPA_S1OPA2: S3 switch enable for OPA2
\arg OPA_S2OPA2: S3 switch enable for OPA2
\arg OPA_S3OPA2: S3 switch enable for OPA2
\param[out] none
\retval none
*/
void opa_switch_enable(uint32_t opax_swy)
{
OPA_CTL |= (uint32_t)(opax_swy);
}
/*!
\brief enable OPA
\param[in] opa_periph
\arg OPAx(x =0,1,2)
\param[out] none
\retval none
*/
void opa_enable(uint32_t opa_periph)
{
if(OPA0 == opa_periph){
OPA_CTL &= ~OPA_CTL_OPA0PD;
}else if(OPA1 == opa_periph){
OPA_CTL &= ~OPA_CTL_OPA1PD;
}else{
OPA_CTL &= ~OPA_CTL_OPA2PD;
}
}
/*!
\brief disable OPA
\param[in] opa_periph
\arg OPAx(x =0,1,2)
\param[out] none
\retval none
*/
void opa_disable(uint32_t opa_periph)
{
if(OPA0 == opa_periph){
OPA_CTL |= OPA_CTL_OPA0PD;
}else if(OPA1 == opa_periph){
OPA_CTL |= OPA_CTL_OPA1PD;
}else{
OPA_CTL |= OPA_CTL_OPA2PD;
}
}
/*!
\brief disable OPA switch
\param[in] opax_swy��OPA switch
only one parameter can be selected which is shown as below:
\arg OPA_T3OPA0: T3 switch enable for OPA0
\arg OPA_S1OPA0: S1 switch enable for OPA0
\arg OPA_S2OPA0: S2 switch enable for OPA0
\arg OPA_S3OPA0: S3 switch enable for OPA0
\arg OPA_T3OPA1: T3 switch enable for OPA1
\arg OPA_S1OPA1: S1 switch enable for OPA1
\arg OPA_S2OPA1: S2 switch enable for OPA1
\arg OPA_S3OPA1: S3 switch enable for OPA1
\arg OPA_S4OPA1: S4 switch enable for OPA1
\arg OPA_T3OPA2: T3 switch enable for OPA2
\arg OPA_S1OPA2: S3 switch enable for OPA2
\arg OPA_S2OPA2: S3 switch enable for OPA2
\arg OPA_S3OPA2: S3 switch enable for OPA2
\param[out] none
\retval none
*/
void opa_switch_disable(uint32_t opax_swy)
{
OPA_CTL &= ~opax_swy;
}
/*!
\brief enable OPA in low power mode
\param[in] opa_periph
\arg OPAx(x =0,1,2)
\param[out] none
\retval none
*/
void opa_low_power_enable(uint32_t opa_periph)
{
if(OPA0 == opa_periph){
OPA_CTL |= OPA_CTL_OPA0LPM;
}else if(OPA1 == opa_periph){
OPA_CTL |= OPA_CTL_OPA1LPM;
}else{
OPA_CTL |= OPA_CTL_OPA2LPM;
}
}
/*!
\brief disable OPA in low power mode
\param[in] opa_periph
\arg OPAx(x =0,1,2)
\param[out] none
\retval none
*/
void opa_low_power_disable(uint32_t opa_periph)
{
if(OPA0 == opa_periph){
OPA_CTL &= ~OPA_CTL_OPA0LPM;
}else if(OPA1 == opa_periph){
OPA_CTL &= ~OPA_CTL_OPA1LPM;
}else{
OPA_CTL &= ~OPA_CTL_OPA2LPM;
}
}
/*!
\brief set OPA power range
\param[in] powerrange: opa power range
only one parameter can be selected which is shown as below:
\arg OPA_POWRANGE_LOW: Low power range is selected (VDDA is lower than 3.3V)
\arg OPA_POWRANGE_HIGH: High power range is selected (VDDA is higher than 3.3V)
\param[out] none
\retval none
*/
void opa_power_range_config(uint32_t powerrange)
{
OPA_CTL &= ~OPA_CTL_OPA_RANGE;
OPA_CTL |= powerrange;
}
/*!
\brief set OPA bias trimming mode
\param[in] opa_trimmode: opa trimming mode
only one parameter can be selected which is shown as below:
\arg OPA_BT_TRIM_FACTORY: factory trimming values are used for offset calibration
\arg OPA_BT_TRIM_USER: user trimming values are used for offset calibration
\param[out] none
\retval none
*/
void opa_trim_mode_set(uint32_t opa_trimmode)
{
OPA_BT &= ~OPA_BT_OT_USER;
OPA_BT |= opa_trimmode;
}
/*!
\brief set OPA bias trimming value
\param[in] opa_periph
\arg OPAx(x =0,1,2)
\param[in] opa_input: opa input
only one parameter can be selected which is shown as below:
\arg OPA_INPUT_P: PMOS input is selected to configure the trimming value
\arg OPA_INPUT_N: NMOS input is selected to configure the trimming value
\param[in] opa_trimmode
\arg this parameter can be any value lower or equal to 0x0000001F.
\param[out] none
\retval none
*/
void opa_trim_value_config(uint32_t opa_periph,uint32_t opa_input,uint32_t opa_trimvalue)
{
uint32_t bt = 0U, ctl = 0U;
ctl = OPA_CTL;
bt = OPA_BT;
if(OPA0 == opa_periph){
/* clear the specified opa calibration for N diff and P diff */
ctl &= (uint32_t)~(OPA_CTL_OPA0CAL_L | OPA_CTL_OPA0CAL_H);
/* set the specified opa calibration for N diff or P diff */
ctl |= opa_input;
if(OPA_INPUT_P == opa_input){
/* clear the specified PMOS pairs normal mode 5-bit offset trim value */
bt &= (~OPA_BT_OA0_TRIM_LOW);
bt |= (opa_trimvalue);
}else{
/* clear the specified NMOS pairs normal mode 5-bit offset trim value */
bt &= (~OPA_BT_OA0_TRIM_HIGH);
bt |= (opa_trimvalue << 5U);
}
}else if(OPA1 == opa_periph){
ctl &= (uint32_t)~(OPA_CTL_OPA1CAL_L | OPA_CTL_OPA1CAL_H);
ctl |= (uint32_t)(opa_input << 8U);
if(OPA_INPUT_P == opa_input){
/* clear the specified PMOS pairs normal mode 5-bit offset trim value */
bt &= (~OPA_BT_OA1_TRIM_LOW);
bt |= (opa_trimvalue << 10U);
}else{
/* clear the specified NMOS pairs normal mode 5-bit offset trim value */
bt &= (~OPA_BT_OA1_TRIM_HIGH);
bt |= (opa_trimvalue << 15U);
}
}else{
ctl &= (uint32_t)~(OPA_CTL_OPA2CAL_L | OPA_CTL_OPA2CAL_H);
ctl |= (uint32_t)(opa_input << 16U);
if(OPA_INPUT_P == opa_input){
/* clear the specified PMOS pairs normal mode 5-bit offset trim value */
bt &= (~OPA_BT_OA2_TRIM_LOW);
bt |= (opa_trimvalue << 20U);
}else{
/* clear the specified NMOS pairs normal mode 5-bit offset trim value */
bt &= (~OPA_BT_OA2_TRIM_HIGH);
bt |= (opa_trimvalue << 25U);
}
}
OPA_CTL = ctl;
OPA_BT = bt;
}
/*!
\brief set OPA bias trimming value low power
\param[in] opa_periph
\arg OPAx(x =0,1,2)
\param[in] opa_input: opa input
only one parameter can be selected which is shown as below:
\arg OPA_INPUT_P: PMOS input is selected to configure the trimming value
\arg OPA_INPUT_N: NMOS input is selected to configure the trimming value
\param[in] opa_trimmode
\arg this parameter can be any value lower or equal to 0x0000001F.
\param[out] none
\retval none
*/
void opa_trim_value_lp_config(uint32_t opa_periph,uint32_t opa_input,uint32_t opa_trimvalue)
{
uint32_t lpbt = 0U, ctl = 0U;
ctl = OPA_CTL;
lpbt = OPA_LPBT;
if(OPA0 == opa_periph){
ctl &= (uint32_t)~(OPA_CTL_OPA0CAL_L | OPA_CTL_OPA0CAL_H);
ctl |= opa_input;
if(OPA_INPUT_P == opa_input){
/* clear the specified PMOS pairs low power mode 5-bit offset trim value */
lpbt &= (~OPA_LPBT_OA0_TRIM_LOW);
lpbt |= (opa_trimvalue);
}else{
/* clear the specified NMOS pairs low power mode 5-bit offset trim value */
lpbt &= (~OPA_LPBT_OA0_TRIM_HIGH);
lpbt |= (opa_trimvalue << 5U);
}
}else if (OPA1 == opa_periph){
ctl &= (uint32_t)~(OPA_CTL_OPA1CAL_L | OPA_CTL_OPA1CAL_H);
ctl |= (uint32_t)(opa_input << 8U);
if(OPA_INPUT_P == opa_input){
/* clear the specified PMOS pairs low power mode 5-bit offset trim value */
lpbt &= (~OPA_LPBT_OA1_TRIM_LOW);
lpbt |= (opa_trimvalue << 10U);
}else{
/* clear the specified NMOS pairs low power mode 5-bit offset trim value */
lpbt &= (~OPA_LPBT_OA1_TRIM_HIGH);
lpbt |= (opa_trimvalue << 15U);
}
}else{
ctl &= (uint32_t)~(OPA_CTL_OPA2CAL_L | OPA_CTL_OPA2CAL_H);
ctl |= (uint32_t)(opa_input << 16U);
if(OPA_INPUT_P == opa_input){
/* clear the specified PMOS pairs low power mode 5-bit offset trim value */
lpbt &= (~OPA_LPBT_OA2_TRIM_LOW);
lpbt |= (opa_trimvalue << 20U);
}else{
/* clear the specified NMOS pairs low power mode 5-bit offset trim value */
lpbt &= (~OPA_LPBT_OA2_TRIM_HIGH);
lpbt |= (opa_trimvalue << 25U);
}
}
OPA_CTL = ctl;
OPA_LPBT = lpbt;
}
/*!
\brief get OPA calibration flag
\param[in] opa_periph
\arg OPAx(x =0,1,2)
\param[out] none
\retval The state of the OPA calibration flag (SET or RESET)
*/
FlagStatus opa_cal_out_get(uint32_t opa_periph)
{
uint32_t data = 0U;
FlagStatus bitstatus = RESET;
data = OPA_CTL;
if(OPA0 == opa_periph){
/* get opa0 calibration output bit status */
if ((uint32_t)RESET != (data & OPA_CTL_OPA0CALOUT)){
bitstatus = SET;
}else{
bitstatus = RESET;
}
}else if(OPA1 == opa_periph){
/* get opa1 calibration output bit status */
if ((uint32_t)RESET != (data & OPA_CTL_OPA1CALOUT)){
bitstatus = SET;
}else{
bitstatus = RESET;
}
}else{
/* get opa2 calibration output bit status */
if((uint32_t)RESET != (data & OPA_CTL_OPA2CALOUT)){
bitstatus = SET;
}else{
bitstatus = RESET;
}
}
return bitstatus;
}
#endif /* GD32F170_190 */
|
the_stack_data/51701191.c | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifdef GIT_WINHTTP
#include "git2.h"
#include "git2/transport.h"
#include "buffer.h"
#include "posix.h"
#include "netops.h"
#include "smart.h"
#include "remote.h"
#include "repository.h"
#include "global.h"
#include <wincrypt.h>
#include <winhttp.h>
/* For IInternetSecurityManager zone check */
#include <objbase.h>
#include <urlmon.h>
#define WIDEN2(s) L ## s
#define WIDEN(s) WIDEN2(s)
#define MAX_CONTENT_TYPE_LEN 100
#define WINHTTP_OPTION_PEERDIST_EXTENSION_STATE 109
#define CACHED_POST_BODY_BUF_SIZE 4096
#define UUID_LENGTH_CCH 32
#define TIMEOUT_INFINITE -1
#define DEFAULT_CONNECT_TIMEOUT 60000
#ifndef WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH
#define WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH 0
#endif
static const char *prefix_https = "https://";
static const char *upload_pack_service = "upload-pack";
static const char *upload_pack_ls_service_url = "/info/refs?service=git-upload-pack";
static const char *upload_pack_service_url = "/git-upload-pack";
static const char *receive_pack_service = "receive-pack";
static const char *receive_pack_ls_service_url = "/info/refs?service=git-receive-pack";
static const char *receive_pack_service_url = "/git-receive-pack";
static const wchar_t *get_verb = L"GET";
static const wchar_t *post_verb = L"POST";
static const wchar_t *pragma_nocache = L"Pragma: no-cache";
static const wchar_t *transfer_encoding = L"Transfer-Encoding: chunked";
static const int no_check_cert_flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID |
SECURITY_FLAG_IGNORE_UNKNOWN_CA;
#if defined(__MINGW32__)
static const CLSID CLSID_InternetSecurityManager_mingw =
{ 0x7B8A2D94, 0x0AC9, 0x11D1,
{ 0x89, 0x6C, 0x00, 0xC0, 0x4F, 0xB6, 0xBF, 0xC4 } };
static const IID IID_IInternetSecurityManager_mingw =
{ 0x79EAC9EE, 0xBAF9, 0x11CE,
{ 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B } };
# define CLSID_InternetSecurityManager CLSID_InternetSecurityManager_mingw
# define IID_IInternetSecurityManager IID_IInternetSecurityManager_mingw
#endif
#define OWNING_SUBTRANSPORT(s) ((winhttp_subtransport *)(s)->parent.subtransport)
typedef enum {
GIT_WINHTTP_AUTH_BASIC = 1,
GIT_WINHTTP_AUTH_NTLM = 2,
GIT_WINHTTP_AUTH_NEGOTIATE = 4,
GIT_WINHTTP_AUTH_DIGEST = 8,
} winhttp_authmechanism_t;
typedef struct {
git_smart_subtransport_stream parent;
const char *service;
const char *service_url;
const wchar_t *verb;
HINTERNET request;
wchar_t *request_uri;
char *chunk_buffer;
unsigned chunk_buffer_len;
HANDLE post_body;
DWORD post_body_len;
unsigned sent_request : 1,
received_response : 1,
chunked : 1;
} winhttp_stream;
typedef struct {
git_smart_subtransport parent;
transport_smart *owner;
gitno_connection_data connection_data;
gitno_connection_data proxy_connection_data;
git_cred *cred;
git_cred *url_cred;
git_cred *proxy_cred;
int auth_mechanisms;
HINTERNET session;
HINTERNET connection;
} winhttp_subtransport;
static int _apply_userpass_credential(HINTERNET request, DWORD target, DWORD scheme, git_cred *cred)
{
git_cred_userpass_plaintext *c = (git_cred_userpass_plaintext *)cred;
wchar_t *user, *pass;
int user_len = 0, pass_len = 0, error = 0;
if ((error = user_len = git__utf8_to_16_alloc(&user, c->username)) < 0)
goto done;
if ((error = pass_len = git__utf8_to_16_alloc(&pass, c->password)) < 0)
goto done;
if (!WinHttpSetCredentials(request, target, scheme, user, pass, NULL)) {
giterr_set(GITERR_OS, "failed to set credentials");
error = -1;
}
done:
if (user_len > 0)
git__memzero(user, user_len * sizeof(wchar_t));
if (pass_len > 0)
git__memzero(pass, pass_len * sizeof(wchar_t));
git__free(user);
git__free(pass);
return error;
}
static int apply_userpass_credential_proxy(HINTERNET request, git_cred *cred, int mechanisms)
{
if (GIT_WINHTTP_AUTH_DIGEST & mechanisms) {
return _apply_userpass_credential(request, WINHTTP_AUTH_TARGET_PROXY,
WINHTTP_AUTH_SCHEME_DIGEST, cred);
}
return _apply_userpass_credential(request, WINHTTP_AUTH_TARGET_PROXY,
WINHTTP_AUTH_SCHEME_BASIC, cred);
}
static int apply_userpass_credential(HINTERNET request, int mechanisms, git_cred *cred)
{
DWORD native_scheme;
if ((mechanisms & GIT_WINHTTP_AUTH_NTLM) ||
(mechanisms & GIT_WINHTTP_AUTH_NEGOTIATE)) {
native_scheme = WINHTTP_AUTH_SCHEME_NTLM;
} else if (mechanisms & GIT_WINHTTP_AUTH_BASIC) {
native_scheme = WINHTTP_AUTH_SCHEME_BASIC;
} else {
giterr_set(GITERR_NET, "invalid authentication scheme");
return -1;
}
return _apply_userpass_credential(request, WINHTTP_AUTH_TARGET_SERVER,
native_scheme, cred);
}
static int apply_default_credentials(HINTERNET request, int mechanisms)
{
/* Either the caller explicitly requested that default credentials be passed,
* or our fallback credential callback was invoked and checked that the target
* URI was in the appropriate Internet Explorer security zone. By setting this
* flag, we guarantee that the credentials are delivered by WinHTTP. The default
* is "medium" which applies to the intranet and sounds like it would correspond
* to Internet Explorer security zones, but in fact does not. */
DWORD data = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
if ((mechanisms & GIT_WINHTTP_AUTH_NTLM) == 0 &&
(mechanisms & GIT_WINHTTP_AUTH_NEGOTIATE) == 0) {
giterr_set(GITERR_NET, "invalid authentication scheme");
return -1;
}
if (!WinHttpSetOption(request, WINHTTP_OPTION_AUTOLOGON_POLICY, &data, sizeof(DWORD)))
return -1;
return 0;
}
static int fallback_cred_acquire_cb(
git_cred **cred,
const char *url,
const char *username_from_url,
unsigned int allowed_types,
void *payload)
{
int error = 1;
GIT_UNUSED(username_from_url);
GIT_UNUSED(payload);
/* If the target URI supports integrated Windows authentication
* as an authentication mechanism */
if (GIT_CREDTYPE_DEFAULT & allowed_types) {
wchar_t *wide_url;
/* Convert URL to wide characters */
if (git__utf8_to_16_alloc(&wide_url, url) < 0) {
giterr_set(GITERR_OS, "failed to convert string to wide form");
return -1;
}
if (SUCCEEDED(CoInitializeEx(NULL, COINIT_MULTITHREADED))) {
IInternetSecurityManager* pISM;
/* And if the target URI is in the My Computer, Intranet, or Trusted zones */
if (SUCCEEDED(CoCreateInstance(&CLSID_InternetSecurityManager, NULL,
CLSCTX_ALL, &IID_IInternetSecurityManager, (void **)&pISM))) {
DWORD dwZone;
if (SUCCEEDED(pISM->lpVtbl->MapUrlToZone(pISM, wide_url, &dwZone, 0)) &&
(URLZONE_LOCAL_MACHINE == dwZone ||
URLZONE_INTRANET == dwZone ||
URLZONE_TRUSTED == dwZone)) {
git_cred *existing = *cred;
if (existing)
existing->free(existing);
/* Then use default Windows credentials to authenticate this request */
error = git_cred_default_new(cred);
}
pISM->lpVtbl->Release(pISM);
}
CoUninitialize();
}
git__free(wide_url);
}
return error;
}
static int certificate_check(winhttp_stream *s, int valid)
{
int error;
winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
PCERT_CONTEXT cert_ctx;
DWORD cert_ctx_size = sizeof(cert_ctx);
git_cert_x509 cert;
/* If there is no override, we should fail if WinHTTP doesn't think it's fine */
if (t->owner->certificate_check_cb == NULL && !valid) {
if (!giterr_last())
giterr_set(GITERR_NET, "unknown certificate check failure");
return GIT_ECERTIFICATE;
}
if (t->owner->certificate_check_cb == NULL || !t->connection_data.use_ssl)
return 0;
if (!WinHttpQueryOption(s->request, WINHTTP_OPTION_SERVER_CERT_CONTEXT, &cert_ctx, &cert_ctx_size)) {
giterr_set(GITERR_OS, "failed to get server certificate");
return -1;
}
giterr_clear();
cert.parent.cert_type = GIT_CERT_X509;
cert.data = cert_ctx->pbCertEncoded;
cert.len = cert_ctx->cbCertEncoded;
error = t->owner->certificate_check_cb((git_cert *) &cert, valid, t->connection_data.host, t->owner->cred_acquire_payload);
CertFreeCertificateContext(cert_ctx);
if (error < 0 && !giterr_last())
giterr_set(GITERR_NET, "user cancelled certificate check");
return error;
}
static void winhttp_stream_close(winhttp_stream *s)
{
if (s->chunk_buffer) {
git__free(s->chunk_buffer);
s->chunk_buffer = NULL;
}
if (s->post_body) {
CloseHandle(s->post_body);
s->post_body = NULL;
}
if (s->request_uri) {
git__free(s->request_uri);
s->request_uri = NULL;
}
if (s->request) {
WinHttpCloseHandle(s->request);
s->request = NULL;
}
s->sent_request = 0;
}
/**
* Extract the url and password from a URL. The outputs are pointers
* into the input.
*/
static int userpass_from_url(wchar_t **user, int *user_len,
wchar_t **pass, int *pass_len,
const wchar_t *url, int url_len)
{
URL_COMPONENTS components = { 0 };
components.dwStructSize = sizeof(components);
/* These tell WinHttpCrackUrl that we're interested in the fields */
components.dwUserNameLength = 1;
components.dwPasswordLength = 1;
if (!WinHttpCrackUrl(url, url_len, 0, &components)) {
giterr_set(GITERR_OS, "failed to extract user/pass from url");
return -1;
}
*user = components.lpszUserName;
*user_len = components.dwUserNameLength;
*pass = components.lpszPassword;
*pass_len = components.dwPasswordLength;
return 0;
}
#define SCHEME_HTTP "http://"
#define SCHEME_HTTPS "https://"
static int winhttp_stream_connect(winhttp_stream *s)
{
winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
git_buf buf = GIT_BUF_INIT;
char *proxy_url = NULL;
wchar_t ct[MAX_CONTENT_TYPE_LEN];
LPCWSTR types[] = { L"*/*", NULL };
BOOL peerdist = FALSE;
int error = -1;
unsigned long disable_redirects = WINHTTP_DISABLE_REDIRECTS;
int default_timeout = TIMEOUT_INFINITE;
int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
size_t i;
const git_proxy_options *proxy_opts;
/* Prepare URL */
git_buf_printf(&buf, "%s%s", t->connection_data.path, s->service_url);
if (git_buf_oom(&buf))
return -1;
/* Convert URL to wide characters */
if (git__utf8_to_16_alloc(&s->request_uri, git_buf_cstr(&buf)) < 0) {
giterr_set(GITERR_OS, "failed to convert string to wide form");
goto on_error;
}
/* Establish request */
s->request = WinHttpOpenRequest(
t->connection,
s->verb,
s->request_uri,
NULL,
WINHTTP_NO_REFERER,
types,
t->connection_data.use_ssl ? WINHTTP_FLAG_SECURE : 0);
if (!s->request) {
giterr_set(GITERR_OS, "failed to open request");
goto on_error;
}
if (!WinHttpSetTimeouts(s->request, default_timeout, default_connect_timeout, default_timeout, default_timeout)) {
giterr_set(GITERR_OS, "failed to set timeouts for WinHTTP");
goto on_error;
}
proxy_opts = &t->owner->proxy;
if (proxy_opts->type == GIT_PROXY_AUTO) {
/* Set proxy if necessary */
if (git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url) < 0)
goto on_error;
}
else if (proxy_opts->type == GIT_PROXY_SPECIFIED) {
proxy_url = git__strdup(proxy_opts->url);
GITERR_CHECK_ALLOC(proxy_url);
}
if (proxy_url) {
git_buf processed_url = GIT_BUF_INIT;
WINHTTP_PROXY_INFO proxy_info;
wchar_t *proxy_wide;
if (!git__prefixcmp(proxy_url, SCHEME_HTTP)) {
t->proxy_connection_data.use_ssl = false;
} else if (!git__prefixcmp(proxy_url, SCHEME_HTTPS)) {
t->proxy_connection_data.use_ssl = true;
} else {
giterr_set(GITERR_NET, "invalid URL: '%s'", proxy_url);
return -1;
}
gitno_connection_data_free_ptrs(&t->proxy_connection_data);
if ((error = gitno_extract_url_parts(&t->proxy_connection_data.host, &t->proxy_connection_data.port, NULL,
&t->proxy_connection_data.user, &t->proxy_connection_data.pass, proxy_url, NULL)) < 0)
goto on_error;
if (t->proxy_connection_data.user && t->proxy_connection_data.pass) {
if (t->proxy_cred) {
t->proxy_cred->free(t->proxy_cred);
}
if ((error = git_cred_userpass_plaintext_new(&t->proxy_cred, t->proxy_connection_data.user, t->proxy_connection_data.pass)) < 0)
goto on_error;
}
if (t->proxy_connection_data.use_ssl)
git_buf_PUTS(&processed_url, SCHEME_HTTPS);
else
git_buf_PUTS(&processed_url, SCHEME_HTTP);
git_buf_puts(&processed_url, t->proxy_connection_data.host);
if (t->proxy_connection_data.port)
git_buf_printf(&processed_url, ":%s", t->proxy_connection_data.port);
if (git_buf_oom(&processed_url)) {
giterr_set_oom();
error = -1;
goto on_error;
}
/* Convert URL to wide characters */
error = git__utf8_to_16_alloc(&proxy_wide, processed_url.ptr);
git_buf_free(&processed_url);
if (error < 0)
goto on_error;
proxy_info.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
proxy_info.lpszProxy = proxy_wide;
proxy_info.lpszProxyBypass = NULL;
if (!WinHttpSetOption(s->request,
WINHTTP_OPTION_PROXY,
&proxy_info,
sizeof(WINHTTP_PROXY_INFO))) {
giterr_set(GITERR_OS, "failed to set proxy");
git__free(proxy_wide);
goto on_error;
}
git__free(proxy_wide);
if (t->proxy_cred) {
if (t->proxy_cred->credtype == GIT_CREDTYPE_USERPASS_PLAINTEXT) {
if ((error = apply_userpass_credential_proxy(s->request, t->proxy_cred, t->auth_mechanisms)) < 0)
goto on_error;
}
}
}
/* Disable WinHTTP redirects so we can handle them manually. Why, you ask?
* http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/b2ff8879-ab9f-4218-8f09-16d25dff87ae
*/
if (!WinHttpSetOption(s->request,
WINHTTP_OPTION_DISABLE_FEATURE,
&disable_redirects,
sizeof(disable_redirects))) {
giterr_set(GITERR_OS, "failed to disable redirects");
goto on_error;
}
/* Strip unwanted headers (X-P2P-PeerDist, X-P2P-PeerDistEx) that WinHTTP
* adds itself. This option may not be supported by the underlying
* platform, so we do not error-check it */
WinHttpSetOption(s->request,
WINHTTP_OPTION_PEERDIST_EXTENSION_STATE,
&peerdist,
sizeof(peerdist));
/* Send Pragma: no-cache header */
if (!WinHttpAddRequestHeaders(s->request, pragma_nocache, (ULONG) -1L, WINHTTP_ADDREQ_FLAG_ADD)) {
giterr_set(GITERR_OS, "failed to add a header to the request");
goto on_error;
}
if (post_verb == s->verb) {
/* Send Content-Type and Accept headers -- only necessary on a POST */
git_buf_clear(&buf);
if (git_buf_printf(&buf,
"Content-Type: application/x-git-%s-request",
s->service) < 0)
goto on_error;
if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
giterr_set(GITERR_OS, "failed to convert content-type to wide characters");
goto on_error;
}
if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
giterr_set(GITERR_OS, "failed to add a header to the request");
goto on_error;
}
git_buf_clear(&buf);
if (git_buf_printf(&buf,
"Accept: application/x-git-%s-result",
s->service) < 0)
goto on_error;
if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
giterr_set(GITERR_OS, "failed to convert accept header to wide characters");
goto on_error;
}
if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
giterr_set(GITERR_OS, "failed to add a header to the request");
goto on_error;
}
}
for (i = 0; i < t->owner->custom_headers.count; i++) {
if (t->owner->custom_headers.strings[i]) {
git_buf_clear(&buf);
git_buf_puts(&buf, t->owner->custom_headers.strings[i]);
if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
giterr_set(GITERR_OS, "failed to convert custom header to wide characters");
goto on_error;
}
if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
giterr_set(GITERR_OS, "failed to add a header to the request");
goto on_error;
}
}
}
/* If requested, disable certificate validation */
if (t->connection_data.use_ssl) {
int flags;
if (t->owner->parent.read_flags(&t->owner->parent, &flags) < 0)
goto on_error;
}
/* If we have a credential on the subtransport, apply it to the request */
if (t->cred &&
t->cred->credtype == GIT_CREDTYPE_USERPASS_PLAINTEXT &&
apply_userpass_credential(s->request, t->auth_mechanisms, t->cred) < 0)
goto on_error;
else if (t->cred &&
t->cred->credtype == GIT_CREDTYPE_DEFAULT &&
apply_default_credentials(s->request, t->auth_mechanisms) < 0)
goto on_error;
/* If no other credentials have been applied and the URL has username and
* password, use those */
if (!t->cred && t->connection_data.user && t->connection_data.pass) {
if (!t->url_cred &&
git_cred_userpass_plaintext_new(&t->url_cred, t->connection_data.user, t->connection_data.pass) < 0)
goto on_error;
if (apply_userpass_credential(s->request, GIT_WINHTTP_AUTH_BASIC, t->url_cred) < 0)
goto on_error;
}
/* We've done everything up to calling WinHttpSendRequest. */
error = 0;
on_error:
if (error < 0)
winhttp_stream_close(s);
git__free(proxy_url);
git_buf_free(&buf);
return error;
}
static int parse_unauthorized_response(
HINTERNET request,
int *allowed_types,
int *allowed_mechanisms)
{
DWORD supported, first, target;
*allowed_types = 0;
*allowed_mechanisms = 0;
/* WinHttpQueryHeaders() must be called before WinHttpQueryAuthSchemes().
* We can assume this was already done, since we know we are unauthorized.
*/
if (!WinHttpQueryAuthSchemes(request, &supported, &first, &target)) {
giterr_set(GITERR_OS, "failed to parse supported auth schemes");
return -1;
}
if (WINHTTP_AUTH_SCHEME_NTLM & supported) {
*allowed_types |= GIT_CREDTYPE_USERPASS_PLAINTEXT;
*allowed_types |= GIT_CREDTYPE_DEFAULT;
*allowed_mechanisms = GIT_WINHTTP_AUTH_NEGOTIATE;
}
if (WINHTTP_AUTH_SCHEME_NEGOTIATE & supported) {
*allowed_types |= GIT_CREDTYPE_DEFAULT;
*allowed_mechanisms = GIT_WINHTTP_AUTH_NEGOTIATE;
}
if (WINHTTP_AUTH_SCHEME_BASIC & supported) {
*allowed_types |= GIT_CREDTYPE_USERPASS_PLAINTEXT;
*allowed_mechanisms |= GIT_WINHTTP_AUTH_BASIC;
}
if (WINHTTP_AUTH_SCHEME_DIGEST & supported) {
*allowed_types |= GIT_CREDTYPE_USERPASS_PLAINTEXT;
*allowed_mechanisms |= GIT_WINHTTP_AUTH_DIGEST;
}
return 0;
}
static int write_chunk(HINTERNET request, const char *buffer, size_t len)
{
DWORD bytes_written;
git_buf buf = GIT_BUF_INIT;
/* Chunk header */
git_buf_printf(&buf, "%X\r\n", len);
if (git_buf_oom(&buf))
return -1;
if (!WinHttpWriteData(request,
git_buf_cstr(&buf), (DWORD)git_buf_len(&buf),
&bytes_written)) {
git_buf_free(&buf);
giterr_set(GITERR_OS, "failed to write chunk header");
return -1;
}
git_buf_free(&buf);
/* Chunk body */
if (!WinHttpWriteData(request,
buffer, (DWORD)len,
&bytes_written)) {
giterr_set(GITERR_OS, "failed to write chunk");
return -1;
}
/* Chunk footer */
if (!WinHttpWriteData(request,
"\r\n", 2,
&bytes_written)) {
giterr_set(GITERR_OS, "failed to write chunk footer");
return -1;
}
return 0;
}
static int winhttp_close_connection(winhttp_subtransport *t)
{
int ret = 0;
if (t->connection) {
if (!WinHttpCloseHandle(t->connection)) {
giterr_set(GITERR_OS, "unable to close connection");
ret = -1;
}
t->connection = NULL;
}
if (t->session) {
if (!WinHttpCloseHandle(t->session)) {
giterr_set(GITERR_OS, "unable to close session");
ret = -1;
}
t->session = NULL;
}
return ret;
}
static int user_agent(git_buf *ua)
{
const char *custom = git_libgit2__user_agent();
git_buf_clear(ua);
git_buf_PUTS(ua, "git/1.0 (");
if (custom)
git_buf_puts(ua, custom);
else
git_buf_PUTS(ua, "libgit2 " LIBGIT2_VERSION);
return git_buf_putc(ua, ')');
}
static void CALLBACK winhttp_status(
HINTERNET connection,
DWORD_PTR ctx,
DWORD code,
LPVOID info,
DWORD info_len)
{
DWORD status;
if (code != WINHTTP_CALLBACK_STATUS_SECURE_FAILURE)
return;
status = *((DWORD *)info);
if ((status & WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID))
giterr_set(GITERR_NET, "SSL certificate issued for different common name");
else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID))
giterr_set(GITERR_NET, "SSL certificate has expired");
else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA))
giterr_set(GITERR_NET, "SSL certificate signed by unknown CA");
else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT))
giterr_set(GITERR_NET, "SSL certificate is invalid");
else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED))
giterr_set(GITERR_NET, "certificate revocation check failed");
else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED))
giterr_set(GITERR_NET, "SSL certificate was revoked");
else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR))
giterr_set(GITERR_NET, "security libraries could not be loaded");
else
giterr_set(GITERR_NET, "unknown security error %d", status);
}
static int winhttp_connect(
winhttp_subtransport *t)
{
wchar_t *wide_host;
int32_t port;
wchar_t *wide_ua;
git_buf ua = GIT_BUF_INIT;
int error = -1;
int default_timeout = TIMEOUT_INFINITE;
int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
t->session = NULL;
t->connection = NULL;
/* Prepare port */
if (git__strtol32(&port, t->connection_data.port, NULL, 10) < 0)
return -1;
/* Prepare host */
if (git__utf8_to_16_alloc(&wide_host, t->connection_data.host) < 0) {
giterr_set(GITERR_OS, "unable to convert host to wide characters");
return -1;
}
if ((error = user_agent(&ua)) < 0) {
git__free(wide_host);
return error;
}
if (git__utf8_to_16_alloc(&wide_ua, git_buf_cstr(&ua)) < 0) {
giterr_set(GITERR_OS, "unable to convert host to wide characters");
git__free(wide_host);
git_buf_free(&ua);
return -1;
}
git_buf_free(&ua);
/* Establish session */
t->session = WinHttpOpen(
wide_ua,
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS,
0);
if (!t->session) {
giterr_set(GITERR_OS, "failed to init WinHTTP");
goto on_error;
}
if (!WinHttpSetTimeouts(t->session, default_timeout, default_connect_timeout, default_timeout, default_timeout)) {
giterr_set(GITERR_OS, "failed to set timeouts for WinHTTP");
goto on_error;
}
/* Establish connection */
t->connection = WinHttpConnect(
t->session,
wide_host,
(INTERNET_PORT) port,
0);
if (!t->connection) {
giterr_set(GITERR_OS, "failed to connect to host");
goto on_error;
}
if (WinHttpSetStatusCallback(t->connection, winhttp_status, WINHTTP_CALLBACK_FLAG_SECURE_FAILURE, 0) == WINHTTP_INVALID_STATUS_CALLBACK) {
giterr_set(GITERR_OS, "failed to set status callback");
goto on_error;
}
error = 0;
on_error:
if (error < 0)
winhttp_close_connection(t);
git__free(wide_host);
git__free(wide_ua);
return error;
}
static int do_send_request(winhttp_stream *s, size_t len, int ignore_length)
{
if (ignore_length) {
if (!WinHttpSendRequest(s->request,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0,
WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) {
return -1;
}
} else {
if (!WinHttpSendRequest(s->request,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0,
len, 0)) {
return -1;
}
}
return 0;
}
static int send_request(winhttp_stream *s, size_t len, int ignore_length)
{
int request_failed = 0, cert_valid = 1, error = 0;
DWORD ignore_flags;
giterr_clear();
if ((error = do_send_request(s, len, ignore_length)) < 0) {
if (GetLastError() != ERROR_WINHTTP_SECURE_FAILURE) {
giterr_set(GITERR_OS, "failed to send request");
return -1;
}
request_failed = 1;
cert_valid = 0;
}
giterr_clear();
if ((error = certificate_check(s, cert_valid)) < 0) {
if (!giterr_last())
giterr_set(GITERR_OS, "user cancelled certificate check");
return error;
}
/* if neither the request nor the certificate check returned errors, we're done */
if (!request_failed)
return 0;
ignore_flags = no_check_cert_flags;
if (!WinHttpSetOption(s->request, WINHTTP_OPTION_SECURITY_FLAGS, &ignore_flags, sizeof(ignore_flags))) {
giterr_set(GITERR_OS, "failed to set security options");
return -1;
}
if ((error = do_send_request(s, len, ignore_length)) < 0)
giterr_set(GITERR_OS, "failed to send request");
return error;
}
static int winhttp_stream_read(
git_smart_subtransport_stream *stream,
char *buffer,
size_t buf_size,
size_t *bytes_read)
{
winhttp_stream *s = (winhttp_stream *)stream;
winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
DWORD dw_bytes_read;
char replay_count = 0;
int error;
replay:
/* Enforce a reasonable cap on the number of replays */
if (++replay_count >= 7) {
giterr_set(GITERR_NET, "too many redirects or authentication replays");
return -1;
}
/* Connect if necessary */
if (!s->request && winhttp_stream_connect(s) < 0)
return -1;
if (!s->received_response) {
DWORD status_code, status_code_length, content_type_length, bytes_written;
char expected_content_type_8[MAX_CONTENT_TYPE_LEN];
wchar_t expected_content_type[MAX_CONTENT_TYPE_LEN], content_type[MAX_CONTENT_TYPE_LEN];
if (!s->sent_request) {
if ((error = send_request(s, s->post_body_len, 0)) < 0)
return error;
s->sent_request = 1;
}
if (s->chunked) {
assert(s->verb == post_verb);
/* Flush, if necessary */
if (s->chunk_buffer_len > 0 &&
write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0)
return -1;
s->chunk_buffer_len = 0;
/* Write the final chunk. */
if (!WinHttpWriteData(s->request,
"0\r\n\r\n", 5,
&bytes_written)) {
giterr_set(GITERR_OS, "failed to write final chunk");
return -1;
}
}
else if (s->post_body) {
char *buffer;
DWORD len = s->post_body_len, bytes_read;
if (INVALID_SET_FILE_POINTER == SetFilePointer(s->post_body,
0, 0, FILE_BEGIN) &&
NO_ERROR != GetLastError()) {
giterr_set(GITERR_OS, "failed to reset file pointer");
return -1;
}
buffer = git__malloc(CACHED_POST_BODY_BUF_SIZE);
while (len > 0) {
DWORD bytes_written;
if (!ReadFile(s->post_body, buffer,
min(CACHED_POST_BODY_BUF_SIZE, len),
&bytes_read, NULL) ||
!bytes_read) {
git__free(buffer);
giterr_set(GITERR_OS, "failed to read from temp file");
return -1;
}
if (!WinHttpWriteData(s->request, buffer,
bytes_read, &bytes_written)) {
git__free(buffer);
giterr_set(GITERR_OS, "failed to write data");
return -1;
}
len -= bytes_read;
assert(bytes_read == bytes_written);
}
git__free(buffer);
/* Eagerly close the temp file */
CloseHandle(s->post_body);
s->post_body = NULL;
}
if (!WinHttpReceiveResponse(s->request, 0)) {
giterr_set(GITERR_OS, "failed to receive response");
return -1;
}
/* Verify that we got a 200 back */
status_code_length = sizeof(status_code);
if (!WinHttpQueryHeaders(s->request,
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
&status_code, &status_code_length,
WINHTTP_NO_HEADER_INDEX)) {
giterr_set(GITERR_OS, "failed to retrieve status code");
return -1;
}
/* The implementation of WinHTTP prior to Windows 7 will not
* redirect to an identical URI. Some Git hosters use self-redirects
* as part of their DoS mitigation strategy. Check first to see if we
* have a redirect status code, and that we haven't already streamed
* a post body. (We can't replay a streamed POST.) */
if (!s->chunked &&
(HTTP_STATUS_MOVED == status_code ||
HTTP_STATUS_REDIRECT == status_code ||
(HTTP_STATUS_REDIRECT_METHOD == status_code &&
get_verb == s->verb) ||
HTTP_STATUS_REDIRECT_KEEP_VERB == status_code)) {
/* Check for Windows 7. This workaround is only necessary on
* Windows Vista and earlier. Windows 7 is version 6.1. */
wchar_t *location;
DWORD location_length;
char *location8;
/* OK, fetch the Location header from the redirect. */
if (WinHttpQueryHeaders(s->request,
WINHTTP_QUERY_LOCATION,
WINHTTP_HEADER_NAME_BY_INDEX,
WINHTTP_NO_OUTPUT_BUFFER,
&location_length,
WINHTTP_NO_HEADER_INDEX) ||
GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
giterr_set(GITERR_OS, "failed to read Location header");
return -1;
}
location = git__malloc(location_length);
GITERR_CHECK_ALLOC(location);
if (!WinHttpQueryHeaders(s->request,
WINHTTP_QUERY_LOCATION,
WINHTTP_HEADER_NAME_BY_INDEX,
location,
&location_length,
WINHTTP_NO_HEADER_INDEX)) {
giterr_set(GITERR_OS, "failed to read Location header");
git__free(location);
return -1;
}
/* Convert the Location header to UTF-8 */
if (git__utf16_to_8_alloc(&location8, location) < 0) {
giterr_set(GITERR_OS, "failed to convert Location header to UTF-8");
git__free(location);
return -1;
}
git__free(location);
/* Replay the request */
winhttp_stream_close(s);
if (!git__prefixcmp_icase(location8, prefix_https)) {
/* Upgrade to secure connection; disconnect and start over */
if (gitno_connection_data_from_url(&t->connection_data, location8, s->service_url) < 0) {
git__free(location8);
return -1;
}
winhttp_close_connection(t);
if (winhttp_connect(t) < 0)
return -1;
}
git__free(location8);
goto replay;
}
/* Handle proxy authentication failures */
if (status_code == HTTP_STATUS_PROXY_AUTH_REQ) {
int allowed_types;
if (parse_unauthorized_response(s->request, &allowed_types, &t->auth_mechanisms) < 0)
return -1;
/* TODO: extract the username from the url, no payload? */
if (t->owner->proxy.credentials) {
int cred_error = 1;
cred_error = t->owner->proxy.credentials(&t->proxy_cred, t->owner->proxy.url, NULL, allowed_types, t->owner->proxy.payload);
if (cred_error < 0)
return cred_error;
}
winhttp_stream_close(s);
goto replay;
}
/* Handle authentication failures */
if (HTTP_STATUS_DENIED == status_code && get_verb == s->verb) {
int allowed_types;
if (parse_unauthorized_response(s->request, &allowed_types, &t->auth_mechanisms) < 0)
return -1;
if (allowed_types) {
int cred_error = 1;
git_cred_free(t->cred);
t->cred = NULL;
/* Start with the user-supplied credential callback, if present */
if (t->owner->cred_acquire_cb) {
cred_error = t->owner->cred_acquire_cb(&t->cred, t->owner->url,
t->connection_data.user, allowed_types, t->owner->cred_acquire_payload);
/* Treat GIT_PASSTHROUGH as though git_cred_acquire_cb isn't set */
if (cred_error == GIT_PASSTHROUGH)
cred_error = 1;
else if (cred_error < 0)
return cred_error;
}
/* Invoke the fallback credentials acquisition callback if necessary */
if (cred_error > 0) {
cred_error = fallback_cred_acquire_cb(&t->cred, t->owner->url,
t->connection_data.user, allowed_types, NULL);
if (cred_error < 0)
return cred_error;
}
if (!cred_error) {
assert(t->cred);
winhttp_stream_close(s);
/* Successfully acquired a credential */
goto replay;
}
}
}
if (HTTP_STATUS_OK != status_code) {
giterr_set(GITERR_NET, "request failed with status code: %d", status_code);
return -1;
}
/* Verify that we got the correct content-type back */
if (post_verb == s->verb)
p_snprintf(expected_content_type_8, MAX_CONTENT_TYPE_LEN, "application/x-git-%s-result", s->service);
else
p_snprintf(expected_content_type_8, MAX_CONTENT_TYPE_LEN, "application/x-git-%s-advertisement", s->service);
if (git__utf8_to_16(expected_content_type, MAX_CONTENT_TYPE_LEN, expected_content_type_8) < 0) {
giterr_set(GITERR_OS, "failed to convert expected content-type to wide characters");
return -1;
}
content_type_length = sizeof(content_type);
if (!WinHttpQueryHeaders(s->request,
WINHTTP_QUERY_CONTENT_TYPE,
WINHTTP_HEADER_NAME_BY_INDEX,
&content_type, &content_type_length,
WINHTTP_NO_HEADER_INDEX)) {
giterr_set(GITERR_OS, "failed to retrieve response content-type");
return -1;
}
if (wcscmp(expected_content_type, content_type)) {
giterr_set(GITERR_NET, "received unexpected content-type");
return -1;
}
s->received_response = 1;
}
if (!WinHttpReadData(s->request,
(LPVOID)buffer,
(DWORD)buf_size,
&dw_bytes_read))
{
giterr_set(GITERR_OS, "failed to read data");
return -1;
}
*bytes_read = dw_bytes_read;
return 0;
}
static int winhttp_stream_write_single(
git_smart_subtransport_stream *stream,
const char *buffer,
size_t len)
{
winhttp_stream *s = (winhttp_stream *)stream;
DWORD bytes_written;
int error;
if (!s->request && winhttp_stream_connect(s) < 0)
return -1;
/* This implementation of write permits only a single call. */
if (s->sent_request) {
giterr_set(GITERR_NET, "subtransport configured for only one write");
return -1;
}
if ((error = send_request(s, len, 0)) < 0)
return error;
s->sent_request = 1;
if (!WinHttpWriteData(s->request,
(LPCVOID)buffer,
(DWORD)len,
&bytes_written)) {
giterr_set(GITERR_OS, "failed to write data");
return -1;
}
assert((DWORD)len == bytes_written);
return 0;
}
static int put_uuid_string(LPWSTR buffer, size_t buffer_len_cch)
{
UUID uuid;
RPC_STATUS status = UuidCreate(&uuid);
int result;
if (RPC_S_OK != status &&
RPC_S_UUID_LOCAL_ONLY != status &&
RPC_S_UUID_NO_ADDRESS != status) {
giterr_set(GITERR_NET, "unable to generate name for temp file");
return -1;
}
if (buffer_len_cch < UUID_LENGTH_CCH + 1) {
giterr_set(GITERR_NET, "buffer too small for name of temp file");
return -1;
}
#if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
result = swprintf_s(buffer, buffer_len_cch,
#else
result = wsprintfW(buffer,
#endif
L"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x",
uuid.Data1, uuid.Data2, uuid.Data3,
uuid.Data4[0], uuid.Data4[1], uuid.Data4[2], uuid.Data4[3],
uuid.Data4[4], uuid.Data4[5], uuid.Data4[6], uuid.Data4[7]);
if (result < UUID_LENGTH_CCH) {
giterr_set(GITERR_OS, "unable to generate name for temp file");
return -1;
}
return 0;
}
static int get_temp_file(LPWSTR buffer, DWORD buffer_len_cch)
{
size_t len;
if (!GetTempPathW(buffer_len_cch, buffer)) {
giterr_set(GITERR_OS, "failed to get temp path");
return -1;
}
len = wcslen(buffer);
if (buffer[len - 1] != '\\' && len < buffer_len_cch)
buffer[len++] = '\\';
if (put_uuid_string(&buffer[len], (size_t)buffer_len_cch - len) < 0)
return -1;
return 0;
}
static int winhttp_stream_write_buffered(
git_smart_subtransport_stream *stream,
const char *buffer,
size_t len)
{
winhttp_stream *s = (winhttp_stream *)stream;
DWORD bytes_written;
if (!s->request && winhttp_stream_connect(s) < 0)
return -1;
/* Buffer the payload, using a temporary file so we delegate
* memory management of the data to the operating system. */
if (!s->post_body) {
wchar_t temp_path[MAX_PATH + 1];
if (get_temp_file(temp_path, MAX_PATH + 1) < 0)
return -1;
s->post_body = CreateFileW(temp_path,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_DELETE, NULL,
CREATE_NEW,
FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (INVALID_HANDLE_VALUE == s->post_body) {
s->post_body = NULL;
giterr_set(GITERR_OS, "failed to create temporary file");
return -1;
}
}
if (!WriteFile(s->post_body, buffer, (DWORD)len, &bytes_written, NULL)) {
giterr_set(GITERR_OS, "failed to write to temporary file");
return -1;
}
assert((DWORD)len == bytes_written);
s->post_body_len += bytes_written;
return 0;
}
static int winhttp_stream_write_chunked(
git_smart_subtransport_stream *stream,
const char *buffer,
size_t len)
{
winhttp_stream *s = (winhttp_stream *)stream;
int error;
if (!s->request && winhttp_stream_connect(s) < 0)
return -1;
if (!s->sent_request) {
/* Send Transfer-Encoding: chunked header */
if (!WinHttpAddRequestHeaders(s->request,
transfer_encoding, (ULONG) -1L,
WINHTTP_ADDREQ_FLAG_ADD)) {
giterr_set(GITERR_OS, "failed to add a header to the request");
return -1;
}
if ((error = send_request(s, 0, 1)) < 0)
return error;
s->sent_request = 1;
}
if (len > CACHED_POST_BODY_BUF_SIZE) {
/* Flush, if necessary */
if (s->chunk_buffer_len > 0) {
if (write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0)
return -1;
s->chunk_buffer_len = 0;
}
/* Write chunk directly */
if (write_chunk(s->request, buffer, len) < 0)
return -1;
}
else {
/* Append as much to the buffer as we can */
int count = (int)min(CACHED_POST_BODY_BUF_SIZE - s->chunk_buffer_len, len);
if (!s->chunk_buffer)
s->chunk_buffer = git__malloc(CACHED_POST_BODY_BUF_SIZE);
memcpy(s->chunk_buffer + s->chunk_buffer_len, buffer, count);
s->chunk_buffer_len += count;
buffer += count;
len -= count;
/* Is the buffer full? If so, then flush */
if (CACHED_POST_BODY_BUF_SIZE == s->chunk_buffer_len) {
if (write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0)
return -1;
s->chunk_buffer_len = 0;
/* Is there any remaining data from the source? */
if (len > 0) {
memcpy(s->chunk_buffer, buffer, len);
s->chunk_buffer_len = (unsigned int)len;
}
}
}
return 0;
}
static void winhttp_stream_free(git_smart_subtransport_stream *stream)
{
winhttp_stream *s = (winhttp_stream *)stream;
winhttp_stream_close(s);
git__free(s);
}
static int winhttp_stream_alloc(winhttp_subtransport *t, winhttp_stream **stream)
{
winhttp_stream *s;
if (!stream)
return -1;
s = git__calloc(1, sizeof(winhttp_stream));
GITERR_CHECK_ALLOC(s);
s->parent.subtransport = &t->parent;
s->parent.read = winhttp_stream_read;
s->parent.write = winhttp_stream_write_single;
s->parent.free = winhttp_stream_free;
*stream = s;
return 0;
}
static int winhttp_uploadpack_ls(
winhttp_subtransport *t,
winhttp_stream *s)
{
GIT_UNUSED(t);
s->service = upload_pack_service;
s->service_url = upload_pack_ls_service_url;
s->verb = get_verb;
return 0;
}
static int winhttp_uploadpack(
winhttp_subtransport *t,
winhttp_stream *s)
{
GIT_UNUSED(t);
s->service = upload_pack_service;
s->service_url = upload_pack_service_url;
s->verb = post_verb;
return 0;
}
static int winhttp_receivepack_ls(
winhttp_subtransport *t,
winhttp_stream *s)
{
GIT_UNUSED(t);
s->service = receive_pack_service;
s->service_url = receive_pack_ls_service_url;
s->verb = get_verb;
return 0;
}
static int winhttp_receivepack(
winhttp_subtransport *t,
winhttp_stream *s)
{
GIT_UNUSED(t);
/* WinHTTP only supports Transfer-Encoding: chunked
* on Windows Vista (NT 6.0) and higher. */
s->chunked = git_has_win32_version(6, 0, 0);
if (s->chunked)
s->parent.write = winhttp_stream_write_chunked;
else
s->parent.write = winhttp_stream_write_buffered;
s->service = receive_pack_service;
s->service_url = receive_pack_service_url;
s->verb = post_verb;
return 0;
}
static int winhttp_action(
git_smart_subtransport_stream **stream,
git_smart_subtransport *subtransport,
const char *url,
git_smart_service_t action)
{
winhttp_subtransport *t = (winhttp_subtransport *)subtransport;
winhttp_stream *s;
int ret = -1;
if (!t->connection)
if ((ret = gitno_connection_data_from_url(&t->connection_data, url, NULL)) < 0 ||
(ret = winhttp_connect(t)) < 0)
return ret;
if (winhttp_stream_alloc(t, &s) < 0)
return -1;
if (!stream)
return -1;
switch (action)
{
case GIT_SERVICE_UPLOADPACK_LS:
ret = winhttp_uploadpack_ls(t, s);
break;
case GIT_SERVICE_UPLOADPACK:
ret = winhttp_uploadpack(t, s);
break;
case GIT_SERVICE_RECEIVEPACK_LS:
ret = winhttp_receivepack_ls(t, s);
break;
case GIT_SERVICE_RECEIVEPACK:
ret = winhttp_receivepack(t, s);
break;
default:
assert(0);
}
if (!ret)
*stream = &s->parent;
return ret;
}
static int winhttp_close(git_smart_subtransport *subtransport)
{
winhttp_subtransport *t = (winhttp_subtransport *)subtransport;
gitno_connection_data_free_ptrs(&t->connection_data);
memset(&t->connection_data, 0x0, sizeof(gitno_connection_data));
gitno_connection_data_free_ptrs(&t->proxy_connection_data);
memset(&t->proxy_connection_data, 0x0, sizeof(gitno_connection_data));
if (t->cred) {
t->cred->free(t->cred);
t->cred = NULL;
}
if (t->proxy_cred) {
t->proxy_cred->free(t->proxy_cred);
t->proxy_cred = NULL;
}
if (t->url_cred) {
t->url_cred->free(t->url_cred);
t->url_cred = NULL;
}
return winhttp_close_connection(t);
}
static void winhttp_free(git_smart_subtransport *subtransport)
{
winhttp_subtransport *t = (winhttp_subtransport *)subtransport;
winhttp_close(subtransport);
git__free(t);
}
int git_smart_subtransport_http(git_smart_subtransport **out, git_transport *owner, void *param)
{
winhttp_subtransport *t;
GIT_UNUSED(param);
if (!out)
return -1;
t = git__calloc(1, sizeof(winhttp_subtransport));
GITERR_CHECK_ALLOC(t);
t->owner = (transport_smart *)owner;
t->parent.action = winhttp_action;
t->parent.close = winhttp_close;
t->parent.free = winhttp_free;
*out = (git_smart_subtransport *) t;
return 0;
}
#endif /* GIT_WINHTTP */
|
the_stack_data/292308.c | // Check that ld gets arch_multiple.
// RUN: %clang -target i386-apple-darwin9 -arch i386 -arch x86_64 %s -### -o foo 2> %t.log
// RUN: grep '".*ld.*" .*"-arch_multiple" "-final_output" "foo"' %t.log
// Make sure we run dsymutil on source input files.
// RUN: %clang -target i386-apple-darwin9 -### -g %s -o BAR 2> %t.log
// RUN: grep '".*dsymutil" "-o" "BAR.dSYM" "BAR"' %t.log
// RUN: %clang -target i386-apple-darwin9 -### -g -filelist FOO %s -o BAR 2> %t.log
// RUN: grep '".*dsymutil" "-o" "BAR.dSYM" "BAR"' %t.log
// Check linker changes that came with new linkedit format.
// RUN: touch %t.o
// RUN: %clang -target i386-apple-darwin9 -### -arch armv6 -miphoneos-version-min=3.0 %t.o 2> %t.log
// RUN: %clang -target i386-apple-darwin9 -### -arch armv6 -miphoneos-version-min=3.0 -dynamiclib %t.o 2>> %t.log
// RUN: %clang -target i386-apple-darwin9 -### -arch armv6 -miphoneos-version-min=3.0 -bundle %t.o 2>> %t.log
// RUN: FileCheck -check-prefix=LINK_IPHONE_3_0 %s < %t.log
// LINK_IPHONE_3_0: {{ld(.exe)?"}}
// LINK_IPHONE_3_0-NOT: -lcrt1.3.1.o
// LINK_IPHONE_3_0: -lcrt1.o
// LINK_IPHONE_3_0: -lSystem
// LINK_IPHONE_3_0: {{ld(.exe)?"}}
// LINK_IPHONE_3_0: -dylib
// LINK_IPHONE_3_0: -ldylib1.o
// LINK_IPHONE_3_0: -lSystem
// LINK_IPHONE_3_0: {{ld(.exe)?"}}
// LINK_IPHONE_3_0: -lbundle1.o
// LINK_IPHONE_3_0: -lSystem
// RUN: %clang -target i386-apple-darwin9 -### -arch armv7 -miphoneos-version-min=3.1 %t.o 2> %t.log
// RUN: %clang -target i386-apple-darwin9 -### -arch armv7 -miphoneos-version-min=3.1 -dynamiclib %t.o 2>> %t.log
// RUN: %clang -target i386-apple-darwin9 -### -arch armv7 -miphoneos-version-min=3.1 -bundle %t.o 2>> %t.log
// RUN: FileCheck -check-prefix=LINK_IPHONE_3_1 %s < %t.log
// LINK_IPHONE_3_1: {{ld(.exe)?"}}
// LINK_IPHONE_3_1-NOT: -lcrt1.o
// LINK_IPHONE_3_1: -lcrt1.3.1.o
// LINK_IPHONE_3_1: -lSystem
// LINK_IPHONE_3_1: {{ld(.exe)?"}}
// LINK_IPHONE_3_1: -dylib
// LINK_IPHONE_3_1-NOT: -ldylib1.o
// LINK_IPHONE_3_1: -lSystem
// LINK_IPHONE_3_1: {{ld(.exe)?"}}
// LINK_IPHONE_3_1-NOT: -lbundle1.o
// LINK_IPHONE_3_1: -lSystem
// RUN: %clang -target i386-apple-darwin9 -### -fpie %t.o 2> %t.log
// RUN: FileCheck -check-prefix=LINK_EXPLICIT_PIE %s < %t.log
//
// LINK_EXPLICIT_PIE: {{ld(.exe)?"}}
// LINK_EXPLICIT_PIE: "-pie"
// RUN: %clang -target i386-apple-darwin9 -### -fno-pie %t.o 2> %t.log
// RUN: FileCheck -check-prefix=LINK_EXPLICIT_NO_PIE %s < %t.log
//
// LINK_EXPLICIT_NO_PIE: {{ld(.exe)?"}}
// LINK_EXPLICIT_NO_PIE: "-no_pie"
// RUN: %clang -target x86_64-apple-darwin10 -### %t.o \
// RUN: -mlinker-version=100 2> %t.log
// RUN: FileCheck -check-prefix=LINK_NEWER_DEMANGLE %s < %t.log
//
// LINK_NEWER_DEMANGLE: {{ld(.exe)?"}}
// LINK_NEWER_DEMANGLE: "-demangle"
// RUN: %clang -target x86_64-apple-darwin10 -### %t.o \
// RUN: -mlinker-version=100 -Wl,--no-demangle 2> %t.log
// RUN: FileCheck -check-prefix=LINK_NEWER_NODEMANGLE %s < %t.log
//
// LINK_NEWER_NODEMANGLE: {{ld(.exe)?"}}
// LINK_NEWER_NODEMANGLE-NOT: "-demangle"
// LINK_NEWER_NODEMANGLE: "-lSystem"
// RUN: %clang -target x86_64-apple-darwin10 -### %t.o \
// RUN: -mlinker-version=95 2> %t.log
// RUN: FileCheck -check-prefix=LINK_OLDER_NODEMANGLE %s < %t.log
//
// LINK_OLDER_NODEMANGLE: {{ld(.exe)?"}}
// LINK_OLDER_NODEMANGLE-NOT: "-demangle"
// LINK_OLDER_NODEMANGLE: "-lSystem"
// RUN: %clang -target x86_64-apple-darwin10 -### %s \
// RUN: -mlinker-version=117 -flto 2> %t.log
// RUN: cat %t.log
// RUN: FileCheck -check-prefix=LINK_OBJECT_LTO_PATH %s < %t.log
//
// LINK_OBJECT_LTO_PATH: {{ld(.exe)?"}}
// LINK_OBJECT_LTO_PATH: "-object_path_lto"
// RUN: %clang -target x86_64-apple-darwin10 -### %t.o \
// RUN: -force_load a -force_load b 2> %t.log
// RUN: cat %t.log
// RUN: FileCheck -check-prefix=FORCE_LOAD %s < %t.log
//
// FORCE_LOAD: {{ld(.exe)?"}}
// FORCE_LOAD: "-force_load" "a" "-force_load" "b"
// RUN: %clang -target x86_64-apple-darwin10 -### %t.o \
// RUN: -lazy_framework Framework 2> %t.log
//
// RUN: FileCheck -check-prefix=LINK_LAZY_FRAMEWORK %s < %t.log
// LINK_LAZY_FRAMEWORK: {{ld(.exe)?"}}
// LINK_LAZY_FRAMEWORK: "-lazy_framework" "Framework"
// RUN: %clang -target x86_64-apple-darwin10 -### %t.o \
// RUN: -lazy_library Library 2> %t.log
//
// RUN: FileCheck -check-prefix=LINK_LAZY_LIBRARY %s < %t.log
// LINK_LAZY_LIBRARY: {{ld(.exe)?"}}
// LINK_LAZY_LIBRARY: "-lazy_library" "Library"
// RUN: %clang -target x86_64-apple-darwin10 -### %t.o 2> %t.log
// RUN: %clang -target x86_64-apple-macosx10.7 -### %t.o 2>> %t.log
// RUN: FileCheck -check-prefix=LINK_VERSION_MIN %s < %t.log
// LINK_VERSION_MIN: {{ld(.exe)?"}}
// LINK_VERSION_MIN: "-macosx_version_min" "10.6.0"
// LINK_VERSION_MIN: {{ld(.exe)?"}}
// LINK_VERSION_MIN: "-macosx_version_min" "10.7.0"
// RUN: %clang -target x86_64-apple-darwin12 -### %t.o 2> %t.log
// RUN: FileCheck -check-prefix=LINK_NO_CRT1 %s < %t.log
// LINK_NO_CRT1-NOT: crt
// RUN: %clang -target armv7-apple-ios6.0 -miphoneos-version-min=6.0 -### %t.o 2> %t.log
// RUN: FileCheck -check-prefix=LINK_NO_IOS_CRT1 %s < %t.log
// LINK_NO_IOS_CRT1-NOT: crt
// RUN: %clang -target i386-apple-darwin12 -pg -### %t.o 2> %t.log
// RUN: FileCheck -check-prefix=LINK_PG %s < %t.log
// LINK_PG: -lgcrt1.o
// LINK_PG: -no_new_main
// RUN: %clang -target x86_64-apple-darwin12 -rdynamic -### %t.o \
// RUN: -mlinker-version=100 2> %t.log
// RUN: FileCheck -check-prefix=LINK_NO_EXPORT_DYNAMIC %s < %t.log
// LINK_NO_EXPORT_DYNAMIC: {{ld(.exe)?"}}
// LINK_NO_EXPORT_DYNAMIC-NOT: "-export_dynamic"
// RUN: %clang -target x86_64-apple-darwin12 -rdynamic -### %t.o \
// RUN: -mlinker-version=137 2> %t.log
// RUN: FileCheck -check-prefix=LINK_EXPORT_DYNAMIC %s < %t.log
// LINK_EXPORT_DYNAMIC: {{ld(.exe)?"}}
// LINK_EXPORT_DYNAMIC: "-export_dynamic"
|
the_stack_data/75137251.c | #include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
int main(int argc, char** argv) {
if (mkdir("/tmp", S_IRWXG) != 0 && errno != EEXIST) {
printf("Unable to create dir '/tmp'\n");
return -1;
}
if (mkdir("/tmp/1", S_IRWXG) != 0 && errno != EEXIST) {
printf("Unable to create dir '/tmp/1'\n");
return -1;
}
if (mkdir("/tmp/1/", S_IRWXG) != 0 && errno != EEXIST) {
printf("Unable to create dir '/tmp/1/'\n");
return -1;
}
DIR *dir = opendir("/tmp");
if (!dir) {
printf("Unable to open dir '/tmp'\n");
return -2;
}
struct dirent *dirent;
while ((dirent = readdir(dir)) != 0) {
printf("Found '%s'\n", dirent->d_name);
if (strlen(dirent->d_name) == 0) {
printf("Found empty path!\n");
return -3;
}
}
closedir(dir);
printf("success\n");
#ifdef REPORT_RESULT
int result = 0;
REPORT_RESULT();
#endif
return 0;
}
|
the_stack_data/15516.c | #include <stdlib.h>
/* PR rtl-optimization/28970 */
/* Origin: Peter Bergner <[email protected]> */
extern void abort (void);
int tar (long i)
{
if (i != 36863)
abort ();
return -1;
}
void bug(int q, long bcount)
{
int j = 0;
int outgo = 0;
while(j != -1)
{
outgo++;
if (outgo > q-1)
outgo = q-1;
j = tar (outgo*bcount);
}
}
int main(void)
{
bug(5, 36863);
return 0;
}
|
the_stack_data/32250.c | //file: _insn_test_xori_X0.c
//op=334
#include <stdio.h>
#include <stdlib.h>
void func_exit(void) {
printf("%s\n", __func__);
exit(0);
}
void func_call(void) {
printf("%s\n", __func__);
exit(0);
}
unsigned long mem[2] = { 0x2f6c6cfee316d7, 0x334d1321b4c11950 };
int main(void) {
unsigned long a[4] = { 0, 0 };
asm __volatile__ (
"moveli r46, 31370\n"
"shl16insli r46, r46, -7442\n"
"shl16insli r46, r46, 26409\n"
"shl16insli r46, r46, 25903\n"
"moveli r40, 2219\n"
"shl16insli r40, r40, -14686\n"
"shl16insli r40, r40, 5250\n"
"shl16insli r40, r40, 16891\n"
"{ xori r46, r40, 75 ; fnop }\n"
"move %0, r46\n"
"move %1, r40\n"
:"=r"(a[0]),"=r"(a[1]));
printf("%016lx\n", a[0]);
printf("%016lx\n", a[1]);
return 0;
}
|
the_stack_data/123576718.c | #include <stdio.h>
int main(){
int count;
printf("AB%n", &count);
printf("\n%d characters printed\n", count);
}
|
the_stack_data/1163376.c | /*
* tests/libFLAC_assert_clash.c
*
* test if libFLAC <assert.h> will clash with the standard one.
* see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=705601
*/
#include <assert.h>
int
main(int argc, char *argv[])
{
assert(1);
return (0);
}
|
the_stack_data/453676.c | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXOP 100
#define NUMBER '0'
#define MAXVAL 100 // maximum depth of val stack
#define BUFSIZE 100
int sp = 0; // next free stack position
double val[MAXVAL]; // value stack
char buf[BUFSIZE]; // buffer for ungetch
int bufp = 0; // next free position in buf
int getop(char[]);
void push(double);
double pop(void);
int getch(void);
void ungetch(int);
int main()
{
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF)
{
switch (type)
{
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop ());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
{
push(pop() / op2);
}
else
{
printf("error: division by zero\n");
}
break;
case '%':
op2 = pop();
push((int) pop() % (int) op2);
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
printf("error: unknown command\n");
break;
}
}
return 0;
}
// push: push f onto value stack
void push(double f)
{
if (sp < MAXVAL)
{
val[sp++] = f;
}
else
{
printf("error: stack full, can't push %g\n", f);
}
}
// pop: pop and return top value from stack
double pop(void)
{
if (sp > 0)
{
return val[--sp];
}
else
{
printf("error: stack empty\n");
return 0.0;
}
}
//getop: get next operator or numeric operand
int getop(char s[])
{
int i, c;
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if (!isdigit(c) && c != '.')
return c; // not a number
i = 0;
// collect an integer
if (isdigit(c))
{
// collect integer part
while (isdigit(s[++i] = c = getch()))
;
}
if (c == '.')
{
// collect fraction part
while (isdigit(s[++i] = c = getch()))
;
}
s[i] = '\0';
if (c != EOF)
ungetch(c);
return NUMBER;
}
// gets a (possible pushed back) character
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
//pushes a character back onto the input
void ungetch(int c)
{
if (bufp >= BUFSIZE)
{
printf("ungetch: too many characters");
}
else
{
buf[bufp++] = c;
}
}
|
the_stack_data/192331549.c | #include <stdio.h>
int main(void) {
float value1, value2;
char operator;
printf ("Type in your expression.\n");
scanf ("%f %c %f", &value1, &operator, &value2);
switch (operator)
{
case '+':
printf ("%.2f\n", value1 + value2);
break;
case '-':
printf ("%.2f\n", value1 - value2);
break;
case '*':
printf ("%.2f\n", value1 * value2);
break;
case '/':
printf ("%.2f\n", value1 / value2);
break;
default:
printf ("Unknown operator.\n");
break;
}
return 0;
} |
the_stack_data/2915.c | #include <stdio.h>
#include <immintrin.h>
void somma(int A[4], int B[4], int C[4]) {
C[0] = A[0] + B[0];
C[1] = A[1] + B[1];
C[2] = A[2] + B[2];
C[3] = A[3] + B[3];
}
void somma_sse(int A[4], int B[4], int C[4]) {
__m128i a, b, c;
a = _mm_loadu_si128((const __m128i*)A);
b = _mm_loadu_si128((const __m128i*)B);
c = _mm_add_epi32(a,b);
_mm_storeu_si128((__m128i*)C, c);
}
int main() {
int A[4] = { 1, 2, 3, 4 };
int B[4] = { 4, 3, 2, 1 };
int C[4];
somma_sse(A,B,C);
printf("%d %d %d %d\n", C[0], C[1], C[2], C[3]); // stampa 5 5 5 5
return 0;
}
|
the_stack_data/900386.c | #include <err.h>
#include <errno.h>
#include <libgen.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
/*
* constants
*/
static const unsigned short RULES[3][3] = {
{0, 1, 0},
{1, 1, 2},
{0, 2, 2}
};
static const short DIRS[4][2] = {
{-1, 0},
{ 0, -1},
{ 1, 0},
{ 0, 1}
};
static const char *COLORS[3] = {
"016 032 041",
"113 170 197",
"201 100 126"
};
/*
* helper functions
*/
static void
usage(char *name)
{
fprintf(
stderr,
"usage : %s [-whi <number>]\n\n"
"options :\n"
" -w <number> set width to <number> (default : 500)\n"
" -h <number> set height to <number> (default : 500)\n"
" -i <number> iterate <number> times (default : 500)\n",
basename(name));
exit(1);
}
static unsigned
convert_to_number(const char *str)
{
errno = 0;
char *ptr;
long number;
if ((number = strtol(str, &ptr, 10)) < 0 || errno != 0 || *ptr != 0)
errx(1, "'%s' isn't a valid positive integer", str);
return number;
}
static void *
allocate(size_t size)
{
void *ptr;
if ((ptr = calloc(1, size)) == NULL)
errx(1, "failed to allocate memory");
return ptr;
}
static inline unsigned
wrap(unsigned coord, long offset, unsigned bound)
{
return ((long)coord + offset + bound) % bound;
}
/*
* main function
*/
static void
rps(unsigned width, unsigned height, unsigned iter)
{
/* init array */
unsigned short ***uni;
uni = allocate(height * sizeof(*uni));
for (unsigned i = 0; i < height; ++i) {
uni[i] = allocate(width * sizeof(*uni[i]));
for (unsigned j = 0; j < width; ++j)
uni[i][j] = allocate(2 * sizeof(*uni[i][j]));
}
bool flag = 0;
for (unsigned i = 0; i < height; ++i)
for (unsigned j = 0; j < width; ++j)
uni[rand() % height][rand() % width][flag] = rand() % 3;
/* run rock paper scissor */
unsigned short tmp;
for (unsigned n = 0; n < iter; ++n) {
printf("P3\n%u %u\n255\n", width, height);
for (unsigned i = 0; i < height; ++i)
for (unsigned j = 0; j < width; ++j) {
puts(COLORS[uni[i][j][flag]]);
tmp = rand() % 4;
uni[i][j][!flag] = RULES[uni[i][j][flag]]
[uni[wrap(i, DIRS[tmp][0], height)][wrap(j, DIRS[tmp][1], width)][flag]];
}
flag ^= 1;
}
/* cleanup */
for (unsigned i = 0; i < height; ++i) {
for (unsigned j = 0; j < width; ++j)
free(uni[i][j]);
free(uni[i]);
}
free(uni);
}
int
main(int argc, char **argv)
{
/* argument parsing */
unsigned width = 500;
unsigned height = 500;
unsigned iter = 500;
for (int arg; (arg = getopt(argc, argv, ":w:h:i:")) != -1;)
switch (arg) {
case 'w': width = convert_to_number(optarg); break;
case 'h': height = convert_to_number(optarg); break;
case 'i': iter = convert_to_number(optarg); break;
default :
usage(argv[0]);
}
if (optind < argc)
usage(argv[0]);
srand(time(NULL));
rps(width, height, iter);
return 0;
}
|
the_stack_data/132953569.c | #include<stdio.h>
#include<stdlib.h>
struct Element {
int i;
int j;
int x;
};
struct Sparse {
int n;
int m;
int num;
struct Element *ele;
};
void create(struct Sparse *s) {
int i;
printf("Enter dimensions: ");
scanf("%d %d", &s->n, &s->m);
printf("Enter number of non-zero elements: ");
scanf("%d", &s->num);
s->ele = (struct Element *)malloc(s->num*(sizeof(struct Element)));
printf("Enter non-zero elements, i, j, x:\n");
for (i=0; i<s->num; i++)
scanf("%d %d %d", &s->ele[i].i, &s->ele[i].j, &s->ele[i].x);
}
void display(struct Sparse s) {
int i, j, k=0;
for (i=0; i<s.n; i++) {
for (j=0; j<s.m; j++) {
if (i == s.ele[k].i && j == s.ele[k].j)
printf("%d ", s.ele[k++].x);
else
printf("0 ");
}
printf("\n");
}
}
struct Sparse * add(struct Sparse s1, struct Sparse *s2) {
struct Sparse *sum;
int i, j, k;
i=j=k=0;
if (s1.n != s2->n || s1.m != s2->m) {
printf("Wrong dimensions, can not add matrices\n");
return NULL;
}
sum = (struct Sparse *)malloc(sizeof(struct Sparse));
sum->ele = (struct Element *)malloc((s1.num + s2->num)*sizeof(struct Element));
/*
sum->ele[k] = s1->ele[i] copy all elements of struct such as:
sum->ele[k].i = sum->ele[i].i;
sum->ele[k].j = sum->ele[i].j;
sum->ele[k].x = sum->ele[i].x;
*/
while (i<s1.num && j<s2->num) {
if (s1.ele[i].i < s2->ele[j].i)
sum->ele[k++] = s1.ele[i++];
else if (s1.ele[i].i > s2->ele[j].i)
sum->ele[k++] = s2->ele[j++];
else {
if (s1.ele[i].j < s2->ele[j].j)
sum->ele[k++] = s1.ele[i++];
else if (s1.ele[i].j > s2->ele[j].j)
sum->ele[k++] = s2->ele[j++];
else {
sum->ele[k] = s1.ele[i];
sum->ele[k++].x = s1.ele[i++].x + s2->ele[j++].x;
}
}
}
for (; i<s1.num; i++) sum->ele[k++] = s1.ele[i];
for (; j<s2->num; j++) sum->ele[k++] = s2->ele[j];
sum->n = s1.n;
sum->m = s2->m;
sum->num = k;
return sum;
};
int main() {
struct Sparse s1, s2, *s3;
create(&s1);
create(&s2);
s3 = add(s1, &s2);
printf("First matrix:\n");
display(s1);
printf("Second matrix:\n");
display(s2);
printf("Total matrix:\n");
display(*s3);
return 0;
}
|
the_stack_data/150141143.c | /*
File: printf.c
Copyright (C) 2004 Kustaa Nyholm
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "printf.h"
typedef void (*putcf) (void*,char);
static putcf stdout_putf;
static void* stdout_putp;
#ifdef PRINTF_LONG_SUPPORT
static void uli2a(unsigned long int num, unsigned int base, int uc,char * bf)
{
int n=0;
unsigned int d=1;
while (num/d >= base)
d*=base;
while (d!=0) {
int dgt = num / d;
num%=d;
d/=base;
if (n || dgt>0|| d==0) {
*bf++ = dgt+(dgt<10 ? '0' : (uc ? 'A' : 'a')-10);
++n;
}
}
*bf=0;
}
static void li2a (long num, char * bf)
{
if (num<0) {
num=-num;
*bf++ = '-';
}
uli2a(num,10,0,bf);
}
#endif
static void ui2a(unsigned int num, unsigned int base, int uc,char * bf)
{
int n=0;
unsigned int d=1;
while (num/d >= base)
d*=base;
while (d!=0) {
int dgt = num / d;
num%= d;
d/=base;
if (n || dgt>0 || d==0) {
*bf++ = dgt+(dgt<10 ? '0' : (uc ? 'A' : 'a')-10);
++n;
}
}
*bf=0;
}
static void i2a (int num, char * bf)
{
if (num<0) {
num=-num;
*bf++ = '-';
}
ui2a(num,10,0,bf);
}
static int a2d(char ch)
{
if (ch>='0' && ch<='9')
return ch-'0';
else if (ch>='a' && ch<='f')
return ch-'a'+10;
else if (ch>='A' && ch<='F')
return ch-'A'+10;
else return -1;
}
static char a2i(char ch, char** src,int base,int* nump)
{
char* p= *src;
int num=0;
int digit;
while ((digit=a2d(ch))>=0) {
if (digit>base) break;
num=num*base+digit;
ch=*p++;
}
*src=p;
*nump=num;
return ch;
}
static void putchw(void* putp,putcf putf,int n, char z, char* bf)
{
char fc=z? '0' : ' ';
char ch;
char* p=bf;
while (*p++ && n > 0)
n--;
while (n-- > 0)
putf(putp,fc);
while ((ch= *bf++))
putf(putp,ch);
}
void tfp_format(void* putp,putcf putf,char *fmt, va_list va)
{
char bf[12];
char ch;
while ((ch=*(fmt++))) {
if (ch!='%')
putf(putp,ch);
else {
char lz=0;
#ifdef PRINTF_LONG_SUPPORT
char lng=0;
#endif
int w=0;
ch=*(fmt++);
if (ch=='0') {
ch=*(fmt++);
lz=1;
}
if (ch>='0' && ch<='9') {
ch=a2i(ch,&fmt,10,&w);
}
#ifdef PRINTF_LONG_SUPPORT
if (ch=='l') {
ch=*(fmt++);
lng=1;
}
#endif
switch (ch) {
case 0:
goto abort;
case 'u' : {
#ifdef PRINTF_LONG_SUPPORT
if (lng)
uli2a(va_arg(va, unsigned long int),10,0,bf);
else
#endif
ui2a(va_arg(va, unsigned int),10,0,bf);
putchw(putp,putf,w,lz,bf);
break;
}
case 'd' : {
#ifdef PRINTF_LONG_SUPPORT
if (lng)
li2a(va_arg(va, unsigned long int),bf);
else
#endif
i2a(va_arg(va, int),bf);
putchw(putp,putf,w,lz,bf);
break;
}
case 'x': case 'X' :
#ifdef PRINTF_LONG_SUPPORT
if (lng)
uli2a(va_arg(va, unsigned long int),16,(ch=='X'),bf);
else
#endif
ui2a(va_arg(va, unsigned int),16,(ch=='X'),bf);
putchw(putp,putf,w,lz,bf);
break;
case 'c' :
putf(putp,(char)(va_arg(va, int)));
break;
case 's' :
putchw(putp,putf,w,0,va_arg(va, char*));
break;
case '%' :
putf(putp,ch);
default:
break;
}
}
}
abort:;
}
void init_printf(void* putp,void (*putf) (void*,char))
{
stdout_putf=putf;
stdout_putp=putp;
}
void tfp_printf(char *fmt, ...)
{
va_list va;
va_start(va,fmt);
tfp_format(stdout_putp,stdout_putf,fmt,va);
va_end(va);
}
static void putcp(void* p,char c)
{
*(*((char**)p))++ = c;
}
void tfp_sprintf(char* s,char *fmt, ...)
{
va_list va;
va_start(va,fmt);
tfp_format(&s,putcp,fmt,va);
putcp(&s,0);
va_end(va);
}
|
the_stack_data/59513580.c | /* Copyright (C) 1992, 1997 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <stdlib.h>
#include <stdio.h>
int
main (void)
{
int err = 0;
int i, j;
while (scanf ("%d %d\n", &i, &j) == 2)
{
div_t d = div (i, j);
printf ("%d / %d = %d + %d/%d", i, j, d.quot, d.rem, j);
if (i == d.quot * j + d.rem)
fputs (" OK\n", stdout);
else
{
fputs (" FAILED\n", stdout);
err = 1;
}
}
return err;
}
|
the_stack_data/40761729.c | #include <stdint.h>
#include <elf.h>
const char *shdr_get_type(uint32_t sh_type)
{
switch (sh_type) {
case SHT_NULL: return "NULL"; break;
case SHT_PROGBITS: return "PROGBITS"; break;
case SHT_SYMTAB: return "SYMTAB"; break;
case SHT_STRTAB: return "STRTAB"; break;
case SHT_RELA: return "RELA"; break;
case SHT_HASH: return "HASH"; break;
case SHT_DYNAMIC: return "DYNAMIC"; break;
case SHT_NOTE: return "NOTE"; break;
default: return ""; break;
}
}
const char *shdr_get_flags(uint32_t sh_flags)
{
switch (sh_flags) {
case SHF_WRITE: return "W"; break;
case SHF_ALLOC: return "A"; break;
case SHF_EXECINSTR: return "X"; break;
case SHF_MASKPROC: return "M"; break;
default: return ""; break;
}
}
|
the_stack_data/133250.c | #include<stdio.h>
int ace(char a,char b,char c,char d){
int cont = 0;
if(a=='d'){
cont++;
}
if(b=='a'){
cont++;
}
if(c=='c'){
cont++;
}
if(d=='d'){
cont++;
}
return cont;
}
int main(){
char a,b,c,d;
scanf("%c %c %c %c",&a,&b,&c,&d);
int ac=ace(a,b,c,d);
{ac == 4 ?printf("Super Fa\n"):ac==3?printf("Fa\n"):
ac==2?printf("Interessado no assunto"):
ac==1?printf("Ja ouviu falar\n"):printf("Nunca assistiu\n");
}
} |
the_stack_data/114516.c | // Listing 5.6 (mmap-read.c) Read an Integer from a Memory-Mapped File, and Double It
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define check_status(expr, msg) \
if (!(expr)) { \
fprintf(stderr, "%s\n", msg); \
fprintf(stderr, " - errno # %d (%s)\n", errno, strerror(errno)); \
fprintf(stderr, " - line # %d (file # %s)\n", __LINE__, __FILE__); \
exit(1); \
}
static const char* file_name = "write_test";
static const char* msg = "Hello world!";
static const int file_length = 1024 * 1;
//
// App entry point
//
int main()
{
int ret;
int fd = open(file_name, O_RDWR, S_IRUSR | S_IWUSR);
check_status(fd > 0, "Fail to open file");
(void)lseek(fd, 0, SEEK_SET);
// Map file as mmap
char *map = (char *)mmap(0, file_length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
check_status(map, "Fail to mmap file");
// Close file handle
(void)close(fd);
printf("Contents of the file:\n");
printf("%s", map);
printf("\n");
// Write data to file
sprintf(map + strlen(map), "\n%s\n", msg);
// Unmap memory
ret = munmap(map, file_length);
check_status(ret == 0, "Fail to munmap file");
printf("File # %s is created, to see its contents, issue\n", file_name);
printf(" cat %s\n", file_name);
return 0;
}
|
the_stack_data/179831828.c | #ifdef INTERFACE
CLASS(NexuizServerCreateTab) EXTENDS(NexuizTab)
METHOD(NexuizServerCreateTab, fill, void(entity))
METHOD(NexuizServerCreateTab, gameTypeChangeNotify, void(entity))
ATTRIB(NexuizServerCreateTab, title, string, "Create")
ATTRIB(NexuizServerCreateTab, intendedWidth, float, 0.9)
ATTRIB(NexuizServerCreateTab, rows, float, 22)
ATTRIB(NexuizServerCreateTab, columns, float, 6.5)
ATTRIB(NexuizServerCreateTab, mapListBox, entity, NULL)
ATTRIB(NexuizServerCreateTab, sliderFraglimit, entity, NULL)
ATTRIB(NexuizServerCreateTab, sliderTimelimit, entity, NULL)
ATTRIB(NexuizServerCreateTab, checkboxFraglimit, entity, NULL)
ATTRIB(NexuizServerCreateTab, checkboxFraglimitMapinfo, entity, NULL)
ENDCLASS(NexuizServerCreateTab)
entity makeNexuizServerCreateTab();
#endif
#ifdef IMPLEMENTATION
entity makeNexuizServerCreateTab()
{
entity me;
me = spawnNexuizServerCreateTab();
me.configureDialog(me);
return me;
}
void fillNexuizServerCreateTab(entity me)
{
entity e, e0;
float n;
me.TR(me);
n = 6;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_dm", "DM"));
e0 = e;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_lms", "LMS"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_arena", "Arena"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_race", "Race"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_cts", "Race CTS"));
if(e.checked) e0 = NULL;
me.TR(me);
n = 6;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_tdm", "TDM"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_ctf", "CTF"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_domination", "Domination"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_keyhunt", "Key Hunt"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_assault", "Assault"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_onslaught", "Onslaught"));
if(e.checked) e0 = NULL;
me.TR(me);
n = 6;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_nexball", "Nexball"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_total_domination", "Total Dom"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_freezetag", "Freeze Tag"));
if(e.checked) e0 = NULL;
me.TD(me, 1, me.columns / n, e = makeNexuizGametypeButton(1, "g_jailbreak", "Jailbreak"));
if(e.checked) e0 = NULL;
if(e0)
{
//print("NO CHECK\n");
e0.setChecked(e0, 1);
}
me.TR(me);
me.TR(me);
me.mapListBox = makeNexuizMapList();
me.TD(me, 1, 3, e = makeNexuizTextLabel(0, "Map list:"));
makeCallback(e, me.mapListBox, me.mapListBox.refilterCallback);
me.TR(me);
me.TD(me, me.rows - 7, 3, me.mapListBox);
me.gotoRC(me, me.rows - 3, 0);
me.TDempty(me, 0.5);
me.TD(me, 1, 1, e = makeNexuizButton("All", '0 0 0'));
e.onClick = MapList_All;
e.onClickEntity = me.mapListBox;
me.TD(me, 1, 1, e = makeNexuizButton("None", '0 0 0'));
e.onClick = MapList_None;
e.onClickEntity = me.mapListBox;
me.TDempty(me, 0.5);
me.gotoRC(me, 3, 3.5); me.setFirstColumn(me, me.currentColumn);
me.TD(me, 1, 3, e = makeNexuizTextLabel(0, "Match settings:"));
me.TR(me);
me.sliderTimelimit = makeNexuizSlider(1.0, 60.0, 0.5, "timelimit_override");
me.TD(me, 1, 1, e = makeNexuizSliderCheckBox(0, 1, me.sliderTimelimit, "Time limit:"));
me.TD(me, 1, 2, me.sliderTimelimit);
me.TR(me);
me.TDempty(me, 0.2);
me.TD(me, 1, 2.8, e = makeNexuizSliderCheckBox(-1, 0, me.sliderTimelimit, "Use map specified default"));
me.TR(me);
me.sliderFraglimit = makeNexuizSlider(1.0, 2000.0, 5, "fraglimit_override");
me.TD(me, 1, 1, e = makeNexuizSliderCheckBox(0, 1, me.sliderFraglimit, "Point limit:"));
me.checkboxFraglimit = e;
me.TD(me, 1, 2, me.sliderFraglimit);
me.TR(me);
me.TDempty(me, 0.2);
me.TD(me, 1, 2.8, e = makeNexuizSliderCheckBox(-1, 0, me.sliderFraglimit, "Use map specified default"));
me.checkboxFraglimitMapinfo = e;
me.TR(me);
me.TR(me);
me.TD(me, 1, 1, e = makeNexuizTextLabel(0, "Player slots:"));
me.TD(me, 1, 2, makeNexuizSlider(1, 32, 1, "menu_maxplayers"));
me.TR(me);
me.TD(me, 1, 1, e = makeNexuizTextLabel(0, "Number of bots:"));
me.TD(me, 1, 2, makeNexuizSlider(0, 9, 1, "bot_number"));
me.TR(me);
me.TDempty(me, 0.2);
me.TD(me, 1, 0.8, e = makeNexuizTextLabel(0, "Bot skill:"));
setDependent(e, "bot_number", 0, -1);
me.TD(me, 1, 2, e = makeNexuizTextSlider("skill"));
e.addValue(e, "Botlike", "0");
e.addValue(e, "Beginner", "1");
e.addValue(e, "You will win", "2");
e.addValue(e, "You can win", "3");
e.addValue(e, "You might win", "4");
e.addValue(e, "Advanced", "5");
e.addValue(e, "Expert", "6");
e.addValue(e, "Pro", "7");
e.addValue(e, "Assassin", "8");
e.addValue(e, "Unhuman", "9");
e.addValue(e, "Godlike", "10");
e.configureNexuizTextSliderValues(e);
setDependent(e, "bot_number", 0, -1);
me.TR(me);
me.TDempty(me, 0.2);
me.TD(me, 1, 0.8, e = makeNexuizTextLabel(0, "Bot names:"));
me.TD(me, 1, 0.7, e = makeNexuizInputBox(1, "bot_prefix"));
setDependent(e, "bot_number", 0, -1);
me.TD(me, 1, 0.6, e = makeNexuizTextLabel(0.5, "Shadow"));
setDependent(e, "bot_number", 0, -1);
me.TD(me, 1, 0.7, e = makeNexuizInputBox(1, "bot_suffix"));
setDependent(e, "bot_number", 0, -1);
me.TR(me);
me.TR(me);
me.TD(me, 1, 1, e = makeNexuizTextLabel(0, "Map voting:"));
me.TD(me, 1, 2, e = makeNexuizTextSlider("g_maplist_votable"));
e.addValue(e, "No voting", "0");
e.addValue(e, "2 choices", "2");
e.addValue(e, "3 choices", "3");
e.addValue(e, "4 choices", "4");
e.addValue(e, "5 choices", "5");
e.addValue(e, "6 choices", "6");
e.addValue(e, "7 choices", "7");
e.addValue(e, "8 choices", "8");
e.addValue(e, "9 choices", "9");
e.configureNexuizTextSliderValues(e);
me.TR(me);
me.TD(me, 1, 3, e = makeNexuizCheckBoxEx(0.5, 0, "sv_vote_simple_majority_factor", "Simple majority wins vcall"));
me.TR(me);
me.TR(me);
me.TDempty(me, 0.5);
me.TD(me, 1, 2, e = makeNexuizButton("Advanced settings...", '0 0 0'));
e.onClick = DialogOpenButton_Click;
e.onClickEntity = main.advancedDialog;
main.advancedDialog.refilterEntity = me.mapListBox;
me.TR(me);
me.TR(me);
me.TD(me, 1, 1, e = makeNexuizButton("Mutators...", '0 0 0'));
e.onClick = DialogOpenButton_Click;
e.onClickEntity = main.mutatorsDialog;
main.mutatorsDialog.refilterEntity = me.mapListBox;
me.TD(me, 1, 2, e0 = makeNexuizTextLabel(0, NULL));
e0.textEntity = main.mutatorsDialog;
e0.allowCut = 1;
me.gotoRC(me, me.rows - 1, 0);
me.TD(me, 1, 2, e = makeNexuizModButton("Multiplayer_Create"));
me.TD(me, 1, me.columns - 2, e = makeNexuizButton("Start Multiplayer!", '0 0 0'));
e.onClick = MapList_LoadMap;
e.onClickEntity = me.mapListBox;
me.mapListBox.startButton = e;
me.gameTypeChangeNotify(me);
}
void GameType_ConfigureSliders(entity e, entity l, entity l2, string pLabel, float pMin, float pMax, float pStep, string pCvar)
{
if(pCvar == "")
{
e.configureNexuizSlider(e, pMin, pMax, pStep, NULL);
l.setText(l, pLabel);
e.disabled = l.disabled = l2.disabled = TRUE;
}
else
{
e.configureNexuizSlider(e, pMin, pMax, pStep, pCvar);
l.setText(l, pLabel);
e.disabled = l.disabled = l2.disabled = FALSE;
}
}
void gameTypeChangeNotifyNexuizServerCreateTab(entity me)
{
// tell the map list to update
float gt;
entity e, l, l2;
gt = gametype_ID_to_MapID(gametype_GetMenu());
e = me.sliderFraglimit;
l = me.checkboxFraglimit;
l2 = me.checkboxFraglimitMapinfo;
switch(gt)
{
case MAPINFO_TYPE_CTF: GameType_ConfigureSliders(e, l, l2, "Capture limit:", 1, 20, 1, "capturelimit_override"); break;
case MAPINFO_TYPE_DOMINATION: GameType_ConfigureSliders(e, l, l2, "Point limit:", 50, 500, 10, "g_domination_point_limit"); break;
case MAPINFO_TYPE_KEYHUNT: GameType_ConfigureSliders(e, l, l2, "Point limit:", 200, 1500, 50, "g_keyhunt_point_limit"); break;
case MAPINFO_TYPE_LMS: GameType_ConfigureSliders(e, l, l2, "Lives:", 3, 50, 1, "g_lms_lives_override"); break;
case MAPINFO_TYPE_RACE: GameType_ConfigureSliders(e, l, l2, "Laps:", 1, 25, 1, "g_race_laps_limit"); break;
case MAPINFO_TYPE_NEXBALL: GameType_ConfigureSliders(e, l, l2, "Goals:", 1, 50, 1, "g_nexball_goallimit"); break;
case MAPINFO_TYPE_ASSAULT: GameType_ConfigureSliders(e, l, l2, "Point limit:", 50, 500, 10, ""); break;
case MAPINFO_TYPE_ONSLAUGHT: GameType_ConfigureSliders(e, l, l2, "Point limit:", 50, 500, 10, ""); break;
case MAPINFO_TYPE_CTS: GameType_ConfigureSliders(e, l, l2, "Point limit:", 50, 500, 10, ""); break;
default: GameType_ConfigureSliders(e, l, l2, "Frag limit:", 5, 100, 5, "fraglimit_override"); break;
}
me.mapListBox.refilter(me.mapListBox);
}
#endif
|
the_stack_data/220454982.c | extern int __VERIFIER_nondet_int();
int main() {
int a = __VERIFIER_nondet_int();
a++;
return a;
}
|
the_stack_data/43887902.c | #include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include "syscall.h"
int dup2(int old, int new)
{
int r;
#ifdef SYS_dup2
while ((r=__syscall(SYS_dup2, old, new))==-EBUSY);
#else
if (old==new) {
r = __syscall(SYS_fcntl, old, F_GETFD);
if (r >= 0) return old;
} else {
while ((r=__syscall(SYS_dup3, old, new, 0))==-EBUSY);
}
#endif
return __syscall_ret(r);
}
|
the_stack_data/59512608.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int menu(){
int a;
system("pause");
system("cls");
printf("1) Lotto\n");
printf("2) Super Lotto\n");
printf("3) Dollaz\n");
printf("4) Exit\n====>>> ");
scanf("%d",&a);
return a;
}
int gen(){
int a;
a= 1+rand()%36;//Stores a random number between 1 and 36 inclusive
return a;
}
void dollaz(int a){
int i;
printf("Dollaz Numbers : ");
for(i=0;i<a;i++)
printf("%d ",gen());
}
void super_lotto(){
int i;
printf("Super Lotto Numbers : ");
for(i=0;i<5;i++)
printf("%d ",gen());
}
void lotto(){
int i;
printf("Lotto Numbers : ");
for(i=0;i<6;i++)
printf("%d ",gen());
}
void run(int a,int b){
int i;
switch(a){
case 1:
lotto();
printf("\n");
break;
case 2:
super_lotto();
printf("\n");
break;
case 3:
dollaz(b);
printf("\n");
}
}
int main()
{
int choice=0;
int num=0;
srand(time(0));//Create the seed for rand() function
while(choice<4){
choice = menu();
if(choice==3){
printf("\nHow many plays 3-10\n===>>> ");
scanf("%d",&num);
}
run(choice,num);
}
}
|
the_stack_data/888946.c | /* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define NUM_THREADS 5
char functions_list[NUM_THREADS][21] =
{
"Maze_Generator",
"Game_Space_Main",
"Game_AI",
"NetWork_Interface",
"PrintHello"
};
void error(const char *msg)
{
perror(msg);
exit(1);
}
void *Maze_Generator(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, %s ( #%ld! )\n", functions_list[tid], tid);
pthread_exit(NULL);
}
void *Game_Space_Main(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, %s ( #%ld! )\n", functions_list[tid], tid);
pthread_exit(NULL);
}
void *Game_AI(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, %s ( #%ld! )\n", functions_list[tid], tid);
pthread_exit(NULL);
}
void *NetWork_Interface(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, %s ( #%ld! )\n", functions_list[tid], tid);
pthread_exit(NULL);
}
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, %s ( #%ld! )\n", functions_list[tid], tid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
pthread_t threads[NUM_THREADS];
int rc;
long t;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
for(t=0;t<NUM_THREADS;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, ( void * )functions_list[t], (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0) error("ERROR writing to socket");
close(newsockfd);
close(sockfd);
/* Last thing that main() should do */
pthread_exit(NULL);
return 0;
}
|
the_stack_data/198579568.c | #include <stdio.h>
void main () {
char buff [ 10 ];
int per = 0;
int x = 123;
per = sprintf ( buff, "%i", x );
printf ( "per = %d;\nstring = %s;\n", per, buff );
}
|
the_stack_data/23576063.c | #include <stdio.h>
#define SIZE 10
int sum(int ar[], int n);
int main(void)
{
int marbles[SIZE] = {20,10,5,39,4,16,19,26,31,20};
long answer;
answer = sum(marbles, SIZE);
printf("The total number of marbles is %ld\n", answer);
printf("Total size of marbles: %zd bytes\n",
sizeof marbles);
return 0;
}
int sum(int ar[], int n)
{
int i, total = 0;
for (i = 0; i < n; i++)
total+= *(ar + i);
printf("Total size of ar: %zd bytes\n",
sizeof ar);
return total;
} |
the_stack_data/161080869.c | #include<stdio.h>
int main(void)
{
printf("hello\n");
return 0;
}
|
the_stack_data/45450373.c | // no package
#include <stdio.h>
int main()
{
printf("Hello, World\n");
return 0;
} |
the_stack_data/178264700.c | /* Make sure dlopen/dlclose are not marked as leaf functions.
Copyright (C) 2013-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Mike Frysinger <[email protected]>
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
/* The bug-dl-leaf.c file will call our lib_main directly. We do this to
keep things simple -- no need to use --export-dynamic with the linker
or build the main ELF as a PIE.
The lib_main func will modify some of its state while dlopening and
dlclosing the bug-dl-leaf-lib-cb.so library. The constructors and
destructors in that library will call back into this library to also
muck with state (the check_val_xxx funcs).
If dlclose/dlopen are marked as "leaf" functions, then with newer
versions of gcc, the state modification won't work correctly. */
#include <assert.h>
#include <dlfcn.h>
static int val = 1;
static int called = 0;
void check_val_init (void)
{
called = 1;
assert (val == 2);
}
void check_val_fini (void)
{
called = 2;
assert (val == 4);
}
int lib_main (void)
{
int ret __attribute__ ((unused));
void *hdl;
/* Make sure the constructor sees the updated val. */
val = 2;
hdl = dlopen ("bug-dl-leaf-lib-cb.so", RTLD_GLOBAL | RTLD_LAZY);
val = 3;
assert (hdl);
assert (called == 1);
/* Make sure the destructor sees the updated val. */
val = 4;
ret = dlclose (hdl);
val = 5;
assert (ret == 0);
assert (called == 2);
return !val;
}
|
the_stack_data/463645.c | #include <stdio.h>
int main()
{
int twos[5] = { 2, 4, 6, 8, 10 };
int *pt;
pt = twos;
printf("%p\n",pt);
printf("%p\n",pt+1);
return(0);
}
|
the_stack_data/182954091.c | /* This testcase is part of GDB, the GNU debugger.
Contributed by Intel Corp. <[email protected]>
Copyright 2014-2020 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
int
func (int n)
{
int vla[n], i;
for (i = 0; i < n; i++)
vla[i] = i;
return n; /* vla-filled */
}
int
main (void)
{
func (5);
return 0;
}
|
the_stack_data/178265488.c | int b();
int a() {
return b();
}
|
the_stack_data/25525.c | void fence() { asm("sync"); }
void lwfence() { asm("lwsync"); }
void isync() { asm("isync"); }
int __unbuffered_cnt=0;
int __unbuffered_p0_r1=0;
int __unbuffered_p0_r3=0;
int __unbuffered_p1_r1=0;
int __unbuffered_p1_r3=0;
int __unbuffered_p1_r5=0;
int x=0;
int y=0;
void * P0(void * arg) {
__unbuffered_p0_r1 = 2;
y = __unbuffered_p0_r1;
fence();
__unbuffered_p0_r3 = 1;
x = __unbuffered_p0_r3;
// Instrumentation for CPROVER
fence();
__unbuffered_cnt++;
}
void * P1(void * arg) {
__unbuffered_p1_r1 = x;
__unbuffered_p1_r3 = 1;
y = __unbuffered_p1_r3;
__unbuffered_p1_r5 = y;
// Instrumentation for CPROVER
fence();
__unbuffered_cnt++;
}
int main() {
__CPROVER_ASYNC_0: P0(0);
__CPROVER_ASYNC_1: P1(0);
__CPROVER_assume(__unbuffered_cnt==2);
fence();
// EXPECT:exists
__CPROVER_assert(!(y==2 && __unbuffered_p1_r1==1 && __unbuffered_p1_r5==1), "Program proven to be relaxed for PPC, model checker says YES.");
return 0;
}
|
the_stack_data/181394229.c | #include <stdio.h>
#include <stdlib.h>
int a[100005];
int main()
{
int n,i,m,k,c,count;
c=100003;
count = 0;
scanf ("%d",&n);
for (i=1;i<=n;i++)
{
scanf ("%d",&m);
a[m]++;
}
scanf ("%d",&k);
for(;c >= 1; --c){
if(a[c] != 0)
count++;
if(count == k)
break;
}
printf("%d %d\n",c,a[c]);
return 0;
} |
the_stack_data/1194145.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_isprint.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sbecker <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/27 13:30:07 by sbecker #+# #+# */
/* Updated: 2018/11/27 17:52:36 by sbecker ### ########.fr */
/* */
/* ************************************************************************** */
int ft_isprint(int c)
{
return (c >= 32 && c <= 126);
}
|
the_stack_data/147785.c | /*-
* Copyright (c) 2005-2014 Rich Felker, et al.
*
* 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 <string.h>
#include <stdint.h>
int
strcmp(const char *l, const char *r)
{
for (; *l == *r && *l; l++, r++) {
}
return (*(uint8_t *)l - *(uint8_t *)r);
}
|
the_stack_data/68572.c | #include <stdio.h>
int main(void)
{
int value = 100;
printf("%d\n", (value = value - 48));
// printf("%d\n", (value = value - \60));
printf("%d\n", (value = value - '0'));
} |
the_stack_data/109909.c | #include <stdio.h>
int x;
int C(int m,int n)
{
if(m<n||m<1||n<1)
{
return 0;
}
if(n==1)
{
return m;
}
if(n==m)
{
return 1;
}
return C(m-1,n)+C(m-1,n-1);
}
int main()
{
int m,n;
scanf("%d %d",&m,&n);
printf("%d",C(m,n));
return 0;
} |
the_stack_data/31387904.c | int main(){
int b = 65/88*69;
return b;
} |
the_stack_data/787173.c | /*
* Copyright © 2009 CNRS
* Copyright © 2009-2017 Inria. All rights reserved.
* Copyright © 2009-2010 Université Bordeaux
* Copyright © 2011 Cisco Systems, Inc. All rights reserved.
* See COPYING in top-level directory.
*/
#include <hwloc.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
/*
* check hwloc_get_closest_objs()
*
* - get the last object of the last level
* - get all closest objects
* - get the common ancestor of last level and its less close object.
* - check that the ancestor is the system level
*/
int
main (void)
{
hwloc_topology_t topology;
int depth;
hwloc_obj_t last;
hwloc_obj_t *closest;
unsigned found;
int err;
unsigned numprocs;
hwloc_obj_t ancestor;
err = hwloc_topology_init (&topology);
if (err)
return EXIT_FAILURE;
hwloc_topology_set_synthetic (topology, "2 3 4 5");
err = hwloc_topology_load (topology);
if (err)
return EXIT_FAILURE;
depth = hwloc_topology_get_depth(topology);
/* get the last object of last level */
numprocs = hwloc_get_nbobjs_by_depth(topology, depth-1);
last = hwloc_get_obj_by_depth(topology, depth-1, numprocs-1);
/* allocate the array of closest objects */
closest = malloc(numprocs * sizeof(*closest));
assert(closest);
/* get closest levels */
found = hwloc_get_closest_objs (topology, last, closest, numprocs);
printf("looked for %u closest entries, found %u\n", numprocs, found);
assert(found == numprocs-1);
/* check first found is closest */
assert(closest[0] == hwloc_get_obj_by_depth(topology, depth-1, numprocs-5 /* arity is 5 on last level */));
/* check some other expected positions */
assert(closest[found-1] == hwloc_get_obj_by_depth(topology, depth-1, 1*3*4*5-1 /* last of first half */));
assert(closest[found/2-1] == hwloc_get_obj_by_depth(topology, depth-1, 1*3*4*5+2*4*5-1 /* last of second third of second half */));
assert(closest[found/2/3-1] == hwloc_get_obj_by_depth(topology, depth-1, 1*3*4*5+2*4*5+3*5-1 /* last of third quarter of third third of second half */));
/* get ancestor of last and less close object */
ancestor = hwloc_get_common_ancestor_obj(topology, last, closest[found-1]);
assert(hwloc_obj_is_in_subtree(topology, last, ancestor));
assert(hwloc_obj_is_in_subtree(topology, closest[found-1], ancestor));
assert(ancestor == hwloc_get_root_obj(topology));
printf("ancestor type %d (%s) depth %d number %u is the root object\n",
(int) ancestor->type, hwloc_obj_type_string(ancestor->type), ancestor->depth, ancestor->logical_index);
free(closest);
hwloc_topology_destroy (topology);
return EXIT_SUCCESS;
}
|
the_stack_data/20450780.c | /* adaptive rejection metropolis sampling */
/* *********************************************************************** */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
/* *********************************************************************** */
typedef struct point { /* a point in the x,y plane */
double x,y; /* x and y coordinates */
double ey; /* exp(y-ymax+YCEIL) */
double cum; /* integral up to x of rejection envelope */
int f; /* is y an evaluated point of log-density */
struct point *pl,*pr; /* envelope points to left and right of x */
} POINT;
/* *********************************************************************** */
typedef struct envelope { /* attributes of the entire rejection envelope */
int cpoint; /* number of POINTs in current envelope */
int npoint; /* max number of POINTs allowed in envelope */
int *neval; /* number of function evaluations performed */
double ymax; /* the maximum y-value in the current envelope */
POINT *p; /* start of storage of envelope POINTs */
double *convex; /* adjustment for convexity */
} ENVELOPE;
/* *********************************************************************** */
typedef struct funbag { /* everything for evaluating log density */
void *mydata; /* user-defined structure holding data for density */
double (*myfunc)(double x, void *mydata);
/* user-defined function evaluating log density at x */
} FUNBAG;
/* *********************************************************************** */
typedef struct metropolis { /* for metropolis step */
int on; /* whether metropolis is to be used */
double xprev; /* previous Markov chain iterate */
double yprev; /* current log density at xprev */
} METROPOLIS;
/* *********************************************************************** */
#define RAND_MAX2 2147483647 /* For Sun4 : remove this for some systems */
#define XEPS 0.00001 /* critical relative x-value difference */
#define YEPS 0.1 /* critical y-value difference */
#define EYEPS 0.001 /* critical relative exp(y) difference */
#define YCEIL 50. /* maximum y avoiding overflow in exp(y) */
/* *********************************************************************** */
/* declarations for functions defined in this file */
int arms_simple (int ninit, double *xl, double *xr,
double (*myfunc)(double x, void *mydata), void *mydata,
int dometrop, double *xprev, double *xsamp);
int arms (double *xinit, int ninit, double *xl, double *xr,
double (*myfunc)(double x, void *mydata), void *mydata,
double *convex, int npoint, int dometrop, double *xprev, double *xsamp,
int nsamp, double *qcent, double *xcent, int ncent,
int *neval);
int initial (double *xinit, int ninit, double xl, double xr, int npoint,
FUNBAG *lpdf, ENVELOPE *env, double *convex, int *neval,
METROPOLIS *metrop);
void sample(ENVELOPE *env, POINT *p);
void invert(double prob, ENVELOPE *env, POINT *p);
int test(ENVELOPE *env, POINT *p, FUNBAG *lpdf, METROPOLIS *metrop);
int update(ENVELOPE *env, POINT *p, FUNBAG *lpdf, METROPOLIS *metrop);
void cumulate(ENVELOPE *env);
int meet (POINT *q, ENVELOPE *env, METROPOLIS *metrop);
double area(POINT *q);
double expshift(double y, double y0);
double logshift(double y, double y0);
double perfunc(FUNBAG *lpdf, ENVELOPE *env, double x);
void display(FILE *f, ENVELOPE *env);
double u_random();
/* *********************************************************************** */
int arms_simple (int ninit, double *xl, double *xr,
double (*myfunc)(double x, void *mydata), void *mydata,
int dometrop, double *xprev, double *xsamp)
/* adaptive rejection metropolis sampling - simplified argument list */
/* ninit : number of starting values to be used */
/* *xl : left bound */
/* *xr : right bound */
/* *myfunc : function to evaluate log-density */
/* *mydata : data required by *myfunc */
/* dometrop : whether metropolis step is required */
/* *xprev : current value from markov chain */
/* *xsamp : to store sampled value */
{
double xinit[ninit], convex=1.0, qcent, xcent;
int err, i, npoint=100, nsamp=1, ncent=0, neval;
/* set up starting values */
for(i=0; i<ninit; i++){
xinit[i] = *xl + (i + 1.0) * (*xr - *xl)/(ninit + 1.0);
}
err = arms(xinit,ninit,xl,xr,myfunc,mydata,&convex,npoint,dometrop,xprev,xsamp,
nsamp,&qcent,&xcent,ncent,&neval);
return err;
}
/* *********************************************************************** */
int arms (double *xinit, int ninit, double *xl, double *xr,
double (*myfunc)(double x, void *mydata), void *mydata,
double *convex, int npoint, int dometrop, double *xprev, double *xsamp,
int nsamp, double *qcent, double *xcent,
int ncent, int *neval)
/* to perform derivative-free adaptive rejection sampling with metropolis step */
/* *xinit : starting values for x in ascending order */
/* ninit : number of starting values supplied */
/* *xl : left bound */
/* *xr : right bound */
/* *myfunc : function to evaluate log-density */
/* *mydata : data required by *myfunc */
/* *convex : adjustment for convexity */
/* npoint : maximum number of envelope points */
/* dometrop : whether metropolis step is required */
/* *xprev : previous value from markov chain */
/* *xsamp : to store sampled values */
/* nsamp : number of sampled values to be obtained */
/* *qcent : percentages for envelope centiles */
/* *xcent : to store requested centiles */
/* ncent : number of centiles requested */
/* *neval : on exit, the number of function evaluations performed */
{
ENVELOPE *env; /* rejection envelope */
POINT pwork; /* a working point, not yet incorporated in envelope */
int msamp=0; /* the number of x-values currently sampled */
FUNBAG lpdf; /* to hold density function and its data */
METROPOLIS *metrop; /* to hold bits for metropolis step */
int i,err;
/* check requested envelope centiles */
for(i=0; i<ncent; i++){
if((qcent[i] < 0.0) || (qcent[i] > 100.0)){
/* percentage requesting centile is out of range */
return 1005;
}
}
/* incorporate density function and its data into FUNBAG lpdf */
lpdf.mydata = mydata;
lpdf.myfunc = myfunc;
/* set up space required for envelope */
env = (ENVELOPE *)malloc(sizeof(ENVELOPE));
if(env == NULL){
/* insufficient space */
return 1006;
}
/* start setting up metropolis struct */
metrop = (METROPOLIS *)malloc(sizeof(METROPOLIS));
if(metrop == NULL){
/* insufficient space */
return 1006;
}
metrop->on = dometrop;
/* set up initial envelope */
err = initial(xinit,ninit,*xl,*xr,npoint,&lpdf,env,convex,
neval,metrop);
if(err)return err;
/* finish setting up metropolis struct (can only do this after */
/* setting up env) */
if(metrop->on){
if((*xprev < *xl) || (*xprev > *xr)){
/* previous markov chain iterate out of range */
return 1007;
}
metrop->xprev = *xprev;
metrop->yprev = perfunc(&lpdf,env,*xprev);
}
/* now do adaptive rejection */
do {
/* sample a new point */
sample (env,&pwork);
/* perform rejection (and perhaps metropolis) tests */
i = test(env,&pwork,&lpdf,metrop);
if(i == 1){
/* point accepted */
xsamp[msamp++] = pwork.x;
} else if (i != 0) {
/* envelope error - violation without metropolis */
return 2000;
}
} while (msamp < nsamp);
/* nsamp points now sampled */
/* calculate requested envelope centiles */
for (i=0; i<ncent; i++){
invert(qcent[i]/100.0,env,&pwork);
xcent[i] = pwork.x;
}
/* free space */
free(env->p);
free(env);
free(metrop);
return 0;
}
/* *********************************************************************** */
int initial (double *xinit, int ninit, double xl, double xr, int npoint,
FUNBAG *lpdf, ENVELOPE *env, double *convex, int *neval,
METROPOLIS *metrop)
/* to set up initial envelope */
/* xinit : initial x-values */
/* ninit : number of initial x-values */
/* xl,xr : lower and upper x-bounds */
/* npoint : maximum number of POINTs allowed in envelope */
/* *lpdf : to evaluate log density */
/* *env : rejection envelope attributes */
/* *convex : adjustment for convexity */
/* *neval : current number of function evaluations */
/* *metrop : for metropolis step */
{
int i,j,k,mpoint;
POINT *q;
if(ninit<3){
/* too few initial points */
return 1001;
}
mpoint = 2*ninit + 1;
if(npoint < mpoint){
/* too many initial points */
return 1002;
}
if((xinit[0] <= xl) || (xinit[ninit-1] >= xr)){
/* initial points do not satisfy bounds */
return 1003;
}
for(i=1; i<ninit; i++){
if(xinit[i] <= xinit[i-1]){
/* data not ordered */
return 1004;
}
}
if(*convex < 0.0){
/* negative convexity parameter */
return 1008;
}
/* copy convexity address to env */
env->convex = convex;
/* copy address for current number of function evaluations */
env->neval = neval;
/* initialise current number of function evaluations */
*(env->neval) = 0;
/* set up space for envelope POINTs */
env->npoint = npoint;
env->p = (POINT *)malloc(npoint*sizeof(POINT));
if(env->p == NULL){
/* insufficient space */
return 1006;
}
/* set up envelope POINTs */
q = env->p;
/* left bound */
q->x = xl;
q->f = 0;
q->pl = NULL;
q->pr = q+1;
for(j=1, k=0; j<mpoint-1; j++){
q++;
if(j%2){
/* point on log density */
q->x = xinit[k++];
q->y = perfunc(lpdf,env,q->x);
q->f = 1;
} else {
/* intersection point */
q->f = 0;
}
q->pl = q-1;
q->pr = q+1;
}
/* right bound */
q++;
q->x = xr;
q->f = 0;
q->pl = q-1;
q->pr = NULL;
/* calculate intersection points */
q = env->p;
for (j=0; j<mpoint; j=j+2, q=q+2){
if(meet(q,env,metrop)){
/* envelope violation without metropolis */
return 2000;
}
}
/* exponentiate and integrate envelope */
cumulate(env);
/* note number of POINTs currently in envelope */
env->cpoint = mpoint;
return 0;
}
/* *********************************************************************** */
void sample(ENVELOPE *env, POINT *p)
/* To sample from piecewise exponential envelope */
/* *env : envelope attributes */
/* *p : a working POINT to hold the sampled value */
{
double prob;
/* sample a uniform */
prob = u_random();
/* get x-value correponding to a cumulative probability prob */
invert(prob,env,p);
return;
}
/* *********************************************************************** */
void invert(double prob, ENVELOPE *env, POINT *p)
/* to obtain a point corresponding to a qiven cumulative probability */
/* prob : cumulative probability under envelope */
/* *env : envelope attributes */
/* *p : a working POINT to hold the sampled value */
{
double u,xl,xr,yl,yr,eyl,eyr,prop,z;
POINT *q;
/* find rightmost point in envelope */
q = env->p;
while(q->pr != NULL)q = q->pr;
/* find exponential piece containing point implied by prob */
u = prob * q->cum;
while(q->pl->cum > u)q = q->pl;
/* piece found: set left and right POINTs of p, etc. */
p->pl = q->pl;
p->pr = q;
p->f = 0;
p->cum = u;
/* calculate proportion of way through integral within this piece */
prop = (u - q->pl->cum) / (q->cum - q->pl->cum);
/* get the required x-value */
if (q->pl->x == q->x){
/* interval is of zero length */
p->x = q->x;
p->y = q->y;
p->ey = q->ey;
} else {
xl = q->pl->x;
xr = q->x;
yl = q->pl->y;
yr = q->y;
eyl = q->pl->ey;
eyr = q->ey;
if(fabs(yr - yl) < YEPS){
/* linear approximation was used in integration in function cumulate */
if(fabs(eyr - eyl) > EYEPS*fabs(eyr + eyl)){
p->x = xl + ((xr - xl)/(eyr - eyl))
* (-eyl + sqrt((1. - prop)*eyl*eyl + prop*eyr*eyr));
} else {
p->x = xl + (xr - xl)*prop;
}
p->ey = ((p->x - xl)/(xr - xl)) * (eyr - eyl) + eyl;
p->y = logshift(p->ey, env->ymax);
} else {
/* piece was integrated exactly in function cumulate */
p->x = xl + ((xr - xl)/(yr - yl))
* (-yl + logshift(((1.-prop)*eyl + prop*eyr), env->ymax));
p->y = ((p->x - xl)/(xr - xl)) * (yr - yl) + yl;
p->ey = expshift(p->y, env->ymax);
}
}
/* guard against imprecision yielding point outside interval */
if ((p->x < xl) || (p->x > xr))exit(1);
return;
}
/* *********************************************************************** */
int test(ENVELOPE *env, POINT *p, FUNBAG *lpdf, METROPOLIS *metrop)
/* to perform rejection, squeezing, and metropolis tests */
/* *env : envelope attributes */
/* *p : point to be tested */
/* *lpdf : to evaluate log-density */
/* *metrop : data required for metropolis step */
{
double u,y,ysqueez,ynew,yold,znew,zold,w;
POINT *ql,*qr;
/* for rejection test */
u = u_random() * p->ey;
y = logshift(u,env->ymax);
if(!(metrop->on) && (p->pl->pl != NULL) && (p->pr->pr != NULL)){
/* perform squeezing test */
if(p->pl->f){
ql = p->pl;
} else {
ql = p->pl->pl;
}
if(p->pr->f){
qr = p->pr;
} else {
qr = p->pr->pr;
}
ysqueez = (qr->y * (p->x - ql->x) + ql->y * (qr->x - p->x))
/(qr->x - ql->x);
if(y <= ysqueez){
/* accept point at squeezing step */
return 1;
}
}
/* evaluate log density at point to be tested */
ynew = perfunc(lpdf,env,p->x);
/* perform rejection test */
if(!(metrop->on) || ((metrop->on) && (y >= ynew))){
/* update envelope */
p->y = ynew;
p->ey = expshift(p->y,env->ymax);
p->f = 1;
if(update(env,p,lpdf,metrop)){
/* envelope violation without metropolis */
return -1;
}
/* perform rejection test */
if(y >= ynew){
/* reject point at rejection step */
return 0;
} else {
/* accept point at rejection step */
return 1;
}
}
/* continue with metropolis step */
yold = metrop->yprev;
/* find envelope piece containing metrop->xprev */
ql = env->p;
while(ql->pl != NULL)ql = ql->pl;
while(ql->pr->x < metrop->xprev)ql = ql->pr;
qr = ql->pr;
/* calculate height of envelope at metrop->xprev */
w = (metrop->xprev - ql->x)/(qr->x - ql->x);
zold = ql->y + w*(qr->y - ql->y);
znew = p->y;
if(yold < zold)zold = yold;
if(ynew < znew)znew = ynew;
w = ynew-znew-yold+zold;
if(w > 0.0)w = 0.0;
if(w > -YCEIL){
w = exp(w);
} else {
w = 0.0;
}
u = u_random();
if(u > w){
/* metropolis says dont move, so replace current point with previous */
/* markov chain iterate */
p->x = metrop->xprev;
p->y = metrop->yprev;
p->ey = expshift(p->y,env->ymax);
p->f = 1;
p->pl = ql;
p->pr = qr;
} else {
/* trial point accepted by metropolis, so update previous markov */
/* chain iterate */
metrop->xprev = p->x;
metrop->yprev = ynew;
}
return 1;
}
/* *********************************************************************** */
int update(ENVELOPE *env, POINT *p, FUNBAG *lpdf, METROPOLIS *metrop)
/* to update envelope to incorporate new point on log density*/
/* *env : envelope attributes */
/* *p : point to be incorporated */
/* *lpdf : to evaluate log-density */
/* *metrop : for metropolis step */
{
POINT *m,*ql,*qr,*q;
if(!(p->f) || (env->cpoint > env->npoint - 2)){
/* y-value has not been evaluated or no room for further points */
/* ignore this point */
return 0;
}
/* copy working POINT p to a new POINT q */
q = env->p + env->cpoint++;
q->x = p->x;
q->y = p->y;
q->f = 1;
/* allocate an unused POINT for a new intersection */
m = env->p + env->cpoint++;
m->f = 0;
if((p->pl->f) && !(p->pr->f)){
/* left end of piece is on log density; right end is not */
/* set up new intersection in interval between p->pl and p */
m->pl = p->pl;
m->pr = q;
q->pl = m;
q->pr = p->pr;
m->pl->pr = m;
q->pr->pl = q;
} else if (!(p->pl->f) && (p->pr->f)){
/* left end of interval is not on log density; right end is */
/* set up new intersection in interval between p and p->pr */
m->pr = p->pr;
m->pl = q;
q->pr = m;
q->pl = p->pl;
m->pr->pl = m;
q->pl->pr = q;
} else {
/* this should be impossible */
exit(10);
}
/* now adjust position of q within interval if too close to an endpoint */
if(q->pl->pl != NULL){
ql = q->pl->pl;
} else {
ql = q->pl;
}
if(q->pr->pr != NULL){
qr = q->pr->pr;
} else {
qr = q->pr;
}
if (q->x < (1. - XEPS) * ql->x + XEPS * qr->x){
/* q too close to left end of interval */
q->x = (1. - XEPS) * ql->x + XEPS * qr->x;
q->y = perfunc(lpdf,env,q->x);
} else if (q->x > XEPS * ql->x + (1. - XEPS) * qr->x){
/* q too close to right end of interval */
q->x = XEPS * ql->x + (1. - XEPS) * qr->x;
q->y = perfunc(lpdf,env,q->x);
}
/* revise intersection points */
if(meet(q->pl,env,metrop)){
/* envelope violation without metropolis */
return 1;
}
if(meet(q->pr,env,metrop)){
/* envelope violation without metropolis */
return 1;
}
if(q->pl->pl != NULL){
if(meet(q->pl->pl->pl,env,metrop)){
/* envelope violation without metropolis */
return 1;
}
}
if(q->pr->pr != NULL){
if(meet(q->pr->pr->pr,env,metrop)){
/* envelope violation without metropolis */
return 1;
}
}
/* exponentiate and integrate new envelope */
cumulate(env);
return 0;
}
/* *********************************************************************** */
void cumulate(ENVELOPE *env)
/* to exponentiate and integrate envelope */
/* *env : envelope attributes */
{
POINT *q,*qlmost;
qlmost = env->p;
/* find left end of envelope */
while(qlmost->pl != NULL)qlmost = qlmost->pl;
/* find maximum y-value: search envelope */
env->ymax = qlmost->y;
for(q = qlmost->pr; q != NULL; q = q->pr){
if(q->y > env->ymax)env->ymax = q->y;
}
/* exponentiate envelope */
for(q = qlmost; q != NULL; q = q->pr){
q->ey = expshift(q->y,env->ymax);
}
/* integrate exponentiated envelope */
qlmost->cum = 0.;
for(q = qlmost->pr; q != NULL; q = q->pr){
q->cum = q->pl->cum + area(q);
}
return;
}
/* *********************************************************************** */
int meet (POINT *q, ENVELOPE *env, METROPOLIS *metrop)
/* To find where two chords intersect */
/* q : to store point of intersection */
/* *env : envelope attributes */
/* *metrop : for metropolis step */
{
double gl,gr,grl,dl,dr;
int il,ir,irl;
if(q->f){
/* this is not an intersection point */
exit(30);
}
/* calculate coordinates of point of intersection */
if ((q->pl != NULL) && (q->pl->pl->pl != NULL)){
/* chord gradient can be calculated at left end of interval */
gl = (q->pl->y - q->pl->pl->pl->y)/(q->pl->x - q->pl->pl->pl->x);
il = 1;
} else {
/* no chord gradient on left */
il = 0;
}
if ((q->pr != NULL) && (q->pr->pr->pr != NULL)){
/* chord gradient can be calculated at right end of interval */
gr = (q->pr->y - q->pr->pr->pr->y)/(q->pr->x - q->pr->pr->pr->x);
ir = 1;
} else {
/* no chord gradient on right */
ir = 0;
}
if ((q->pl != NULL) && (q->pr != NULL)){
/* chord gradient can be calculated across interval */
grl = (q->pr->y - q->pl->y)/(q->pr->x - q->pl->x);
irl = 1;
} else {
irl = 0;
}
if(irl && il && (gl<grl)){
/* convexity on left exceeds current threshold */
if(!(metrop->on)){
/* envelope violation without metropolis */
return 1;
}
/* adjust left gradient */
gl = gl + (1.0 + *(env->convex)) * (grl - gl);
}
if(irl && ir && (gr>grl)){
/* convexity on right exceeds current threshold */
if(!(metrop->on)){
/* envelope violation without metropolis */
return 1;
}
/* adjust right gradient */
gr = gr + (1.0 + *(env->convex)) * (grl - gr);
}
if(il && irl){
dr = (gl - grl) * (q->pr->x - q->pl->x);
if(dr < YEPS){
/* adjust dr to avoid numerical problems */
dr = YEPS;
}
}
if(ir && irl){
dl = (grl - gr) * (q->pr->x - q->pl->x);
if(dl < YEPS){
/* adjust dl to avoid numerical problems */
dl = YEPS;
}
}
if(il && ir && irl){
/* gradients on both sides */
q->x = (dl * q->pr->x + dr * q->pl->x)/(dl + dr);
q->y = (dl * q->pr->y + dr * q->pl->y + dl * dr)/(dl + dr);
} else if (il && irl){
/* gradient only on left side, but not right hand bound */
q->x = q->pr->x;
q->y = q->pr->y + dr;
} else if (ir && irl){
/* gradient only on right side, but not left hand bound */
q->x = q->pl->x;
q->y = q->pl->y + dl;
} else if (il){
/* right hand bound */
q->y = q->pl->y + gl * (q->x - q->pl->x);
} else if (ir){
/* left hand bound */
q->y = q->pr->y - gr * (q->pr->x - q->x);
} else {
/* gradient on neither side - should be impossible */
exit(31);
}
if(((q->pl != NULL) && (q->x < q->pl->x)) ||
((q->pr != NULL) && (q->x > q->pr->x))){
/* intersection point outside interval (through imprecision) */
exit(32);
}
/* successful exit : intersection has been calculated */
return 0;
}
/* *********************************************************************** */
double area(POINT *q)
/* To integrate piece of exponentiated envelope to left of POINT q */
{
double a;
if(q->pl == NULL){
/* this is leftmost point in envelope */
exit(1);
} else if(q->pl->x == q->x){
/* interval is zero length */
a = 0.;
} else if (fabs(q->y - q->pl->y) < YEPS){
/* integrate straight line piece */
a = 0.5*(q->ey + q->pl->ey)*(q->x - q->pl->x);
} else {
/* integrate exponential piece */
a = ((q->ey - q->pl->ey)/(q->y - q->pl->y))*(q->x - q->pl->x);
}
return a;
}
/* *********************************************************************** */
double expshift(double y, double y0)
/* to exponentiate shifted y without underflow */
{
if(y - y0 > -2.0 * YCEIL){
return exp(y - y0 + YCEIL);
} else {
return 0.0;
}
}
/* *********************************************************************** */
double logshift(double y, double y0)
/* inverse of function expshift */
{
return (log(y) + y0 - YCEIL);
}
/* *********************************************************************** */
double perfunc(FUNBAG *lpdf, ENVELOPE *env, double x)
/* to evaluate log density and increment count of evaluations */
/* *lpdf : structure containing pointers to log-density function and data */
/* *env : envelope attributes */
/* x : point at which to evaluate log density */
{
double y;
/* evaluate density function */
y = (lpdf->myfunc)(x,lpdf->mydata);
/* increment count of function evaluations */
(*(env->neval))++;
return y;
}
/* *********************************************************************** */
void display(FILE *f, ENVELOPE *env)
/* to display envelope - for debugging only */
{
POINT *q;
/* print envelope attributes */
fprintf(f,"========================================================\n");
fprintf(f,"envelope attributes:\n");
fprintf(f,"points in use = %d, points available = %d\n",
env->cpoint,env->npoint);
fprintf(f,"function evaluations = %d\n",*(env->neval));
fprintf(f,"ymax = %f, p = %x\n",env->ymax,env->p);
fprintf(f,"convexity adjustment = %f\n",*(env->convex));
fprintf(f,"--------------------------------------------------------\n");
/* find leftmost POINT */
q = env->p;
while(q->pl != NULL)q = q->pl;
/* now print each POINT from left to right */
for(q = env->p; q != NULL; q = q->pr){
fprintf(f,"point at %x, left at %x, right at %x\n",q,q->pl,q->pr);
fprintf(f,"x = %f, y = %f, ey = %f, cum = %f, f = %d\n",
q->x,q->y,q->ey,q->cum,q->f);
}
fprintf(f,"========================================================\n");
return;
}
/* *********************************************************************** */
double u_random()
/* to return a standard uniform random number */
{
return ((double)rand() + 0.5)/((double)RAND_MAX2 + 1.0);
}
/* *********************************************************************** */
|
the_stack_data/27876.c | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2016 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
/*
* this application calls a user-written function that contains a good code pattern.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern void good_jump();
int main( int argc, char * argv[] )
{
char * buffer;
buffer = (char *)malloc( 64 );
strcpy( buffer, "abc" );
printf("%s\n", buffer );
good_jump();
printf("returned from good_jump.\n");
free( buffer );
return 0;
}
|
the_stack_data/409154.c | #if 0
#ifdef STM32F0xx
#include "stm32f0xx_hal_timebase_rtc_alarm_template.c"
#endif
#ifdef STM32F1xx
#include "stm32f1xx_hal_timebase_rtc_alarm_template.c"
#endif
#ifdef STM32F2xx
#include "stm32f2xx_hal_timebase_rtc_alarm_template.c"
#endif
#ifdef STM32F3xx
#include "stm32f3xx_hal_timebase_rtc_alarm_template.c"
#endif
#ifdef STM32F4xx
#include "stm32f4xx_hal_timebase_rtc_alarm_template.c"
#endif
#ifdef STM32F7xx
#include "stm32f7xx_hal_timebase_rtc_alarm_template.c"
#endif
#ifdef STM32G0xx
#include "stm32g0xx_hal_timebase_rtc_alarm_template.c"
#endif
#ifdef STM32H7xx
#include "stm32h7xx_hal_timebase_rtc_alarm_template.c"
#endif
#ifdef STM32WBxx
#include "stm32wbxx_hal_timebase_rtc_alarm_template.c"
#endif
#endif /* 0 */
|
the_stack_data/61075072.c | #include<stdio.h>
#include<stdlib.h>
int max_(int m,int n)
{
int max;
if(m>=n)
max=m;
else
max=n;
return max;
}
int main()
{
int n,max=0,i;
scanf("%d",&n);
int s[100001]={0};
int x;
for(int i=1;i<=n;i++){
scanf("%d",&x);
s[x]++;
max=max_(max,x);
}
int j=0;
int fin,k;
scanf("%d",&k);
for(i=max;j<k;i--){
if(s[i]!=0){
fin=i;
j++;
}
}
printf("%d %d",fin,s[fin]);
return 0;
} |
the_stack_data/88034.c | #include <stdio.h>
static void SayHello(const char* s){
puts(s);
} |
the_stack_data/1139454.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name,"r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name);
while( ( ch = fgetc(fp) ) != EOF ){
printf("%c",ch);
}
fclose(fp);
return 0;
}
|
the_stack_data/175142377.c | /* { dg-do compile } */
/* { dg-require-effective-target ilp32 } */
void *
test (unsigned long long x, unsigned long long y)
{
return (void *) (unsigned int) (x / y);
}
|
the_stack_data/767435.c | /* dlarrc.f -- translated by f2c (version 20061008) */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <assert.h>
/* Subroutine */
int xdrrc_(char *jobt, int *n, long double *vl,
long double *vu, long double *d__, long double *e, long double *pivmin,
int *eigcnt, int *lcnt, int *rcnt, int *info)
{
/* System generated locals */
int i__1;
long double d__1;
/* Local variables */
int i__;
long double sl, su, tmp, tmp2;
int matt;
extern int xlsame_(char *, char *);
long double lpivot, rpivot;
/* -- LAPACK auxiliary routine (version 3.2) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* Find the number of eigenvalues of the symmetric tridiagonal matrix T */
/* that are in the interval (VL,VU] if JOBT = 'T', and of L D L^T */
/* if JOBT = 'L'. */
/* Arguments */
/* ========= */
/* JOBT (input) CHARACTER*1 */
/* = 'T': Compute Sturm count for matrix T. */
/* = 'L': Compute Sturm count for matrix L D L^T. */
/* N (input) INT */
/* The order of the matrix. N > 0. */
/* VL (input) LONG DOUBLE PRECISION */
/* VU (input) LONG DOUBLE PRECISION */
/* The lower and upper bounds for the eigenvalues. */
/* D (input) LONG DOUBLE PRECISION array, dimension (N) */
/* JOBT = 'T': The N diagonal elements of the tridiagonal matrix T. */
/* JOBT = 'L': The N diagonal elements of the diagonal matrix D. */
/* E (input) LONG DOUBLE PRECISION array, dimension (N) */
/* JOBT = 'T': The N-1 offdiagonal elements of the matrix T. */
/* JOBT = 'L': The N-1 offdiagonal elements of the matrix L. */
/* PIVMIN (input) LONG DOUBLE PRECISION */
/* The minimum pivot in the Sturm sequence for T. */
/* EIGCNT (output) INT */
/* The number of eigenvalues of the symmetric tridiagonal matrix T */
/* that are in the interval (VL,VU] */
/* LCNT (output) INT */
/* RCNT (output) INT */
/* The left and right negcounts of the interval. */
/* INFO (output) INT */
/* Further Details */
/* =============== */
/* Based on contributions by */
/* Beresford Parlett, University of California, Berkeley, USA */
/* Jim Demmel, University of California, Berkeley, USA */
/* Inderjit Dhillon, University of Texas, Austin, USA */
/* Osni Marques, LBNL/NERSC, USA */
/* Christof Voemel, University of California, Berkeley, USA */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Parameter adjustments */
--e;
--d__;
/* Function Body */
*info = 0;
*lcnt = 0;
*rcnt = 0;
*eigcnt = 0;
matt = xlsame_(jobt, "T");
if (matt) {
/* Sturm sequence count on T */
lpivot = d__[1] - *vl;
rpivot = d__[1] - *vu;
if (lpivot <= 0.) {
++(*lcnt);
}
if (rpivot <= 0.) {
++(*rcnt);
}
i__1 = *n - 1;
for (i__ = 1; i__ <= i__1; ++i__) {
/* Computing 2nd power */
d__1 = e[i__];
tmp = d__1 * d__1;
lpivot = d__[i__ + 1] - *vl - tmp / lpivot;
rpivot = d__[i__ + 1] - *vu - tmp / rpivot;
if (lpivot <= 0.) {
++(*lcnt);
}
if (rpivot <= 0.) {
++(*rcnt);
}
/* L10: */
}
} else {
/* Sturm sequence count on L D L^T */
sl = -(*vl);
su = -(*vu);
i__1 = *n - 1;
for (i__ = 1; i__ <= i__1; ++i__) {
lpivot = d__[i__] + sl;
rpivot = d__[i__] + su;
if (lpivot <= 0.) {
++(*lcnt);
}
if (rpivot <= 0.) {
++(*rcnt);
}
tmp = e[i__] * d__[i__] * e[i__];
tmp2 = tmp / lpivot;
if (tmp2 == 0.) {
sl = tmp - *vl;
} else {
sl = sl * tmp2 - *vl;
}
tmp2 = tmp / rpivot;
if (tmp2 == 0.) {
su = tmp - *vu;
} else {
su = su * tmp2 - *vu;
}
/* L20: */
}
lpivot = d__[*n] + sl;
rpivot = d__[*n] + su;
if (lpivot <= 0.) {
++(*lcnt);
}
if (rpivot <= 0.) {
++(*rcnt);
}
}
*eigcnt = *rcnt - *lcnt;
return 0;
/* end of XDRRC */
} /* xdrrc_ */
|
the_stack_data/237642370.c | // Writen by Attractive Chaos; distributed under the MIT license
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "time.h"
double **mm_init(int n)
{
double **m;
int i;
m = (double**)malloc(n * sizeof(void*));
for (i = 0; i < n; ++i)
m[i] = calloc(n, sizeof(double));
return m;
}
void mm_destroy(int n, double **m)
{
int i;
for (i = 0; i < n; ++i) free(m[i]);
free(m);
}
double **mm_gen(int n)
{
double **m, tmp = 1. / n / n;
int i, j;
m = mm_init(n);
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
m[i][j] = tmp * (i - j) * (i + j);
return m;
}
// better cache performance by transposing the second matrix
double **mm_mul(int n, double *const *a, double *const *b)
{
int i, j, k;
double **m, **c;
m = mm_init(n); c = mm_init(n);
for (i = 0; i < n; ++i) // transpose
for (j = 0; j < n; ++j)
c[i][j] = b[j][i];
for (i = 0; i < n; ++i) {
double *p = a[i], *q = m[i];
for (j = 0; j < n; ++j) {
double t = 0.0, *r = c[j];
for (k = 0; k < n; ++k)
t += p[k] * r[k];
q[j] = t;
}
}
mm_destroy(n, c);
return m;
}
void run(int n)
{
clock_t t = clock();
double **a, **b, **m;
n = (n/2) * 2;
a = mm_gen(n); b = mm_gen(n);
m = mm_mul(n, a, b);
fprintf(stdout, "%.9f\n", m[n/2][n/2]);
mm_destroy(n, a); mm_destroy(n, b); mm_destroy(n, m);
fprintf(stderr, "time(%.2f)\n", (float)(clock() - t)/CLOCKS_PER_SEC);
}
int main(int argc, char* argv[])
{
unsigned N = (argc > 1) ? atol(argv[1]) : 100;
unsigned times = (argc > 2) ? atol(argv[2]) : 1;
fprintf(stderr, "started\n");
for (int i = 0; i < times; i++) { run(N); }
return 0;
} /* main() */
|
the_stack_data/20451408.c | /******************************************************************************
Problem statement - Search for a query in an Array_t
------------------------------------------------------------------------------------------------------------
----->>> Read an array from the user that has N(< 200 integers) elements (0 <= A[i] <= 500)
Then read a query from the user for example - 3
As the user entered 3 that means he can now search for 3 elemnts in the array
print the number if the number exists in the array or return 0 if the number doesnot exist in the array
------------------------------------------------------------------------------------------------------------
Constraint - Do not use nested loops
- Do not sort the array
- Do not alter the contents of the orginal array
- Space complexity is not an issue but T.C should be roughly O(N).
*******************************************************************************/
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#include <stdlib.h>
int main(void)
{
printf("Enter the number of elements in the array\n");
int N=0;
scanf("%d", &N);
printf("Enter the number of queries\n");
int Q=0;
scanf("%d", &Q);
//create an array of 501 elements because maximum value of A[i] can be between 0 to 500
int *A = (int *)malloc(sizeof(int)*501);
printf("Enter the elements in the array\n");
//First fill all the elements with -1
for(int i=0 ; i<N ; i++)
{
A[i] = -1;
}
//Now ask the user to enter the value of the elements in the array & fill it in the index pertaining to tha value
int value=0;
for(int i=0 ; i<N ; i++)
{
scanf("%d", &value);
//we are doing this to make the query easier & to avoid nested loops
A[value] = value;
}
int val=0;
//query process
while(Q--)
{
printf("\nEnter the number you wish to query from the array\n");
scanf("%d", &val);
printf("%d", A[val]);
}
return 0;
}
|
the_stack_data/62637403.c | #include <stdio.h>
#include <string.h>
int main(){
char string[10];
int A = -73;
unsigned int B = 31337;
strcpy(string, "sample");
//Example of printing with different format string
printf("[A] Dec: %d, Hex: %x, Unsigned: %u\n", A, A, A);
printf("[B] Dec: %d, Hex: %x, Unsigned: %u\n", B, B, B);
printf("[field with on B] 3: '%3u', 10: '%10u', '%08u'\n");
printf("[string] %s Address %08x\n", string, string);
//Example of unary address operator (dereferencing) adn a %x format string
printf("variable A is at address: %08x\n", &A);
}
|
the_stack_data/50378.c | int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
void main()
{
printid(a);
getid(a);
printid(a);
} |
the_stack_data/1127690.c | #include <stdio.h>
int gcd(int, int);
int main()
{
int first_number = 0, second_number = 0;
printf("This program prints the Greatest Common Divisor of two numbers using Euclid's algorithm.\n");
printf("Please enter two numbers.\n");
scanf("%d", &first_number);
scanf("%d", &second_number);
printf("The GCD of %d and %d is %d.\n", first_number, second_number, gcd(first_number, second_number));
return 0;
}
int gcd(int first, int second)
{
if(first % second == 0)
return second;
else
gcd(second, first % second);
} |
the_stack_data/116845.c | /*Binary search is an efficient approach to search a particular element from a sorted array of numbers.
You have a sorted array consisting of X elements, and you input the value to be found in it. The algorithm compares your input value with the key value of the array's middle element.
So here we have the following 3 scenarios:
1)If input key value matches the key value of the middle element, then its index is returned.
2)If input key value is lesser than the key value of middle element, then we do a search on the sub array to the left of the middle element.
3)Similarly if the input key value is greater than key value of middle element, then we do a search on the sub array to the right of the middle element.*/
#include <stdio.h>
//It is assumed that the given array is sorted in ascending order beforehand.
//Iterative Approach: Time Complexity is O(log(N))
int binarySearchIterative(int l, int r, int key, int arr[])
{
while(r>=l)
{
// Find the mid
int mid=(l+r)/2;
// Check if key is present at mid
if(arr[mid]==key)
return mid;
// Since key is not present at mid, we will check in which region it is present and then repeat the Search operation in that region
else if(arr[mid]<key)
{
// The key lies in between mid and r
l=mid+1;
}
else
{
// The key lies in between l and mid
r=mid-1;
}
}
// Key not found then return -1
return -1;
}
//Recursive Approach: Time Complexity is O(log(N))
int binarySearchRecursive(int l, int r, int key, int arr[])
{
if(r>=l)
{
// Find the mid
int mid=(l+r)/2;
// Check if key is present at mid
if(arr[mid]==key)
{
return mid;
}
// Since key is not present at mid, we will check in which region it is present and then repeat the Search operation in that region
else if(arr[mid]>key)
{
// The key lies in between l and mid
return binarySearchRecursive(l, mid-1, key, arr);
}
else
{
// The key lies in between mid and r
return binarySearchRecursive(mid+1, r, key, arr);
}
}
// Key not found then return -1
return -1;
}
int main()
{
int left, right, key, ans;
printf("Enter number of elements in the array: ");
scanf("%d",&right);//Length of array
int arr[right];
printf("Enter the elements of array in ascending order: ");
for(int i=0;i<right;i++)
{
scanf("%d",&arr[i]);
}
left=0;// Starting index
printf("Enter the element to be searched: ");
scanf("%d",&key);// Key to be searched in the array
ans=binarySearchIterative(left, right, key, arr);// Search the key in array using Iterative Binary Search
if(ans!=-1)// Check if key is there in array or not
printf("Iterative Approach: Index is: %d and pos is: %d\n",ans,ans+1);
else
printf("Iterative Approach: Element not found in array");
ans=binarySearchRecursive(left, right, key, arr);// Search the key in array using Recursive Binary Search
if(ans!=-1)// Check if key is there in array or not
printf("Recursive Approach: Index of: %d and pos is: %d\n",ans,ans+1);
else
printf("Recursive Approach: Element not found in array");;
}
/*
Time Complexity: O(log(N))
Sample I/O:
INPUT:
Enter number of elements in the array:
10
Enter the elements of array in ascending order:
2
4
6
8
10
12
14
16
18
20
Enter the element to be searched:
14
OUTPUT:
Iterative Approach: Index is: 6 and pos is: 7
Recursive Approach: Index of: 6 and pos is: 7
*/ |
the_stack_data/98573979.c | #include <stdio.h>
int main()
{
int i, n;
printf("Please enter a number: ");
scanf("%d", &n);
for (i = 1; i <= 10; i++){
printf("%d X %d = %d\n", n, i, n*i);
}
return 0;
}
|
the_stack_data/154827762.c | #include <stdio.h>
#include <assert.h>
#define NDEBUG // 使用assert() 需注释此句
int main( int argc, char *argv[] )
{
assert(0); // 程序不该运行到此处
return 0;
}
|
the_stack_data/416018.c | #include <stdio.h>
/*copy input to output;2nd version*/
main ()
{
int c;
while((c=getchar()) !=EOF)
putchar(c);
}
|
the_stack_data/97178.c | // RUN: %clang_cc1 -emit-llvm %s -o /dev/null
int printf(const char *, ...);
int foo(void);
int main(void) {
while (foo()) {
switch (foo()) {
case 0:
case 1:
case 2:
case 3:
printf("3");
case 4: printf("4");
case 5:
case 6:
default:
break;
}
}
return 0;
}
|
the_stack_data/170452715.c | /*---------------------------------------------------------------------
strtol() - convert a string to a long int and return it
Copyright (C) 2018, Philipp Klaus Krause . [email protected]
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this library; see the file COPYING. If not, write to the
Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
As a special exception, if you link this library with other files,
some of which are compiled with SDCC, to produce an executable,
this library does not by itself cause the resulting executable to
be covered by the GNU General Public License. This exception does
not however invalidate any other reasons why the executable file
might be covered by the GNU General Public License.
-------------------------------------------------------------------------*/
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
#pragma disable_warning 196
long int strtol(const char *nptr, char **endptr, int base)
{
const char *ptr = nptr;
const char *rptr;
unsigned long int u;
bool neg;
while (isblank (*ptr))
ptr++;
neg = (*ptr == '-');
if (*ptr == '-')
{
neg = true;
ptr++;
}
else
neg = false;
// strtoul() would accept leading blanks or signs (that might come after '-' handled above)
if (neg && (isblank (*ptr) || *ptr == '-' || *ptr == '+'))
{
if (endptr)
*endptr = nptr;
return (0);
}
u = strtoul(ptr, &rptr, base);
// Check for conversion error
if (rptr == ptr)
{
if (endptr)
*endptr = nptr;
return (0);
}
if (endptr)
*endptr = rptr;
// Check for range error
if (!neg && u > LONG_MAX)
{
errno = ERANGE;
return (LONG_MAX);
}
else if (neg && u > -LONG_MIN)
{
errno = ERANGE;
return (LONG_MIN);
}
return (neg ? -u : u);
}
|
the_stack_data/298862.c | /* BEGIN_ICS_COPYRIGHT7 ****************************************
Copyright (c) 2015-2017, Intel Corporation
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.
** END_ICS_COPYRIGHT7 ****************************************/
/* [ICS VERSION STRING: unknown] */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
exit(0);
}
|
the_stack_data/331043.c | #include <stdio.h>
int main()
{
int i,n;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
int last = a[n-1];
if(last%10 == 0)
printf("Yes\n");
else
printf("No\n");
} |
the_stack_data/297874.c | /* Copyright (c) 2013, Vsevolod Stakhov
* 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.
*
* THIS SOFTWARE IS PROVIDED ''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 AUTHOR 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.
*/
/**
* @file this utility generates character table for ucl
*/
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
static inline int
print_flag (const char *flag, bool *need_or, char *val)
{
int res;
res = sprintf (val, "%s%s", *need_or ? "|" : "", flag);
*need_or |= true;
return res;
}
int
main (int argc, char **argv)
{
int i, col, r;
const char *name = "ucl_chartable";
bool need_or;
char valbuf[2048];
col = 0;
if (argc > 1) {
name = argv[1];
}
printf ("static const unsigned int %s[255] = {\n", name);
for (i = 0; i < 255; i ++) {
need_or = false;
r = 0;
/* UCL_CHARACTER_VALUE_END */
if (i == ' ' || i == '\t') {
r += print_flag ("UCL_CHARACTER_WHITESPACE", &need_or, valbuf + r);
}
if (isspace (i)) {
r += print_flag ("UCL_CHARACTER_WHITESPACE_UNSAFE", &need_or, valbuf + r);
}
if (isalnum (i) || i >= 0x80 || i == '/' || i == '_') {
r += print_flag ("UCL_CHARACTER_KEY_START", &need_or, valbuf + r);
}
if (isalnum (i) || i == '-' || i == '_' || i == '/' || i == '.' || i >= 0x80) {
r += print_flag ("UCL_CHARACTER_KEY", &need_or, valbuf + r);
}
if (i == 0 || i == '\r' || i == '\n' || i == ']' || i == '}' || i == ';' || i == ',' || i == '#') {
r += print_flag ("UCL_CHARACTER_VALUE_END", &need_or, valbuf + r);
}
else {
if (isprint (i) || i >= 0x80) {
r += print_flag ("UCL_CHARACTER_VALUE_STR", &need_or, valbuf + r);
}
if (isdigit (i) || i == '-') {
r += print_flag ("UCL_CHARACTER_VALUE_DIGIT_START", &need_or, valbuf + r);
}
if (isalnum (i) || i == '.' || i == '-' || i == '+') {
r += print_flag ("UCL_CHARACTER_VALUE_DIGIT", &need_or, valbuf + r);
}
}
if (i == '"' || i == '\\' || i == '/' || i == 'b' ||
i == 'f' || i == 'n' || i == 'r' || i == 't' || i == 'u') {
r += print_flag ("UCL_CHARACTER_ESCAPE", &need_or, valbuf + r);
}
if (i == ' ' || i == '\t' || i == ':' || i == '=') {
r += print_flag ("UCL_CHARACTER_KEY_SEP", &need_or, valbuf + r);
}
if (i == '\n' || i == '\r' || i == '\\' || i == '\b' || i == '\t' ||
i == '"' || i == '\f') {
r += print_flag ("UCL_CHARACTER_JSON_UNSAFE", &need_or, valbuf + r);
}
if (i == '\n' || i == '\r' || i == '\\' || i == '\b' || i == '\t' ||
i == '"' || i == '\f' || i == '=' || i == ':' || i == '{' || i == '[' || i == ' ') {
r += print_flag ("UCL_CHARACTER_UCL_UNSAFE", &need_or, valbuf + r);
}
if (!need_or) {
r += print_flag ("UCL_CHARACTER_DENIED", &need_or, valbuf + r);
}
if (isprint (i)) {
r += sprintf (valbuf + r, " /* %c */", i);
}
if (i != 254) {
r += sprintf (valbuf + r, ", ");
}
col += r;
if (col > 80) {
printf ("\n%s", valbuf);
col = r;
}
else {
printf ("%s", valbuf);
}
}
printf ("\n}\n");
return 0;
}
|
the_stack_data/7269.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/timeb.h>
#include <malloc.h>
#include <math.h>
#define N_RUNS 20
#define N 10240
// read timer in second
double read_timer() {
struct timeb tm;
ftime(&tm);
return (double) tm.time + (double) tm.millitm / 1000.0;
}
//Create a matrix and a vector and fill with random numbers
void init(double *matrix, double *vector) {
for (int i = 0; i<N; i++) {
for (int j = 0; j<N; j++) {
matrix[i*N+j] = (double)rand()/(double)(RAND_MAX/10.0);
}
vector[i] = (double)rand()/(double)(RAND_MAX/10.0);
}
}
void matvec_simd(double *matrix, double *vector, double *dest) {
for (int i = 0; i<N; i++) {
double tmp = 0;
#pragma omp simd reduction(+: tmp)
for (int j = 0; j<N; j++) {
tmp += matrix[i*N+j] * vector[j];
}
dest[i] = tmp;
}
}
// Debug functions
void matvec_serial(double *matrix, double *vector, double *dest) {
for (int i = 0; i<N; i++) {
double tmp = 0;
for (int j = 0; j<N; j++) {
tmp += matrix[i*N+j] * vector[j];
}
dest[i] = tmp;
}
}
void print_matrix(double *matrix) {
for (int i = 0; i<8; i++) {
printf("[");
for (int j = 0; j<8; j++) {
printf("%.2f ", matrix[i*N+j]);
}
puts("]");
}
puts("");
}
void print_vector(double *vector) {
printf("[");
for (int i = 0; i<8; i++) {
printf("%.2f ", vector[i]);
}
puts("]");
}
double check(double *A, double *B){
double difference = 0;
for(int i = 0;i<N; i++){
difference += fabsf(A[i]- B[i]);
}
return difference;
}
int main(int argc, char **argv) {
//Set everything up
double *dest_vector = malloc(sizeof(double*)*N);
double *serial_vector = malloc(sizeof(double*)*N);
double *matrix = malloc(sizeof(double*)*N*N);
double *vector = malloc(sizeof(double)*N);
srand(time(NULL));
init(matrix, vector);
//warming up
matvec_simd(matrix, vector, dest_vector);
double t = 0;
double start = read_timer();
for (int i = 0; i<N_RUNS; i++)
matvec_simd(matrix, vector, dest_vector);
t += (read_timer() - start);
double t_serial = 0;
double start_serial = read_timer();
for (int i = 0; i<N_RUNS; i++)
matvec_serial(matrix, vector, serial_vector);
t_serial += (read_timer() - start_serial);
print_matrix(matrix);
print_vector(vector);
puts("=\n");
print_vector(dest_vector);
puts("---------------------------------");
print_vector(serial_vector);
double gflops = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t);
double gflops_serial = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t_serial);
printf("==================================================================\n");
printf("Performance:\t\t\tRuntime (s)\t GFLOPS\n");
printf("------------------------------------------------------------------\n");
printf("Matrix-vector (SIMD):\t\t%4f\t%4f\n", t/N_RUNS, gflops);
printf("Matrix-vector (Serial):\t\t%4f\t%4f\n", t_serial/N_RUNS, gflops_serial);
printf("Correctness check: %f\n", check(dest_vector,serial_vector));
free(dest_vector);
free(serial_vector);
free(matrix);
free(vector);
return 0;
}
|
the_stack_data/3263779.c | // WARNING: ODEBUG bug in exit_to_usermode_loop
// https://syzkaller.appspot.com/bug?id=55c67ce74d4586507d2f
// status:6
// 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/rfkill.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 = 0;
for (; i < 100; i++) {
if (pthread_create(&th, &attr, fn, arg) == 0) {
pthread_attr_destroy(&attr);
return;
}
if (errno == EAGAIN) {
usleep(50);
continue;
}
break;
}
exit(1);
}
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (ev->state)
exit(1);
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
static int event_isset(event_t* ev)
{
return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE);
}
static int event_timedwait(event_t* ev, uint64_t timeout)
{
uint64_t start = current_time_ms();
uint64_t now = start;
for (;;) {
uint64_t remain = timeout - (now - start);
struct timespec ts;
ts.tv_sec = remain / 1000;
ts.tv_nsec = (remain % 1000) * 1000 * 1000;
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts);
if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
return 1;
now = current_time_ms();
if (now - start > timeout)
return 0;
}
}
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
struct 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);
}
#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;
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);
int n = 0;
int err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
uint16_t id = 0;
struct nlattr* 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;
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);
int n = 0;
int err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
uint16_t id = 0;
struct nlattr* 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 = {(uint32_t)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
#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 rfkill_unblock_all()
{
int fd = open("/dev/rfkill", O_WRONLY);
if (fd < 0)
exit(1);
struct rfkill_event event = {0};
event.idx = 0;
event.type = RFKILL_TYPE_ALL;
event.op = RFKILL_OP_CHANGE_ALL;
event.soft = 0;
event.hard = 0;
if (write(fd, &event, sizeof(event)) < 0)
exit(1);
close(fd);
}
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 = 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);
int ret = ioctl(hci_sock, HCIDEVUP, vendor_pkt.id);
if (ret) {
if (errno == ERFKILL) {
rfkill_unblock_all();
ret = ioctl(hci_sock, HCIDEVUP, vendor_pkt.id);
}
if (ret && 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);
}
#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)
{
int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (int 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);
socklen_t 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);
struct ipt_get_entries entries;
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)
{
int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (int i = 0; i < num_tables; i++) {
struct ipt_table_desc* table = &tables[i];
if (table->info.valid_hooks == 0)
continue;
struct ipt_getinfo info;
memset(&info, 0, sizeof(info));
strcpy(info.name, table->name);
socklen_t optlen = sizeof(info);
if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen))
exit(1);
if (memcmp(&table->info, &info, sizeof(table->info)) == 0) {
struct ipt_get_entries entries;
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;
}
struct xt_counters counters[XT_MAX_ENTRIES];
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)
{
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (unsigned 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);
socklen_t 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);
struct arpt_get_entries entries;
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()
{
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (unsigned 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;
struct arpt_getinfo info;
memset(&info, 0, sizeof(info));
strcpy(info.name, table->name);
socklen_t 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) {
struct arpt_get_entries entries;
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 {
}
struct xt_counters counters[XT_MAX_ENTRIES];
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)
{
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (size_t 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);
socklen_t 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()
{
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (unsigned 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;
struct ebt_replace replace;
memset(&replace, 0, sizeof(replace));
strcpy(replace.name, table->name);
socklen_t 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 (unsigned h = 0; h < NF_BR_NUMHOOKS; h++)
table->replace.hook_entry[h] = 0;
if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) {
char entrytable[XT_TABLE_SIZE];
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 (unsigned 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();
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = (200 << 20);
setrlimit(RLIMIT_AS, &rlim);
rlim.rlim_cur = rlim.rlim_max = 32 << 20;
setrlimit(RLIMIT_MEMLOCK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 136 << 20;
setrlimit(RLIMIT_FSIZE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 1 << 20;
setrlimit(RLIMIT_STACK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 0;
setrlimit(RLIMIT_CORE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 256;
setrlimit(RLIMIT_NOFILE, &rlim);
if (unshare(CLONE_NEWNS)) {
}
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) {
}
if (unshare(CLONE_NEWIPC)) {
}
if (unshare(0x02000000)) {
}
if (unshare(CLONE_NEWUTS)) {
}
if (unshare(CLONE_SYSVSEM)) {
}
typedef struct {
const char* name;
const char* value;
} sysctl_t;
static const sysctl_t sysctls[] = {
{"/proc/sys/kernel/shmmax", "16777216"},
{"/proc/sys/kernel/shmall", "536870912"},
{"/proc/sys/kernel/shmmni", "1024"},
{"/proc/sys/kernel/msgmax", "8192"},
{"/proc/sys/kernel/msgmni", "1024"},
{"/proc/sys/kernel/msgmnb", "1024"},
{"/proc/sys/kernel/sem", "1024 1048576 500 1024"},
};
unsigned i;
for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++)
write_file(sysctls[i].name, sysctls[i].value);
}
static int wait_for_loop(int pid)
{
if (pid < 0)
exit(1);
int status = 0;
while (waitpid(-1, &status, __WALL) != pid) {
}
return WEXITSTATUS(status);
}
static void drop_caps(void)
{
struct __user_cap_header_struct cap_hdr = {};
struct __user_cap_data_struct cap_data[2] = {};
cap_hdr.version = _LINUX_CAPABILITY_VERSION_3;
cap_hdr.pid = getpid();
if (syscall(SYS_capget, &cap_hdr, &cap_data))
exit(1);
const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE);
cap_data[0].effective &= ~drop;
cap_data[0].permitted &= ~drop;
cap_data[0].inheritable &= ~drop;
if (syscall(SYS_capset, &cap_hdr, &cap_data))
exit(1);
}
static int do_sandbox_none(void)
{
if (unshare(CLONE_NEWPID)) {
}
int pid = fork();
if (pid != 0)
return wait_for_loop(pid);
setup_common();
initialize_vhci();
sandbox_common();
drop_caps();
initialize_netdevices_init();
if (unshare(CLONE_NEWNET)) {
}
initialize_tun();
initialize_netdevices();
loop();
exit(1);
}
#define FS_IOC_SETFLAGS _IOW('f', 2, long)
static void remove_dir(const char* dir)
{
int iter = 0;
DIR* dp = 0;
retry:
while (umount2(dir, MNT_DETACH) == 0) {
}
dp = opendir(dir);
if (dp == NULL) {
if (errno == EMFILE) {
exit(1);
}
exit(1);
}
struct dirent* ep = 0;
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);
while (umount2(filename, MNT_DETACH) == 0) {
}
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);
if (umount2(filename, MNT_DETACH))
exit(1);
}
}
closedir(dp);
for (int 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) {
if (umount2(dir, MNT_DETACH))
exit(1);
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);
for (int 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()
{
for (int 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 < 5; 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 = 0;
for (;; 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 = syscall(__NR_epoll_create, 1);
if (res != -1)
r[0] = res;
break;
case 1:
NONFAILING(memcpy((void*)0x20000000, "/dev/adsp1\000", 11));
res = syscall(__NR_openat, 0xffffffffffffff9cul, 0x20000000ul, 0ul, 0ul);
if (res != -1)
r[1] = res;
break;
case 2:
NONFAILING(*(uint32_t*)0x200000c0 = 0x60000001);
NONFAILING(*(uint64_t*)0x200000c4 = 0);
syscall(__NR_epoll_ctl, r[0], 1ul, r[1], 0x200000c0ul);
break;
case 3:
res = syscall(__NR_epoll_create, 0xaf);
if (res != -1)
r[2] = res;
break;
case 4:
NONFAILING(*(uint32_t*)0x20000100 = 0);
NONFAILING(*(uint64_t*)0x20000104 = 0);
syscall(__NR_epoll_ctl, r[2], 1ul, r[0], 0x20000100ul);
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/119853.c | #include <stdio.h>
int main(int argc, char *argv[])
{
char email[50];
int dia, mes, ano;
float altura, peso, imc;
printf("Digite email: ");
scanf("%s", email);
printf("Data nascimento (DD/MM/AA)");
scanf("%d%d%d", &dia, &mes, &ano);
printf("Digite a altura(metro): ");
scanf("%f", &altura);
printf("Digite peso (kg): ");
scanf("%f", &peso);
imc = peso / (altura * altura);
printf("Email: %s\n", email);
printf("Nascimento: %d%d%d\n", dia, mes, ano);
printf("IMC: %f\n", imc);
return 0;
}
|
the_stack_data/78428.c | #include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct bitnode
{
char data;
struct bitnode *lchild,*rchild;
}bitnode,*bitree;
bitree create_tree() //先序创建
{
char a;
bitree root;
scanf("%c",&a);
fflush(stdin);
if(a=='*')return NULL;
else
{
root=(bitnode*)malloc(sizeof(bitnode));
root->data=a;
root->lchild=create_tree();
root->rchild=create_tree();
}
return root;
}
void inorder(bitree root)//中序遍历
{
bitree s[100];
int top=0;
while(root||top)
{
while(root)
{
s[++top]=root;root=root->lchild;
}
if(top)
{
putchar(s[top]->data);
root=s[top--]->rchild;
}
}
}
int leafcount(bitree root)//计算叶子节点个数
{
int a;
if(!root)
{
return 0;
}
else
{
if((!root->lchild)&&(!root->rchild))
{
return 1;
}
else
{
a=leafcount(root->lchild)+leafcount(root->rchild);
return a;
}
}
}
int bitnodeHeight(bitree root)//计算树的高度
{
int lchild,rchild,a;
if(!root)
{
return (0);
}
else
{
lchild=bitnodeHeight(root->lchild);
rchild=bitnodeHeight(root->rchild);
a=(lchild>rchild)?(lchild+1):(rchild+1);
return a;
}
}
void main()
{
bitree root=NULL;
root=create_tree();//输入序列为先序遍历序列,*代表空
inorder(root);
printf("\n");
printf("%d\n",leafcount(root));
printf("%d\n",bitnodeHeight(root));
printf("\n");
}
//输入先序序列例如ab**c**(每输入一次回车)不能省略*(代表空)
|
the_stack_data/62638415.c | #include <stdio.h>
int main()
{
printf ("Bom dia!\n");
printf ("Olá mundo\n");
return 0;
} |
the_stack_data/154828774.c | #include "stdio.h"
#include "math.h"
int main()
{
float a, b, c, d, x1, x2;
printf("Insert the rates of the trinomial.\n");
scanf("%f%f%f", &a, &b, &c);
d = pow(b, 2) - 4 * a * c;
if (d > 0)
{
x1 = (-b + sqrt(d)) /( 2 * a);
x2 = (-b - sqrt(d)) /( 2 * a);
printf("The trinomial is (%f)*x^2 + (%f)*x +(%f) and its solutions are x1=%f and x2=%f.\n",a,b,c,x1,x2);
}
else
{
if (d == 0)
{
x1 =(float) -b/(a*2);
printf("The trinomial is (%f)*x^2 + (%f)*x +(%f) and its double solution is x1=x2=%f.\n", a, b, c,x1);
}
else
{
printf("The trinomial is (%f)*x^2 + (%f)*x +(%f) but there aren't any real solutions.\n", a, b, c);
}
}
return 0;
}
|
the_stack_data/421604.c | #include <stdio.h>
int min(int x,int y){return (x<y)?x:y;}
void swap(int *x,int *y){
int t = *x;
*x = *y;
*y = t;
}
int childMax(int *a,int n,int r,int x,int y){
if(x<n && a[x]>a[r]) r = x;
if(y<n && a[y]>a[r]) r = y;
return r;
}
void heapify(int *a,int n,int r){
int c = childMax(a,n,r,r*2+1,r*2+2);
if(r!=c){
swap(&a[r],&a[c]);
heapify(a,n,c);
}
}
void heapSort(int *a,int n){
for(int i = (n-2)/2;i>=0;i--){
heapify(a,n,i);
}
for(int i = n-1;i>=0;i--){
swap(&a[i],&a[0]);
heapify(a,i,0);
}
}
void Main(){
int n,k,ts, id = 0,a[100010];
scanf("%d",&ts);
while(ts--){
scanf("%d",&n);
for(int i = 0;i<n;i++) scanf("%d",a+i);
heapSort(a,n);
int Ans = min(a[n-2]-1,n-2);
printf("%d\n",Ans);
}
return;
}
int main(){
Main();
return 0;
}
|
the_stack_data/1136442.c | #include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function designed for chat between client and server.
void func(int sockfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(sockfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// and send that buffer to client
write(sockfd, buff, sizeof(buff));
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");
// Function for chatting between client and server
func(connfd);
// After chatting close the socket
close(sockfd);
}
|
the_stack_data/87022.c | #include <stdio.h>
int main(int argc, char** argv)
{
// LOCAL VARIABLES
char** temp_arr = argv;
// INPUT VALIDATION
if (temp_arr)
{
temp_arr++;
if (*temp_arr)
{
// DO IT
while (*temp_arr)
{
fprintf(stdout, "%s ", *temp_arr);
temp_arr++;
}
fprintf(stdout, "\n");
}
}
// DONE
return 0;
}
|
the_stack_data/309649.c | int a[123123];
int c;
int b[456456];
int d;
int e[789789];
void f() {
a[123] = 321;
}
void g() {
c = 321321;
}
void h() {
b[456] = 654;
}
void i() {
d = 654654;
}
void j() {
e[789] = 987;
}
int MAIN() {
write(a[123]);
write("\n");
write(c);
write("\n");
write(b[456]);
write("\n");
write(d);
write("\n");
write(e[789]);
write("\n");
f();
write(a[123]);
write("\n");
write(c);
write("\n");
write(b[456]);
write("\n");
write(d);
write("\n");
write(e[789]);
write("\n");
g();
write(a[123]);
write("\n");
write(c);
write("\n");
write(b[456]);
write("\n");
write(d);
write("\n");
write(e[789]);
write("\n");
h();
write(a[123]);
write("\n");
write(c);
write("\n");
write(b[456]);
write("\n");
write(d);
write("\n");
write(e[789]);
write("\n");
i();
write(a[123]);
write("\n");
write(c);
write("\n");
write(b[456]);
write("\n");
write(d);
write("\n");
write(e[789]);
write("\n");
j();
write(a[123]);
write("\n");
write(c);
write("\n");
write(b[456]);
write("\n");
write(d);
write("\n");
write(e[789]);
write("\n");
}
|
the_stack_data/28860.c | #include <stdio.h>
main () {
int i = 1, soma = 0;
for (i; i <= 100; i++) {
soma = soma + i;
}
printf("A soma dos numeros de 1 a 100 eh: %d", soma);
}
|
the_stack_data/32949822.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b;
printf("Digite o valor de A: ");
scanf("%d", &a);
printf("Digite o valor de B: ");
scanf("%d", &b);
if (a > b) {
printf("O valor de A eh o maior!");
}
else if (a < b) {
printf("O valor de B eho maior!");
}
else {
printf("A e B sao iguais!");
}
return 0;
}
|
the_stack_data/31388912.c | /*
*
* Copyright (c) 1997
* Moscow Center for SPARC Technology
*
* Copyright (c) 1999
* Boris Fomitchev
*
* 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, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
# ifndef _STLP_DEBUG_C
# define _STLP_DEBUG_C
#if defined ( _STLP_DEBUG )
# ifdef _STLP_THREADS
# ifndef _STLP_NEED_MUTABLE
# define _STLP_ACQUIRE_LOCK(_Lock) _Lock._M_acquire_lock();
# define _STLP_RELEASE_LOCK(_Lock) _Lock._M_release_lock();
# else
# define _STLP_ACQUIRE_LOCK(_Lock) ((_STLP_mutex&)_Lock)._M_acquire_lock();
# define _STLP_RELEASE_LOCK(_Lock) ((_STLP_mutex&)_Lock)._M_release_lock();
# endif /* _STLP_NEED_MUTABLE */
# else
# define _STLP_ACQUIRE_LOCK(_Lock)
# define _STLP_RELEASE_LOCK(_Lock)
# endif /* _STLP_THREADS */
_STLP_BEGIN_NAMESPACE
//==========================================================
// global non-inline functions
//==========================================================
// [ i1, i2)
template <class _Iterator>
inline bool _STLP_CALL
__in_range_aux(const _Iterator& __it, const _Iterator& __first,
const _Iterator& __last, const random_access_iterator_tag &) {
return ( __it >= __first &&
__it < __last);
}
template <class _Iterator1, class _Iterator>
# if defined (_STLP_MSVC) && (_STLP_MSVC >= 1100)
inline bool _STLP_CALL __in_range_aux(_Iterator1 __it, const _Iterator& __first,
# else
inline bool _STLP_CALL __in_range_aux(const _Iterator1& __it, const _Iterator& __first,
# endif
const _Iterator& __last, const forward_iterator_tag &) {
_Iterator1 __i(__first);
for (; __i != __last && __i != __it; ++__i);
return (__i!=__last);
}
# if defined (_STLP_NONTEMPL_BASE_MATCH_BUG)
template <class _Iterator1, class _Iterator>
inline bool _STLP_CALL
__in_range_aux(const _Iterator1& __it, const _Iterator& __first,
const _Iterator& __last, const bidirectional_iterator_tag &) {
_Iterator1 __i(__first);
for (; __i != __last && __i != __it; ++__i);
return (__i !=__last);
}
# endif
template <class _Iterator>
bool _STLP_CALL __check_range(const _Iterator& __first, const _Iterator& __last) {
_STLP_VERBOSE_RETURN(__valid_range(__first,__last), _StlMsg_INVALID_RANGE )
return true;
}
template <class _Iterator>
bool _STLP_CALL __check_range(const _Iterator& __it,
const _Iterator& __start, const _Iterator& __finish) {
_STLP_VERBOSE_RETURN(__in_range(__it,__start, __finish),
_StlMsg_NOT_IN_RANGE_1)
return true;
}
template <class _Iterator>
bool _STLP_CALL __check_range(const _Iterator& __first, const _Iterator& __last,
const _Iterator& __start, const _Iterator& __finish) {
_STLP_VERBOSE_RETURN(__in_range(__first, __last, __start, __finish),
_StlMsg_NOT_IN_RANGE_2)
return true;
}
//===============================================================
template <class _Iterator>
void _STLP_CALL __invalidate_range(const __owned_list* __base,
const _Iterator& __first,
const _Iterator& __last)
{
typedef _Iterator* _Safe_iterator_ptr;
typedef __owned_link _L_type;
_STLP_ACQUIRE_LOCK(__base->_M_lock)
_L_type* __pos;
_L_type* __prev;
for (__prev = (_L_type*)&__base->_M_node, __pos= (_L_type*)__prev->_M_next;
__pos!=0;) {
if ((!(&__first == (_Iterator*)__pos || &__last == (_Iterator*)__pos))
&& __in_range_aux(
*(_Iterator*)__pos,
__first,
__last,
_STLP_ITERATOR_CATEGORY(__first, _Iterator))) {
__pos->_M_owner = 0;
__pos = (_L_type*) (__prev->_M_next = __pos->_M_next);
}
else {
__prev = __pos;
__pos=(_L_type*)__pos->_M_next;
}
}
_STLP_RELEASE_LOCK(__base->_M_lock)
}
template <class _Iterator>
void _STLP_CALL __invalidate_iterator(const __owned_list* __base,
const _Iterator& __it)
{
typedef __owned_link _L_type;
_L_type* __position, *__prev;
_STLP_ACQUIRE_LOCK(__base->_M_lock)
for (__prev = (_L_type*)&__base->_M_node, __position = (_L_type*)__prev->_M_next;
__position!= 0;) {
// this requires safe iterators to be derived from __owned_link
if ((__position != (_L_type*)&__it) && *((_Iterator*)__position)==__it) {
__position->_M_owner = 0;
__position = (_L_type*) (__prev->_M_next = __position->_M_next);
}
else {
__prev = __position;
__position=(_L_type*)__position->_M_next;
}
}
_STLP_RELEASE_LOCK(__base->_M_lock)
}
_STLP_END_NAMESPACE
# endif /* _STLP_DEBUG */
# if defined (_STLP_EXPOSE_GLOBALS_IMPLEMENTATION)
// dwa 12/26/99 -- for abort
# if defined (_STLP_USE_NEW_C_HEADERS)
# include <cstdlib>
# else
# include <stdlib.h>
# endif
# if defined (_STLP_WIN32)
# include <stl/_threads.h>
# endif
//==========================================================
// .c section
// owned_list non-inline methods and global functions
//==========================================================
#if defined ( _STLP_ASSERTIONS )
_STLP_BEGIN_NAMESPACE
# ifndef _STLP_STRING_LITERAL
# define _STLP_STRING_LITERAL(__x) __x
# endif
# ifdef _STLP_WINCE
# define _STLP_PERCENT_S "%hs"
# else
# define _STLP_PERCENT_S "%s"
# endif
# define _STLP_MESSAGE_TABLE_BODY = { \
_STLP_STRING_LITERAL("\n" _STLP_PERCENT_S "(%d): STL error: %s\n"), \
_STLP_STRING_LITERAL(_STLP_PERCENT_S "(%d): STL assertion failure : " _STLP_PERCENT_S "\n" _STLP_ASSERT_MSG_TRAILER), \
_STLP_STRING_LITERAL("\n" _STLP_PERCENT_S "(%d): STL error : " _STLP_PERCENT_S "\n" _STLP_PERCENT_S "(%d): STL assertion failure: " _STLP_PERCENT_S " \n" _STLP_ASSERT_MSG_TRAILER), \
_STLP_STRING_LITERAL("Invalid argument to operation (see operation documentation)"), \
_STLP_STRING_LITERAL("Taking an iterator out of destroyed (or otherwise corrupted) container"), \
_STLP_STRING_LITERAL("Trying to extract an object out from empty container"),\
_STLP_STRING_LITERAL("Past-the-end iterator could not be erased"), \
_STLP_STRING_LITERAL("Index out of bounds"), \
_STLP_STRING_LITERAL("Container doesn't own the iterator"), \
_STLP_STRING_LITERAL("Uninitialized or invalidated (by mutating operation) iterator used"), \
_STLP_STRING_LITERAL("Uninitialized or invalidated (by mutating operation) lefthand iterator in expression"), \
_STLP_STRING_LITERAL("Uninitialized or invalidated (by mutating operation) righthand iterator in expression"), \
_STLP_STRING_LITERAL("Iterators used in expression are from different owners"), \
_STLP_STRING_LITERAL("Iterator could not be dereferenced (past-the-end ?)"), \
_STLP_STRING_LITERAL("Range [first,last) is invalid"), \
_STLP_STRING_LITERAL("Iterator is not in range [first,last)"), \
_STLP_STRING_LITERAL("Range [first,last) is not in range [start,finish)"), \
_STLP_STRING_LITERAL("The advance would produce invalid iterator"), \
_STLP_STRING_LITERAL("Iterator is singular (advanced beyond the bounds ?)"), \
_STLP_STRING_LITERAL("Memory block deallocated twice"), \
_STLP_STRING_LITERAL("Deallocating a block that was never allocated"), \
_STLP_STRING_LITERAL("Deallocating a memory block allocated for another type"), \
_STLP_STRING_LITERAL("Size of block passed to deallocate() doesn't match block size"), \
_STLP_STRING_LITERAL("Pointer underrun - safety margin at front of memory block overwritten"), \
_STLP_STRING_LITERAL("Pointer overrrun - safety margin at back of memory block overwritten"), \
_STLP_STRING_LITERAL("Attempt to dereference null pointer returned by auto_ptr::get()"), \
_STLP_STRING_LITERAL("Unknown problem") \
}
# if ( _STLP_STATIC_TEMPLATE_DATA > 0 )
template <class _Dummy>
const char* __stl_debug_engine<_Dummy>::_Message_table[_StlMsg_MAX] _STLP_MESSAGE_TABLE_BODY;
# else
__DECLARE_INSTANCE(const char*, __stl_debug_engine<bool>::_Message_table[_StlMsg_MAX],
_STLP_MESSAGE_TABLE_BODY);
# endif
# undef _STLP_STRING_LITERAL
# undef _STLP_PERCENT_S
_STLP_END_NAMESPACE
// abort()
# include <cstdlib>
# if !defined( _STLP_DEBUG_MESSAGE )
# include <cstdarg>
# include <cstdio>
_STLP_BEGIN_NAMESPACE
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_Message(const char * __format_str, ...)
{
STLPORT_CSTD::va_list __args;
va_start( __args, __format_str );
# if defined (_STLP_WINCE)
TCHAR __buffer[512];
int _convert = strlen(__format_str) + 1;
LPWSTR _lpw = (LPWSTR)alloca(_convert*sizeof(wchar_t));
_lpw[0] = '\0';
MultiByteToWideChar(GetACP(), 0, __format_str, -1, _lpw, _convert);
wvsprintf(__buffer, _lpw, __args);
// wvsprintf(__buffer, __format_str, __args);
_STLP_WINCE_TRACE(__buffer);
# elif defined (_STLP_WIN32) && ( defined(_STLP_MSVC) || defined (__ICL) || defined (__BORLANDC__))
char __buffer [4096];
vsnprintf(__buffer, sizeof(__buffer) / sizeof(char),
__format_str, __args);
OutputDebugStringA(__buffer);
# elif defined (__amigaos__)
STLPORT_CSTD::vfprintf(stderr, __format_str, (char *)__args);
# else
STLPORT_CSTD::vfprintf(stderr, __format_str, __args);
# endif /* WINCE */
# ifdef _STLP_DEBUG_MESSAGE_POST
_STLP_DEBUG_MESSAGE_POST
# endif
va_end(__args);
}
_STLP_END_NAMESPACE
# endif /* _STLP_DEBUG_MESSAGE */
_STLP_BEGIN_NAMESPACE
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_IndexedError(int __error_ind, const char* __f, int __l)
{
__stl_debug_message(_Message_table[_StlFormat_ERROR_RETURN],
__f, __l, _Message_table[__error_ind]);
}
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_VerboseAssert(const char* __expr, int __error_ind, const char* __f, int __l)
{
__stl_debug_message(_Message_table[_StlFormat_VERBOSE_ASSERTION_FAILURE],
__f, __l, _Message_table[__error_ind], __f, __l, __expr);
__stl_debug_terminate();
}
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_Assert(const char* __expr, const char* __f, int __l)
{
__stl_debug_message(_Message_table[_StlFormat_ASSERTION_FAILURE],__f, __l, __expr);
__stl_debug_terminate();
}
// if exceptions are present, sends unique exception
// if not, calls abort() to terminate
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_Terminate()
{
# ifdef _STLP_USE_NAMESPACES
using namespace _STLP_STD;
# endif
# if defined (_STLP_USE_EXCEPTIONS) && ! defined (_STLP_NO_DEBUG_EXCEPTIONS)
throw __stl_debug_exception();
# else
_STLP_ABORT();
# endif
}
_STLP_END_NAMESPACE
# endif /* _STLP_ASSERTIONS */
#ifdef _STLP_DEBUG
_STLP_BEGIN_NAMESPACE
//==========================================================
// owned_list non-inline methods
//==========================================================
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_Invalidate_all(__owned_list* __l) {
_STLP_ACQUIRE_LOCK(__l->_M_lock);
_Stamp_all(__l, 0);
__l->_M_node._M_next =0;
_STLP_RELEASE_LOCK(__l->_M_lock);
}
// boris : this is unasafe routine; should be used from within critical section only !
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_Stamp_all(__owned_list* __l, __owned_list* __o) {
// crucial
if (__l->_M_node._M_owner) {
for (__owned_link* __position = (__owned_link*)__l->_M_node._M_next;
__position != 0; __position= (__owned_link*)__position->_M_next) {
_STLP_ASSERT(__position->_Owner()== __l)
__position->_M_owner=__o;
}
}
}
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_Verify(const __owned_list* __l) {
_STLP_ACQUIRE_LOCK(__l->_M_lock);
if (__l) {
_STLP_ASSERT(__l->_M_node._Owner() != 0)
for (__owned_link* __position = (__owned_link*)__l->_M_node._M_next;
__position != 0; __position= (__owned_link*)__position->_M_next) {
_STLP_ASSERT(__position->_Owner()== __l)
}
}
_STLP_RELEASE_LOCK(__l->_M_lock);
}
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_Swap_owners(__owned_list& __x, __owned_list& __y) {
// according to the standard : --no swap() function invalidates any references,
// pointers, or iterators referring to the elements of the containers being swapped.
__owned_link* __tmp;
// boris : there is a deadlock potential situation here if we lock two containers sequentially.
// As user is supposed to provide its own synchronization around swap() ( it is unsafe to do any container/iterator access
// in parallel with swap()), we just do not use any locking at all -- that behaviour is closer to non-debug version
__tmp = __x._M_node._M_next;
_Stamp_all(&__x, &__y);
_Stamp_all(&__y, &__x);
__x._M_node._M_next = __y._M_node._M_next;
__y._M_node._M_next = __tmp;
}
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_M_detach(__owned_list* __l, __owned_link* __c_node) {
if (__l != 0) {
_STLP_VERBOSE_ASSERT(__l->_Owner()!=0, _StlMsg_INVALID_CONTAINER)
_STLP_ACQUIRE_LOCK(__l->_M_lock)
// boris : re-test the condition in case someone else already deleted us
if(__c_node->_M_owner != 0) {
__owned_link* __prev, *__next;
for (__prev = &__l->_M_node; (__next = __prev->_M_next) != __c_node;
__prev = __next) {
_STLP_ASSERT(__next && __next->_Owner() == __l)
}
__prev->_M_next = __c_node->_M_next;
__c_node->_M_owner=0;
}
_STLP_RELEASE_LOCK(__l->_M_lock)
}
}
template <class _Dummy>
void _STLP_CALL
__stl_debug_engine<_Dummy>::_M_attach(__owned_list* __l, __owned_link* __c_node) {
if (__l ==0) {
(__c_node)->_M_owner = 0;
} else {
_STLP_VERBOSE_ASSERT(__l->_Owner()!=0, _StlMsg_INVALID_CONTAINER)
_STLP_ACQUIRE_LOCK(__l->_M_lock)
__c_node->_M_owner = __l;
__c_node->_M_next = __l->_M_node._M_next;
__l->_M_node._M_next = __c_node;
_STLP_RELEASE_LOCK(__l->_M_lock)
}
}
template <class _Dummy>
void* _STLP_CALL
__stl_debug_engine<_Dummy>::_Get_container_ptr(const __owned_link* __l) {
const __owned_list* __owner = __l->_Owner();
_STLP_VERBOSE_RETURN_0(__owner != 0, _StlMsg_INVALID_ITERATOR)
void* __ret = __CONST_CAST(void*,__owner->_Owner());
_STLP_VERBOSE_RETURN_0(__ret !=0, _StlMsg_INVALID_CONTAINER)
return __ret;
}
template <class _Dummy>
bool _STLP_CALL
__stl_debug_engine<_Dummy>::_Check_same_owner( const __owned_link& __i1,
const __owned_link& __i2)
{
_STLP_VERBOSE_RETURN(__i1._Valid(), _StlMsg_INVALID_LEFTHAND_ITERATOR)
_STLP_VERBOSE_RETURN(__i2._Valid(), _StlMsg_INVALID_RIGHTHAND_ITERATOR)
_STLP_VERBOSE_RETURN((__i1._Owner()==__i2._Owner()), _StlMsg_DIFFERENT_OWNERS)
return true;
}
template <class _Dummy>
bool _STLP_CALL
__stl_debug_engine<_Dummy>::_Check_same_owner_or_null( const __owned_link& __i1,
const __owned_link& __i2)
{
_STLP_VERBOSE_RETURN(__i1._Owner()==__i2._Owner(), _StlMsg_DIFFERENT_OWNERS)
return true;
}
template <class _Dummy>
bool _STLP_CALL
__stl_debug_engine<_Dummy>::_Check_if_owner( const __owned_list * __l, const __owned_link& __it)
{
const __owned_list* __owner_ptr = __it._Owner();
_STLP_VERBOSE_RETURN(__owner_ptr!=0, _StlMsg_INVALID_ITERATOR)
_STLP_VERBOSE_RETURN(__l==__owner_ptr, _StlMsg_NOT_OWNER)
return true;
}
_STLP_END_NAMESPACE
#endif /* _STLP_DEBUG */
#endif /* if defined (EXPOSE_GLOBALS_IMPLEMENTATION) */
#endif /* header guard */
// Local Variables:
// mode:C++
// End:
|
the_stack_data/9513496.c | #include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define BUF_SIZE 30
void error_handling(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
int main(int argc, char const *argv[]) {
int sd;
FILE *fp;
char buf[ BUF_SIZE ];
int read_cnt;
struct sockaddr_in serv_adr;
if (argc != 3) {
printf("Usage : %s <IP> <port>\n", argv[ 0 ]);
exit(1);
}
fp = fopen("receive.cpp", "wb");
sd = socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = inet_addr(argv[ 1 ]);
serv_adr.sin_port = htons(atoi(argv[ 2 ]));
connect(sd, (struct sockaddr *) &serv_adr, sizeof(serv_adr));
while ((read_cnt = read(sd, buf, BUF_SIZE)) != 0)
fwrite((void *) buf, 1, read_cnt, fp);
puts("Received file data");
write(sd, "Thank you", 10);
fclose(fp);
close(sd);
return 0;
}
|
the_stack_data/40222.c | #include <stdio.h>
int isprime(int a)
{
int y=0;
for (int i=2;i<a;i++)
{
if(a%i==0)
{
y=1;
break;
}
}
return y;
}
int main()
{
int n;
scanf("%d",&n);
n++;
while(isprime(n))
{
n++;
}
printf("%d",n);
return 0;
} |
the_stack_data/67564.c | #include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
char *tuberia1 = "tuberia1";
char *tuberia2 = "tuberia2";
char buffer[256];
fd_set set;
int pipeselect, pipeactual, numpipeactual, bytes;
//Creamos las dos tuberias
mkfifo(tuberia1, 0644);
mkfifo(tuberia2, 0644);
//Abrimos las tuberías
int fd1 = open(tuberia1, O_RDONLY | O_NONBLOCK);
int fd2 = open(tuberia2, O_RDONLY | O_NONBLOCK);
while(1){
FD_ZERO(&set);
FD_SET(fd1,&set);
FD_SET(fd2,&set);
pipeselect = select((fd2>fd1) ? fd2+1 : fd1+1, &set, NULL,NULL,NULL);
if (FD_ISSET(fd1,&set)){
pipeactual = fd1;
numpipeactual = 1;
}else if (FD_ISSET(fd2,&set)){
pipeactual = fd2;
numpipeactual = 2;
}
ssize_t readsize = 256;
while(readsize == 256){
readsize = read(pipeactual, buffer, 256);
buffer[readsize] = '\0';
printf("Tuberia[%i]:%s\n",numpipeactual,buffer);
}
if (numpipeactual == 1){
close(fd1);
fd1 = open(tuberia1, O_RDONLY | O_NONBLOCK);
} else if (numpipeactual == 2){
close(fd2);
fd2 = open(tuberia2, O_RDONLY | O_NONBLOCK);
}
}
return 0;
}
|
the_stack_data/148793.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2012-2019 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 <termios.h>
#include <unistd.h>
static struct termios t;
static void
break_here ()
{
}
int main ()
{
tcgetattr (0, &t);
break_here ();
/* Disable ECHO. */
t.c_lflag &= ~ECHO;
tcsetattr (0, TCSANOW, &t);
tcgetattr (0, &t);
break_here ();
tcgetattr (0, &t);
break_here ();
return 0;
}
|
the_stack_data/165765449.c | // This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
typedef struct {
unsigned short a;
} A;
void foo1(unsigned int x) {
if (x != 0x800 && x != 0x810) {
ERROR:
goto ERROR;
}
}
void foo2(int x, int y) {
int l;
if (!((l = (t(x) - t(y)) ? 0 : 1) || 0)) {
foo1(0x800);
}
}
int t(int x) { return x + 2; }
int main(int argc, char **argv) {
int i;
for (i = 0; i < 2; ++i) {
foo1(((A){((!(i >> 4) ? 8 : 64 + (i >> 4)) << 8) + (i << 4)}).a);
}
int j = 7;
int a, b;
foo2(a = 1, b = (j & 2 == 2) ? t(b) : 1);
exit(0);
}
|
the_stack_data/168892464.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_print_combn.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: llima-ce <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/17 14:42:13 by llima-ce #+# #+# */
/* Updated: 2021/07/18 00:13:09 by llima-ce ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdio.h>
void ft_print(int My_Number[], int n);
void ft_print_combn(int n)
{
int My_Number[10];
int i;
i = 0;
while (i < n)
{
My_Number[i] = i + '0';
i++;
}
i = n - 1;
while (My_Number[0] <= 58 - n)
{
ft_print(My_Number, n);
My_Number[i]++;
if (My_Number[i] > 58 - n + i)
{
My_Number[i] = My_Number[i - 1] + 1;
i--;
}
if (My_Number[i] <= My_Number[i + 1])
{
i++;
}
}
}
void ft_print(int My_Number[], int n)
{
int o;
o = 0;
while (o <= n)
{
write(1, &My_Number[o], 1);
}
write(1, ", ", 2);
}
|
the_stack_data/122082.c | // 修改10.5节的poker.c程序,使其能识别牌的另一种类别——“同花大顺”(同花色的A、K、Q、J
// 和10)。 同花大顺的级别高于其他所有的类别。
/* Classifies a poker hand */
#include <stdbool.h> /* C99 only */
#include <stdio.h>
#include <stdlib.h>
#define RANK 0
#define SUIT 1
#define NUM_CARDS 5
/* external variables */
int hand[NUM_CARDS][2];
int pairs; /* can be 0, 1, or 2 */
bool four;
bool three;
bool straight;
bool flush;
bool new_rank_suit_type;
/* prototypes */
void read_cards(void);
void analyze_hand(void);
void print_result(void);
/************************************************************
* main: Calls read_cards, analyze_hand, and print_result *
* repeatedly. *
************************************************************/
int main(void) {
for (;;) {
read_cards();
analyze_hand();
print_result();
}
}
/************************************************************
* read_cards: Reads the cards into the external *
* variables num_in_rank and num_in_suit; *
* checks for bad cards and duplicate cards. *
***********************************************************/
void read_cards(void) {
// bool card_exists[NUM_RANKS][NUM_SUITS];
char ch, rank_ch, suit_ch;
int rank, suit;
bool bad_card;
int cards_read = 0;
while (cards_read < NUM_CARDS) {
bad_card = false;
printf("Enter a card: ");
rank_ch = getchar();
switch (rank_ch) {
case '0':
exit(EXIT_SUCCESS);
case '2':
rank = 0;
break;
case '3':
rank = 1;
break;
case '4':
rank = 2;
break;
case '5':
rank = 3;
break;
case '6':
rank = 4;
break;
case '7':
rank = 5;
break;
case '8':
rank = 6;
break;
case '9':
rank = 7;
break;
case 't':
case 'T':
rank = 8;
break;
case 'j':
case 'J':
rank = 9;
break;
case 'q':
case 'Q':
rank = 10;
break;
case 'k':
case 'K':
rank = 11;
break;
case 'a':
case 'A':
rank = 12;
break;
default:
bad_card = true;
}
suit_ch = getchar();
switch (suit_ch) {
case 'c':
case 'C':
suit = 0;
break;
case 'd':
case 'D':
suit = 1;
break;
case 'h':
case 'H':
suit = 2;
break;
case 's':
case 'S':
suit = 3;
break;
default:
bad_card = true;
}
while ((ch = getchar()) != '\n')
if (ch != ' ') bad_card = true;
if (bad_card) printf("Bad card; ignored.\n");
bool card_exist = false;
for (int i = 0; i != cards_read; ++i) {
if (hand[i][RANK] == rank && hand[i][SUIT] == suit) {
printf("Duplicate card; ignored.\n");
card_exist = true;
break;
}
}
if (!card_exist) {
hand[cards_read][RANK] = rank;
hand[cards_read][SUIT] = suit;
++cards_read;
}
}
}
/************************************************************
* analyze_hand: Determines whether the hand contains a *
* straight, a flush, four-of-a-kind, *
* and/or three-of-a-kind; determines the *
* number of pairs; stores the results into *
* the external variables straight, flush, *
* four, three, and pairs. *
************************************************************/
void analyze_hand(void) {
// 先根据rank排序
for (int i = 0; i != NUM_CARDS - 1; ++i) {
// 找到最小的index
int min_i = i;
for (int j = i + 1; j != NUM_CARDS; ++j) {
if (hand[j][RANK] < hand[min_i][RANK]) {
min_i = j;
}
}
// 交换
int temp_rank = hand[i][RANK];
int temp_suit = hand[i][SUIT];
hand[i][RANK] = hand[min_i][RANK];
hand[i][SUIT] = hand[min_i][SUIT];
hand[min_i][RANK] = temp_rank;
hand[min_i][SUIT] = temp_suit;
}
/* check for flush */
// 同花色
bool flush = true;
int suit = hand[0][SUIT];
for (int i = 1; i != NUM_CARDS; ++i) {
if (hand[i][SUIT] != suit) {
flush = false;
break;
}
}
/* check for straight */
// 顺子
straight = true;
for (int i = 0; i != NUM_CARDS - 1; ++i) {
if (hand[i][RANK] + 1 != hand[i + 1][RANK]) {
straight = false;
break;
}
}
// 同花大顺
new_rank_suit_type = false;
if (flush && straight) {
new_rank_suit_type = true;
int check_a[NUM_CARDS] = {8, 9, 10, 11, 12};
for (int i = 0; i != NUM_CARDS; ++i) {
if (hand[i][RANK] != check_a[i]) {
new_rank_suit_type = false;
break;
}
}
}
/* check for 4-of-a-kind, 3-of-a-kind, and pairs */
four = false;
three = false;
pairs = 0;
int card = 0;
while (card < NUM_CARDS) {
int rank = hand[card][RANK];
int run = 0;
do {
++run;
++card;
} while (card < NUM_CARDS && hand[card][RANK] == rank);
switch (run) {
case 2:
++pairs;
break;
case 3:
three = true;
break;
case 4:
four = true;
break;
}
}
}
/************************************************************
* print_result: prints the classification of the hand, *
* based on the values of the external *
* variables straight, flush, four, three, *
* and pairs. *
***********************************************************/
void print_result(void) {
if (new_rank_suit_type)
printf("同花大顺");
else if (straight && flush)
printf("Straight flush");
else if (four)
printf("Four of a kind");
else if (three && pairs == 1)
printf("Full house");
else if (flush)
printf("Flush");
else if (straight)
printf("Straight");
else if (three)
printf("Three of a kind");
else if (pairs == 2)
printf("Two pairs");
else if (pairs == 1)
printf("Pair");
else
printf("High card");
printf("\n\n");
}
|
the_stack_data/162644082.c | /* This File is Part of LibFalcon.
* Copyright (c) 2018, Syed Nasim
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 LibFalcon 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 HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(__cplusplus)
extern "C" {
#endif
inline unsigned char inportb (unsigned short port)
{
unsigned char rv;
asm volatile ("inb %1, %0" : "=a" (rv) : "dN" (port));
return rv;
}
#if defined(__cplusplus)
}
#endif
#if defined(__cplusplus)
extern "C" {
#endif
#include <string.h>
int bcmp(const void *s1, const void *s2, size_t n)
{
return memcmp(s1, s2, n);
}
#if defined(__cplusplus)
}
#endif
|
Subsets and Splits