file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/168893885.c
|
//
// Created by hengxin on 7/16/21.
//
#include <ncurses.h>
int main() {
initscr();
printw("Upper left corner "); addch(ACS_ULCORNER); printw("\n");
printw("Lower left corner "); addch(ACS_LLCORNER); printw("\n");
printw("Lower right corner "); addch(ACS_LRCORNER); printw("\n");
printw("Tee pointing right "); addch(ACS_LTEE); printw("\n");
printw("Tee pointing left "); addch(ACS_RTEE); printw("\n");
printw("Tee pointing up "); addch(ACS_BTEE); printw("\n");
printw("Tee pointing down "); addch(ACS_TTEE); printw("\n");
printw("Horizontal line "); addch(ACS_HLINE); printw("\n");
printw("Vertical line "); addch(ACS_VLINE); printw("\n");
printw("Large Plus or cross over "); addch(ACS_PLUS); printw("\n");
printw("Scan Line 1 "); addch(ACS_S1); printw("\n");
printw("Scan Line 3 "); addch(ACS_S3); printw("\n");
printw("Scan Line 7 "); addch(ACS_S7); printw("\n");
printw("Scan Line 9 "); addch(ACS_S9); printw("\n");
printw("Diamond "); addch(ACS_DIAMOND); printw("\n");
printw("Checker board (stipple) "); addch(ACS_CKBOARD); printw("\n");
printw("Degree Symbol "); addch(ACS_DEGREE); printw("\n");
printw("Plus/Minus Symbol "); addch(ACS_PLMINUS); printw("\n");
printw("Bullet "); addch(ACS_BULLET); printw("\n");
printw("Arrow Pointing Left "); addch(ACS_LARROW); printw("\n");
printw("Arrow Pointing Right "); addch(ACS_RARROW); printw("\n");
printw("Arrow Pointing Down "); addch(ACS_DARROW); printw("\n");
printw("Arrow Pointing Up "); addch(ACS_UARROW); printw("\n");
printw("Board of squares "); addch(ACS_BOARD); printw("\n");
printw("Lantern Symbol "); addch(ACS_LANTERN); printw("\n");
printw("Solid Square Block "); addch(ACS_BLOCK); printw("\n");
printw("Less/Equal sign "); addch(ACS_LEQUAL); printw("\n");
printw("Greater/Equal sign "); addch(ACS_GEQUAL); printw("\n");
printw("Pi "); addch(ACS_PI); printw("\n");
printw("Not equal "); addch(ACS_NEQUAL); printw("\n");
printw("UK pound sign "); addch(ACS_STERLING); printw("\n");
refresh();
getch();
endwin();
return 0;
}
|
the_stack_data/82950077.c
|
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* Portions copyright (c) 1999, 2000
* 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:
*
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
*
* This product includes software developed by the University of
* California, Berkeley, Intel Corporation, and its contributors.
*
* 4. Neither the name of University, Intel Corporation, or their respective
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS, INTEL CORPORATION AND
* CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS,
* INTEL CORPORATION 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.
*
*/
/*++
Module Name:
wasctime.c
Abstract:
Wide char string asctime
Revision History
--*/
#include <sys/stat.h>
#include <wchar.h>
#include <time.h>
#include <stdlib.h>
wchar_t *wasctime ( const struct tm * timeptr)
{
static wchar_t result[26];
char *time;
time = asctime ( timeptr);
mbstowcs((wchar_t *) result,time, 26);
return result;
}
|
the_stack_data/25138793.c
|
#include <stdio.h>
#define MATRIZ 12
int main() {
int linha;
scanf("%d", &linha);
char operacao[2];
scanf("%s", &operacao);
double resultado = 0.0;
int i, j;
double matriz[MATRIZ][MATRIZ];
for (i = 0; i < MATRIZ; i++){
for(j = 0; j < MATRIZ; j++){
scanf("%lf", &matriz[i][j]);
if (i == linha){
resultado += matriz[i][j];
}
}
}
if (operacao[0] == 'S'){
printf("%.1lf\n", resultado);
}
else if (operacao[0] == 'M'){
double divisor = (double) MATRIZ;
double media = resultado / divisor;
printf("%.1lf\n", media);
}
return 0;
}
|
the_stack_data/173578152.c
|
/**
* Allow Perseverance to Finish Its Work.
*
* By walking through this example you’ll learn:
* - In the parent process, wait for the child process to complete its work.
* - How to use wait().
*
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
//
// Expected output:
//
// It breaks my heart to see my fellow zealots suffer on the battlefield
// But what if we dragoons went to their rescue?
// Duh! Ra! Goon!
//
int main(int argc, char* argv[]){
pid_t pid;
int status;
printf("It breaks my heart to see my fellow zealots suffer on the battlefield.\n");
printf("But what if we dragoons went to their rescue?\n");
printf("Duh! ");
fflush(stdout);
pid = fork();
if(pid > 0){
// HINT: The parent process should fall into this scope.
wait(&status);
printf("Goon!\n");
} else if(pid == 0){
// HINT: The child process should fall into this scope.
printf("Ra! ");
} else {
printf("WTF?");
return -1;
}
return 0;
}
|
the_stack_data/66985.c
|
/******************************************************************************
* Copyright (C) 2017 by Alex Fosdick - University of Colorado
*
* Redistribution, modification or use of this software in source or binary
* forms is permitted as long as the files maintain this copyright. Users are
* permitted to modify this and use it to learn about the field of embedded
* software. Alex Fosdick and the University of Colorado are not liable for any
* misuse of this material.
*
*****************************************************************************/
#include <stdio.h>
/* A pretty boring main file */
int main(void){
printf("\nModule Demo File!\n");
return 0;
}
|
the_stack_data/28709.c
|
#include <stdio.h>
int sum(int n1, int n2);
int keyCheck(char key);
int main()
{
int n1, n2;
char key;
printf("\nEnter the first number: ");
scanf("%d", &n1);
printf("\nEnter the second number: ");
scanf("%d", &n2);
printf("\nPress the third button (ENTER) : ");
getchar();
scanf("%c", &key);
if (keyCheck(key) == 1)
{
if (sum(n1, n2) == 0)
printf("0-PROXYCITY\n");
else if (sum(n1, n2) == 1)
printf("1-DNSUEY!\n");
else if (sum(n1, n2) == 2)
printf("2-P.Y.N.G.\n");
else if (sum(n1, n2) == 3)
printf("3-SERVERS\n");
else if (sum(n1, n2) == 4)
printf("4-CRIPTONIZE\n");
else if (sum(n1, n2) == 5)
printf("5-HOST!\n");
else if (sum(n1, n2) == 6)
printf("6-OFFLINEDAY\n");
else if (sum(n1, n2) == 7)
printf("7-SALT\n");
else if (sum(n1, n2) == 8)
printf("8-ANSWER!\n");
else if (sum(n1, n2) == 9)
printf("9-RAR?\n");
else if (sum(n1, n2) == 10)
printf("10-WIFI ANTENNAS\n");
}
}
int sum(int n1, int n2)
{
return n1 + n2;
}
int keyCheck(char key)
{
if (key == 0x0A)
return 1;
else
return 0;
}
|
the_stack_data/76699706.c
|
#include <stdio.h>
int main()
{
int my_value = 1337;
// &: Memoryaddress
printf("Value: %d\n", my_value);
printf("Memory address: %p\n", (void *)(&my_value));
printf("Size: %lu\n", sizeof(my_value));
return 0;
}
|
the_stack_data/9512877.c
|
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *left;
struct node *right;
};
struct node * insert(struct node *temp,int x);
struct node * out(struct node *temp1);
int main(){
int val;
struct node *root =NULL;
printf("enter value to insert into BST, \nenter 200 to print the BST inorder traversal\n\n\n");
while(1){
scanf("%d",&val);
if(val==200){
out(root);
continue;
}
if(root==NULL){
root = insert(root,val);
}
else{
insert(root,val);
}
}
return 0;
}
struct node * insert(struct node *temp,int x){
if (temp==NULL){
temp = (struct node*)malloc(sizeof(struct node));
temp->data=x;
temp->left=NULL;
temp->right=NULL;
return temp;
}
else{
if(temp->data<x){
temp->right= insert(temp->right,x);
}
else{
temp->left= insert(temp->left,x);
}
}
}
struct node * out(struct node *temp1){
if(temp1==NULL){
return;
}
else{
out(temp1->left);
printf("%d ",temp1->data);
out(temp1->right);
}
}
|
the_stack_data/243893933.c
|
#include <stdint.h>
static const uint32_t sha256_k[] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
#define rotr(v, b) (((uint32_t)v >> b) | (v << (32 - b)))
static inline void sha256round(uint32_t *hs, uint32_t *w) {
for (int i = 16; i < 64; ++i) {
uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
}
uint32_t a = hs[0];
uint32_t b = hs[1];
uint32_t c = hs[2];
uint32_t d = hs[3];
uint32_t e = hs[4];
uint32_t f = hs[5];
uint32_t g = hs[6];
uint32_t h = hs[7];
for (int i = 0; i < 64; ++i) {
uint32_t s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
uint32_t ch = (e & f) ^ (~e & g);
uint32_t temp1 = (h + s1 + ch + sha256_k[i] + w[i]);
uint32_t s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
uint32_t temp2 = (s0 + maj);
h = g;
g = f;
f = e;
e = (d + temp1);
d = c;
c = b;
b = a;
a = (temp1 + temp2);
}
hs[0] += a;
hs[1] += b;
hs[2] += c;
hs[3] += d;
hs[4] += e;
hs[5] += f;
hs[6] += g;
hs[7] += h;
}
#define INLINE __attribute__((always_inline)) static inline
INLINE void sha256block(uint8_t *buf, uint32_t len, uint32_t *dst) {
uint32_t hs[] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
uint32_t w[64];
for (uint32_t i = 0; i < len; i += 64) {
for (uint32_t j = 0; j < 16; j++) {
uint32_t off = (j << 2) + i;
w[j] = (buf[off] << 24) | (buf[off + 1] << 16) | (buf[off + 2] << 8) |
buf[off + 3];
}
sha256round(hs, w);
}
dst[0] = hs[0];
dst[1] = hs[1];
}
#define POLYNOMIAL 0xEDB88320
INLINE void makeCRC32tab(uint32_t *table) {
for (uint32_t b = 0; b < 256; ++b) {
uint32_t r = b;
for (uint32_t j = 0; j < 8; ++j) {
if (r & 1)
r = (r >> 1) ^ POLYNOMIAL;
else
r = (r >> 1);
}
table[b] = r;
}
}
INLINE uint32_t crc(const uint8_t *p, uint32_t len, uint32_t *crcTable) {
uint32_t crc = ~0U;
for (uint32_t i = 0; i < len; ++i)
crc = crcTable[*p++ ^ (crc & 0xff)] ^ (crc >> 8);
return (~crc);
}
INLINE uint32_t murmur3_core(const uint8_t *data, uint32_t len) {
uint32_t h = 0x2F9BE6CC;
const uint32_t *data32 = (const uint32_t *)data;
uint32_t i = len >> 2;
do {
uint32_t k = *data32++;
k *= 0xcc9e2d51;
k = (k << 15) | (k >> 17);
k *= 0x1b873593;
h ^= k;
h = (h << 13) | (h >> 19);
h = (h * 5) + 0xe6546b64;
} while (--i);
return h;
}
INLINE void murmur3_core_2(const uint8_t *data, uint32_t len, uint32_t *dst) {
// compute two hashes with different seeds in parallel, hopefully reducing
// collisions
uint32_t h0 = 0x2F9BE6CC;
uint32_t h1 = 0x1EC3A6C8;
const uint32_t *data32 = (const uint32_t *)data;
uint32_t i = len >> 2;
do {
uint32_t k = *data32++;
k *= 0xcc9e2d51;
k = (k << 15) | (k >> 17);
k *= 0x1b873593;
h0 ^= k;
h1 ^= k;
h0 = (h0 << 13) | (h0 >> 19);
h1 = (h1 << 13) | (h1 >> 19);
h0 = (h0 * 5) + 0xe6546b64;
h1 = (h1 * 5) + 0xe6546b64;
} while (--i);
dst[0] = h0;
dst[1] = h1;
}
int Reset_Handler(uint32_t *dst, uint8_t *ptr, uint32_t pageSize,
uint32_t numPages) {
uint32_t crcTable[256];
makeCRC32tab(crcTable);
for (uint32_t i = 0; i < numPages; ++i) {
#if 0
sha256block(ptr, pageSize, dst);
#elif 0
dst[0] = crc(ptr, pageSize, crcTable);
dst[1] = murmur3_core(ptr, pageSize);
#else
murmur3_core_2(ptr, pageSize, dst);
#endif
dst += 2;
ptr += pageSize;
}
#ifdef __arm__
__asm__("bkpt 42");
#endif
return 0;
}
#if 0
#define PAGE_SIZE 0x400
#define SIZE_IN_WORDS (PAGE_SIZE / 4)
#define setConfig(v) \
do { \
NRF_NVMC->CONFIG = v; \
while (NRF_NVMC->READY == NVMC_READY_READY_Busy) \
; \
} while (0)
void overwriteFlashPage(uint32_t *to, uint32_t *from) {
int same = 1;
for (int i = 0; i <= (SIZE_IN_WORDS - 1); i++) {
if (to[i] != from[i]) {
same = 0;
break;
}
}
if (same)
return;
// Turn on flash erase enable and wait until the NVMC is ready:
setConfig(NVMC_CONFIG_WEN_Een << NVMC_CONFIG_WEN_Pos);
// Erase page:
NRF_NVMC->ERASEPAGE = (uint32_t)to;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
;
// Turn off flash erase enable and wait until the NVMC is ready:
setConfig(NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);
// Turn on flash write enable and wait until the NVMC is ready:
setConfig(NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos);
for (int i = 0; i <= (SIZE_IN_WORDS - 1); i++) {
*(to + i) = *(from + i);
while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
;
}
// Turn off flash write enable and wait until the NVMC is ready:
setConfig(NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);
}
#endif
#ifndef __arm__
#define PS 1024
#define NP 10
#include <stdio.h>
#include <string.h>
int main() {
uint8_t buf[NP * PS];
uint32_t sums[NP * 2];
memset(buf, 0, sizeof(buf));
for (int i = 0; i < PS; ++i)
buf[i] = i;
for (int i = 0; i < PS; ++i)
buf[i + PS] = 108;
Reset_Handler(sums, buf, PS, NP);
for (int i = 0; i < NP; ++i) {
printf("%08x %08x\n", sums[i * 2], sums[i * 2 + 1]);
}
return 0;
}
#endif
|
the_stack_data/97013680.c
|
//把一组字符串中的数字转换并加起来
#include "stdio.h"
#include "stdlib.h"
int add(char **d, int n)
{
int result=0, tmp;
for(int i=0;i<n;i++){
tmp=atoi(d[i]);
result+=tmp;
}
return result;
}
int main()
{
char *values[]={"15","27","38"};
int n=sizeof(values)/sizeof(char *);
printf("result=%d\n", add(values, n));
return 0;
}
|
the_stack_data/631777.c
|
#include <math.h>
double fdim(double x, double y)
{
if (isnan(x))
return x;
if (isnan(y))
return y;
return x > y ? x - y : 0;
}
|
the_stack_data/3263810.c
|
/*! 'serial port' module (UART) */
#ifdef UART
#include "uart.h"
#include "../io.h"
#include "../interrupt.h"
#include <arch/device.h>
#include <kernel/errno.h>
/*!
* Identify UART chip
* - algorithm taken from:
* http://en.wikibooks.org/wiki/Serial_Programming/8250_UART_Programming
*/
static int identify_UART ( arch_uart_t *up )
{
int test;
if ( up->uart_type )
return up->uart_type;
outb ( COM1_BASE + FCR, 0xE7 );
test = inb ( COM1_BASE + IIR );
if ( test & 0x40 )
{
if ( test & 0x80 )
{
if ( test & 0x20 )
up->uart_type = UT16750;
else
up->uart_type = UT16550A;
}
else {
up->uart_type = UT16550;
}
}
else {
outb ( COM1_BASE + SR, 0x2A );
test = inb ( COM1_BASE + SR );
if ( test == 0x2A )
up->uart_type = UT16450;
else
up->uart_type = UT8250;
}
return up->uart_type;
}
/*! Initialize UART device */
static int uart_init ( uint flags, void *params, device_t *dev )
{
arch_uart_t *up;
/* set default parameters */
up = dev->params;
/* check chip */
identify_UART ( up );
if ( up->uart_type )
return 0; /* already initialized */
return uart_config ( dev, &up->params );
}
/*! Set UART configuration */
static int uart_config ( device_t *dev, uart_t *params )
{
arch_uart_t *up;
uint8 setting;
ASSERT_AND_RETURN_ERRNO ( dev && params, -EINVAL );
ASSERT_AND_RETURN_ERRNO ( params->data_bits >= 5 || params->data_bits<=8,
-EINVAL );
ASSERT_AND_RETURN_ERRNO ( params->parity >= 0 || params->parity <= 7,
-EINVAL );
ASSERT_AND_RETURN_ERRNO ( params->stop_bit >= STOPBIT_1 ||
params->stop_bit <= STOPBIT_15,
-EINVAL );
ASSERT_AND_RETURN_ERRNO ( params->mode == UART_BYTE ||
params->mode == UART_STREAM,
-EINVAL );
up = dev->params;
up->params = *params;
/* first disable interrupts */
outb ( up->port + IER, 0 );
/* clear FIFO (set FCR) */
if ( up->uart_type > UT8250 )
{
setting = FCR_ENABLE | FCR_CLEAR;
if ( params->mode == UART_BYTE )
setting |= FCR_BYTE_MODE;
else
setting |= FCR_STREAM_MODE;
if ( up->uart_type == UT16750 )
setting |= FCR_64BYTES;
outb ( up->port + FCR, setting );
}
/* load divisor */
outb ( up->port + LCR, LCR_DLAB_ON ); /* set DLAB=1 */
outb ( up->port + DLL, up->params.speed & 0xff ); /* Low Byte */
outb ( up->port + DLM, up->params.speed >> 8 ); /* High Byte */
outb ( up->port + LCR, LCR_DLAB_OFF ); /* set DLAB=0 */
/* set LCR */
setting = up->params.data_bits - 5;
setting |= up->params.parity | up->params.stop_bit | LCR_DLAB_OFF;
if ( up->uart_type >= UT16550 )
setting |= LCR_BREAK;
/* set MCR */
outb ( up->port + MCR, MCR_DEFAULT );
/* set IER */
outb ( up->port + IER, IER_DEFAULT );
/* "clear" software buffers */
up->inf = up->inl = up->insz = 0;
up->outf = up->outl = up->outsz = 0;
return 0;
}
/*! Disable UART device */
int uart_destroy ( uint flags, void *params, device_t *dev )
{
arch_uart_t *up;
ASSERT ( dev );
up = dev->params;
/* clear IER - disable interrupt generation */
outb ( up->port + IER, IER_DISABLE );
return 0;
}
/*! Interrupt handler for UART device */
static int uart_interrupt_handler ( int irq_num, void *device )
{
device_t *dev;
arch_uart_t *up;
uint8 iir;
int brk, rcv, snd;
dev = device;
up = dev->params;
rcv = snd = brk = FALSE;
while (1)
{
iir = inb ( up->port + IIR );
if ( !( iir & IIR_INT_PENDING ) )
return 0; /* no interrupt pending from this device */
if ( iir & IIR_TIMEOUT )
brk = TRUE;
if ( iir & IIR_LINE )
{
if ( inb ( up->port + LSR ) & LSR_DATA_READY )
rcv = TRUE;
else if ( inb ( up->port + LSR ) & LSR_THR_EMPTY )
snd = TRUE;
else if ( inb ( up->port + LSR ) & LSR_BREAK )
snd = TRUE;
/* else TODO: handle errors */
}
if ( rcv || brk || ( iir & IIR_RECV_DATA ) )
{
/* read data from UART to software buffer */
uart_read ( up );
rcv = TRUE;
continue;
}
if ( snd || iir & IIR_THR_EMPTY )
{
/* if there is data in software buffer send them */
uart_write ( up );
snd = TRUE;
continue;
}
if ( iir & IIR_MODEM )
{
/* TODO: handle modem interrupts */
}
}
/* TODO: do something with rcv, snd, brk ? */
return 0;
}
/*! If there is data in software buffer send them to UART */
static void uart_write ( arch_uart_t *up )
{
while ( up->outsz > 0 && inb ( up->port + LSR ) & LSR_THR_EMPTY )
{
outb ( up->port + THR, up->outbuff[up->outf] );
INC_MOD ( up->outf, up->outbufsz );
up->outsz--;
}
}
/*! Send data to UART device (through software buffer) */
static int uart_send ( void *data, size_t size, uint flags, device_t *dev )
{
arch_uart_t *up;
uint8 *d;
ASSERT ( dev );
if ( flags & UART_SETCONF )
return uart_config ( dev, (uart_t *) data );
/* send */
flags &= ~UART_SETCONF;
up = dev->params;
d = data;
do {
/* first, copy to software buffer */
while ( size > 0 && up->outsz < up->outbufsz )
{
if ( *d == 0 && flags == CONSOLE_PRINT )
{
size = 0;
break;
}
up->outbuff[up->outl] = *d++;
INC_MOD ( up->outl, up->outbufsz );
up->outsz++;
size--;
}
/* second, copy from software buffer to uart */
uart_write ( up );
}
while ( size > 0 && up->outsz < up->outbufsz );
return size; /* FIXME 0 if all sent, otherwise not send part length */
}
/*! Read data from UART to software buffer */
static void uart_read ( arch_uart_t *up )
{
/* While UART is not empty and software buffer is not full */
while ( ( inb ( up->port + LSR ) & LSR_DATA_READY )
&& up->insz < up->inbufsz )
{
up->inbuff[up->inl] = inb ( up->port + RBR );
INC_MOD ( up->inl, up->inbufsz );
up->insz++;
}
}
/*! Read from UART (using software buffer) */
static int uart_recv ( void *data, size_t size, uint flags, device_t *dev )
{
arch_uart_t *up;
uint8 *d;
int i;
ASSERT ( dev );
up = dev->params;
if ( flags & UART_GETCONF )
{
if ( size < sizeof (uart_t) )
return EXIT_FAILURE;
*( (uart_t *) data ) = up->params;
return sizeof (uart_t);
}
/* else = flags == UART_RECV */
/* first, copy from uart to software buffer */
uart_read ( up );
/* second, copy from software buffer to data */
d = data;
i = 0;
while ( i < size && up->insz > 0 )
{
d[i] = up->inbuff[up->inf];
INC_MOD ( up->inf, up->inbufsz );
up->insz--;
i++;
}
return i; /* bytes read */
}
/*! Get status */
static int uart_status ( uint flags, device_t *dev )
{
arch_uart_t *up;
int rflags = 0;
ASSERT ( dev );
up = dev->params;
/* first, copy from uart to software buffer */
uart_read ( up );
/* look up software buffers */
if ( up->insz > 0 )
rflags |= DEV_IN_READY;
if ( up->outsz < up->outbufsz )
rflags |= DEV_OUT_READY;
//kprintf ( "status = %d\n", rflags );
return rflags;
}
/*! uart0 device & parameters */
static uint8 com1_inbuf[BUFFER_SIZE];
static uint8 com1_outbuf[BUFFER_SIZE];
/*! COM1 device & parameters */
static arch_uart_t com1_params = (arch_uart_t)
{
.uart_type = UNDEFINED,
.params = UART_DEFAULT_SETTING,
.port = COM1_BASE,
.inbuff = com1_inbuf,
.inbufsz=BUFFER_SIZE, .inf = 0, .inl = 0, .insz = 0,
.outbuff = com1_outbuf,
.outbufsz=BUFFER_SIZE, .outf = 0, .outl = 0, .outsz = 0
};
/*! uart as device_t */
device_t uart_com1 = (device_t)
{
.dev_name = "COM1",
.irq_num = IRQ_COM1,
.irq_handler = uart_interrupt_handler,
.init = uart_init,
.destroy = uart_destroy,
.send = uart_send,
.recv = uart_recv,
.status = uart_status,
.flags = DEV_TYPE_SHARED | DEV_TYPE_CONSOLE,
.params = &com1_params
};
#endif /* UART */
|
the_stack_data/140764447.c
|
#include <assert.h>
void _assert(const char* file, long line, const char* exp)
{
//fprintf(stderr, "Assertion failed: %s, file %s, line %l\n", exp, file, line);
__asm__("int $3");
}
|
the_stack_data/242330264.c
|
/*
Lista de Exercícios 01
Exercício 06
Autor: Murilo Carvalho
*/
#include <stdio.h>
int main(){
/*
Elabore um algoritmo que calcule o preço de venda de um carro.
O preço de venda é formado pelo preço da montadora,
mais 15% de lucro, mais 11% de IPI, mais 17% de ICM.
As porcentagens são sobre o preço da montadora, que é lido.
Apresente na tela o preço final e o valor dos impostos.
*/
float precoMontadora = 0.0;
float valorImpostos = 0.0;
float valorVendaCarro = 0.0;
printf("***** Preco de Venda de Carro (R$) *****");
printf("\n");
printf("Informe o preco de custo da montadora:");
scanf("%f",&precoMontadora);
valorImpostos = precoMontadora*0.11;
valorImpostos += precoMontadora*0.17;
valorVendaCarro = precoMontadora + (precoMontadora*0.15) + valorImpostos;
printf("========== Valor final do Carro =============== \n");
printf("Preco da Montadora.: R$%.2f \n",precoMontadora);
printf("IPI: R$%.2f \n", precoMontadora*0.11);
printf("ICM: R$%.2f \n", precoMontadora*0.17);
printf("Valor total dos impostos: R$%.2f \n", valorImpostos);
printf("Valor de venda final do carro: R$%.2f", valorVendaCarro);
return 0;
}
|
the_stack_data/37645.c
|
extern int xxx;
int
main ()
{
return xxx;
}
|
the_stack_data/97012508.c
|
/*
Author : Arnob Mahmud
mail : [email protected]
*/
#include <stdio.h>
#include <math.h>
int main(int argc, char const *argv[])
{
float setup_cost, demand_rate, holding_cost, EOQ, TBO;
printf("Enter set up cost :\n");
scanf("%f", &setup_cost);
printf("Enter demand rate :\n");
scanf("%f", &demand_rate);
printf("Enter holding cost :\n");
scanf("%f", &holding_cost);
EOQ = sqrt((2 * demand_rate * setup_cost) / holding_cost);
TBO = sqrt((2 * setup_cost / demand_rate * holding_cost));
printf("EOQ is %.2f.\n", EOQ);
printf("TBO is %.2f.\n", TBO);
return 0;
}
|
the_stack_data/10103.c
|
/*
* This file is the 'memsnoop' application. memsnoop 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, version 2.
* 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.
*
* Copyright (C) 2017 Pelagicore
*
* This application is used to read and write raw memory via the /dev/mem
* interface. Please note that reading/writing the wrong locations in memory
* is dangerous, and can damage your system. Only use this application on
* memory addresses you know are safe, and preferrably in a virtual machine.
*
* You can find interesting memory locations in /proc/iomem.
*
* Usage: memsnoop read 0x<address> <num bytes to read>
* or
* memsnoop write 0x<address> 0x<offset in bytes> 0x<byte value to write>
*/
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#define ERROR(x) { \
fprintf(stderr, "%s\n", ((x))); \
exit(1); \
}
void read_bytes(char *mem, long addr, unsigned int size) {
while(size) {
int i = 16;
printf("0x%lx: ", addr);
for (; i > 0 && size > 0; i--, size--, addr++) {
printf("%.2x ", *mem++);
}
printf("\n");
}
}
void write_bytes(char *mem, unsigned int offset, char value) {
*(mem+offset) = value;
}
void usage(char *name) {
fprintf(stderr, "USAGE: %s read 0x<address> <num bytes to read>\n"
"%s write 0x<address> 0x<offset in bytes> 0x<byte value to write>\n",
name, name);
}
int main(int argc, char *argv[]) {
char *mem, *command;
int fd;
long addr;
unsigned int size;
if (argc < 4) {
usage(argv[0]);
exit(1);
}
if (sscanf(argv[1], "%ms", &command) <= 0) {
usage(argv[0]);
ERROR("\nFailed to read command (read/write)");
}
if (sscanf(argv[2],"%10lx", &addr) <= 0) {
usage(argv[0]);
ERROR("\nFailed to read address (must be hexadecimal, prefixed with 0x)");
}
fd = open ("/dev/mem", O_RDWR);
if (fd <= 0) {
ERROR("Failed to open /dev/mem");
}
mem = mmap(NULL, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd,
(off_t) addr);
assert(mem != MAP_FAILED);
if (!strncmp(command, "read", 4)) {
if (sscanf(argv[3],"%10u", &size) <= 0) {
usage(argv[0]);
ERROR("\nFailed to read count (must be decimal integer value)");
}
read_bytes(mem, addr, size);
} else if (!strncmp(command, "write", 5)) {
unsigned char value;
unsigned long offset;
if (argc != 5) {
usage(argv[0]);
ERROR("\nNot enough arguments");
}
if (sscanf(argv[3],"%10lx", &offset) <= 0) {
usage(argv[0]);
ERROR("\nFailed to read offset (must be hexadecimal, prefixed with 0x)");
}
if (sscanf(argv[4]+2,"%02hhx", &value) <= 0) {
usage(argv[0]);
ERROR("\nFailed to read value (must be hexadecimal, prefixed with 0x)");
}
write_bytes(mem, offset, value);
} else {
usage(argv[0]);
exit(1);
}
munmap(mem, getpagesize());
close(fd);
return 0;
}
|
the_stack_data/1186225.c
|
// gcc -o fibc fib.c
// Time taken 2 seconds 739 milliseconds
#include <stdio.h>
#include <time.h>
int fib(int n) {
if(n <= 2) {
return 1;
}
return fib(n-2) + fib(n-1);
}
int main() {
clock_t start = clock(), diff;
for(int i = 1; i <= 42; i++) {
printf("%d ", fib(i));
fflush(stdout);
}
diff = clock() - start;
int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("\nTime taken %d seconds %d milliseconds\n", msec/1000, msec%1000);
return 0;
}
|
the_stack_data/51699429.c
|
#include<stdio.h>
int fact(int num);
main( )
{
int n,factorial;
printf("Enter the number\n");
scanf("%d",&n);
if(n==0)
printf("Factorial of %d is : 1",n);
else
{
factorial=fact(n);
printf("Factorial of %d is : %d",n,factorial);
}
}
int fact(int num)
{
int i,f=1;
for(i=1;i<=num;i++)
f=f*i;
return(f);
}
|
the_stack_data/4290.c
|
// [ACM] #10222 - Decode the Mad man
// Problem Status CPU Date&Time(UTC) ID Best CPU
// 10222 Accepted 0.000 2006-10-30 15:14:39 5089507 0.000
#include<stdio.h>
int main(void)
{
char c;
while(1)
{
c = getchar();
if(c == EOF)
break;
if('0' <= c && c <= '9')
{
if(c == '0')
printf("8");
else
printf("%c" , c - 2);
}
else if('a' <= c && c <= 'z')
{
switch(c)
{
case 'c' :
printf("z");
break;
case 'v' :
printf("x");
break;
case 'b' :
printf("c");
break;
case 'n' :
printf("v");
break;
case 'm' :
printf("b");
break;
case 'd' :
printf("a");
break;
case 'f' :
printf("s");
break;
case 'g' :
printf("d");
break;
case 'h' :
printf("f");
break;
case 'j' :
printf("g");
break;
case 'k' :
printf("h");
break;
case 'l' :
printf("j");
break;
case 'e' :
printf("q");
break;
case 'r' :
printf("w");
break;
case 't' :
printf("e");
break;
case 'y' :
printf("r");
break;
case 'u' :
printf("t");
break;
case 'i' :
printf("y");
break;
case 'o' :
printf("u");
break;
case 'p' :
printf("i");
break;
}
}
else
{
switch(c)
{
case '\n' :
printf("\n");
break;
case ' ' :
printf(" ");
break;
case '-' :
printf("9");
break;
case '=' :
printf("0");
break;
case '\\' :
printf("-");
break;
case '[' :
printf("o");
break;
case ']' :
printf("p");
break;
case ';' :
printf("k");
break;
case '\'' :
printf("l");
break;
case ',' :
printf("n");
break;
case '.' :
printf("m");
break;
case '/' :
printf(",");
break;
}
}
}
return 0;
}
|
the_stack_data/154626.c
|
/*
* Copyright (c) 2013 Qualcomm Atheros, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the
* disclaimer below) 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 Qualcomm Atheros nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
* GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define MAX_READ_SIZE 80
uint32_t checksum = 0;
void write_file(FILE *out, unsigned char *buf, uint32_t size, unsigned char *endian, unsigned char nl)
{
int i=0;
unsigned char tmp_buf[4];
for(i=0; i<size; i+=4)
{
if( nl==1 )
{
if(i%16 == 0) {
fprintf(out, "\n");
}
tmp_buf[0] = buf[i];
tmp_buf[1] = buf[i+1];
tmp_buf[2] = buf[i+2];
tmp_buf[3] = buf[i+3];
fprintf(out, "0x%08X, ", *((uint32_t *)(&tmp_buf[0])));
} else {
if(i%16 == 0) {
fprintf(out, "\n");
}
tmp_buf[0] = buf[i+3];
tmp_buf[1] = buf[i+2];
tmp_buf[2] = buf[i+1];
tmp_buf[3] = buf[i+0];
fprintf(out, "0x%08X, ", *((uint32_t *)(&tmp_buf[0])));
}
checksum = checksum ^ *((uint32_t *)(&tmp_buf[0]));
}
}
void write_rom(FILE *out, FILE *in)
{
int size;
long file_size;
unsigned char buffer[MAX_READ_SIZE];
int multiple = 0;
file_size = size = 0;
while(1)
{
size = fread(buffer, sizeof(unsigned char), sizeof(buffer), in);
file_size += size;
//write_file(out, buffer, size, NULL, 0);
if( size == 0 )
{
if (multiple)
fprintf(out, "%08X\n", checksum);
goto ERR_DONE;
}
else if (size<MAX_READ_SIZE)
{
multiple = 0;
write_file(out, buffer, size, NULL, 1);
fprintf(out, "%08X\n", checksum);
goto ERR_DONE;
}
else if (size==MAX_READ_SIZE)
{
multiple = 1;
write_file(out, buffer, MAX_READ_SIZE, NULL, 1);
}
else
goto ERR_DONE;
}
ERR_DONE:
return;
}
void write_array(FILE *out, FILE *in, unsigned char hif)
{
int size;
long file_size;
unsigned char buffer[MAX_READ_SIZE];
int multiple = 0;
file_size = size = 0;
// fprintf(out, "#include \"80211core_sh.h\"\n");
fprintf(out, "#include <stdint.h>\n");
fprintf(out, "const uint32_t zcFwImage[] = {\n");
while(1)
{
size = fread(buffer, sizeof(unsigned char), sizeof(buffer), in);
file_size += size;
if( size == 0 )
{
if (multiple)
{
fprintf(out, "0x%08X\n", checksum);
file_size += 4;
}
fprintf(out, "};\n");
fprintf(out, "\nconst uint32_t zcFwImageSize=%ld;\n", file_size);
goto ERR_DONE;
}
else if (size<MAX_READ_SIZE)
{
multiple = 0;
write_file(out, buffer, size, NULL, hif);
fprintf(out, "0x%08X\n", checksum);
if( (size%4)!=0 )
file_size += (4-(size%4));
file_size += 4;
fprintf(out, "};\n");
fprintf(out, "\nconst uint32_t zcFwImageSize=%ld;\n", file_size);
goto ERR_DONE;
}
else if (size==MAX_READ_SIZE)
{
multiple = 1;
write_file(out, buffer, MAX_READ_SIZE, NULL, hif);
}
else
goto ERR_DONE;
}
ERR_DONE:
return;
}
int main(int argc, char* argv[])
{
FILE *in, *out;
int retVal;
int i=0;
char input_file_name[80];
char output_file_name[80];
in = out = 0x0;
if( argc < 3 )
{
printf("\"bin2hex [input_file] [output_file] - gen array data\"!\n\r");
printf("\"bin2hex [input_file] [output_file] [rom]- gen rom code\"!\n\r");
goto ERR_DONE;
}
strcpy(input_file_name, argv[1]);
strcpy(output_file_name, argv[2]);
printf("bin2h %s %s!\n\r", input_file_name, output_file_name);
if((in = fopen(input_file_name,"rb")) == NULL)
goto ERR_DONE;
if((out = fopen(output_file_name,"wt")) == NULL)
goto ERR_DONE;
if( !strcmp(argv[3],"rom"))
/* for loading into RAM directly, e.g ROM code or patch code */
write_rom(out, in);
else {
if(!strcmp(argv[4],"usb"))
write_array(out, in, 1); /* for generating firmware (usb) */
else if (!strcmp(argv[4],"pci"))
write_array(out, in, 0); /* for generating firmware (pci) */
else
write_array(out, in, 1); /* Default case firmware (usb) */
}
ERR_DONE:
if(in) fclose(in);
if(out) fclose(out);
return 0;
}
|
the_stack_data/68886493.c
|
/*
program to window portion of 3-D data file
window len= [in= out= planes= vecs= esize= p0= v0= e0= np= nv= ne= dp= dv= de=]
arguments:
in=stdin input file, a series of vectors
out=stdout windowed result
len=(nt=) length of input file vector
vecs=(nx=) number of vectors in a plane
planes=1 number of planes in dataset
esize=4 size of input file element in bytes
p0=0 the first plane to be copied
v0=0 the first vector in each plane to be copied
e0=0 the first element of each vector to be copied
np=(planes-p0)/dp the number of planes to be copied
nv=(vecs-v0)/dv the number of vectors to be copied
ne=(len-e0)/de the number of elements from each vector to be copied
dp=1 increment between input planes
dv=1 increment between input vectors
de=1 increment between input elements
#
to compile: cc window -o window -lget
*/
#include <stdio.h>
#include <fcntl.h>
char in[40], out[40];
main (argc,argv)
int argc; char **argv;
{
int rfile,wfile;
int len,esize=4;
int v0=0,e0=0,nv=0,ne=0,dv=1,de=1;
int nseek,de1,i,j,k,planes=1,vecs=0,np=0,dp=1,nseek1,m,p0=0;
char *x;
/* fetch parameters */
setpar(argc,argv);
if (getpar("in","s",in)) {
if ((rfile = open(in,O_RDONLY,0644)) < 2) {
fprintf(stderr,"cannot open %s\n",in);
exit(-1);
}
}
else rfile=0;
if (getpar("out","s",out)) {
if ((wfile = open(out,O_WRONLY | O_CREAT | O_TRUNC,0644)) < 2) {
fprintf(stderr,"cannot open %s\n",out);
exit(-1);
}
}
else wfile=1;
if (getpar("len","d",&len)==0)
if (getpar("nt","d",&len)==0) fprintf(stderr,"len= missing\n");
getpar("planes","d",&planes);
getpar("esize","d",&esize);
if (getpar("vecs","d",&vecs)==0) mstpar("nx","d",&vecs);
getpar("p0","d",&p0);
getpar("v0","d",&v0);
getpar("e0","d",&e0);
getpar("dp","d",&dp);
getpar("dv","d",&dv);
getpar("de","d",&de);
if (getpar("np","d",&np)==0) np = (planes - p0) / dp;
if (getpar("nv","d",&nv)==0) nv = (vecs - v0) / dv;
if (getpar("ne","d",&ne)==0) ne = (len - e0) / de;
endpar();
fprintf(stderr," in=%s out=%s\n",in,out);
fprintf(stderr," planes=%d vecs=%d len=%d esize=%d\n",planes,vecs,len,esize);
fprintf(stderr," np=%d p0=%d dp=%d\n",np,p0,dp);
fprintf(stderr," nv=%d v0=%d dv=%d\n",nv,v0,dv);
fprintf(stderr," ne=%d e0=%d de=%d\n",ne,e0,de);
x = (char *) malloc(ne*de*esize);
lseek (rfile,((p0*vecs+v0)*len+e0)*esize,0);
nseek = ((dv - 1) * len + (len - ne * de)) * esize;
nseek1 = ((dp - 1) * vecs + (vecs - nv * dv)) * len * esize;
ne *= esize;
de1 = (de - 1) * esize;
while (np-->0) {
for (m=0; m<nv; m++) {
read (rfile,x,ne*de);
if (de>1) for (i=j=0; i<ne; j+=de1)
for (k=i+esize; i<k;) x[i++] = x[j++];
dowrite (wfile,x,ne);
lseek (rfile,nseek,1);
}
lseek (rfile,nseek1,1);
}
}
int
dowrite(fd,buf,bytes)
int fd, bytes;
char *buf;
{
int nwrite, total;
if ((total = write(fd,buf,bytes)) <= 0) return(total);
buf += total;
while (bytes > total) {
if ((nwrite = write(fd,buf,bytes-total)) <= 0) return(total);
total += nwrite;
buf += nwrite;
}
return(total);
}
|
the_stack_data/43888736.c
|
/*
Objective
This challenge will help you learn the concept of recursion.
A function that calls itself is known as a recursive function. The C programming language supports recursion. But while using recursion, one needs to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.
To prevent infinite recursion, if ... else statement (or similar approach) can be used where one branch makes the recursive call and other doesn't.
void recurse() {
.....
recurse() //recursive call
.....
}
int main() {
.....
recurse(); //function call
.....
}
Task
There is a series, S, where the next term is the sum of pervious three terms. Given the first three terms of the series, a, b, and c respectively, you have to output the nth term of the series using recursion.
Recursive method for calculating nth term is given below.
Input Format
* The first line contains a single integer, n.
* The next line contains 3 space-separated integers, a, b, and c.
Constraints
1 <= n <= 20
1 <= a, b, c <= 100
Output Format
Print the nth term of the series, S(n).
Sample Input 0
5
1 2 3
Sample Output 0
11
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int find_nth_term(int n, int a, int b, int c) {
if (n == 1) {
return a;
} else if (n == 2) {
return b;
} else if (n == 3) {
return c;
}
return find_nth_term(n - 1, a, b, c) + find_nth_term(n - 2, a, b, c) + find_nth_term(n - 3, a, b, c);
}
int main() {
int n, a, b, c;
scanf("%d %d %d %d", &n, &a, &b, &c);
int ans = find_nth_term(n, a, b, c);
printf("%d", ans);
return 0;
}
|
the_stack_data/5118.c
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <sys/user.h>
#ifdef PTRACE
#include <sys/ptrace.h>
#if __WORDSIZE == 64
#define REG(reg) reg.orig_rax
#else
#define REG(reg) reg.orig_eax
#endif
#endif
int main(int argc, char *argv[]) {
pid_t cpid;
int wstatus;
struct user_regs_struct regs;
cpid = fork();
if (cpid == -1) {
perror("failed to fork\n");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Code executed by child */
printf("child %d\n", cpid);
#ifdef PTRACE
ptrace(PTRACE_TRACEME, 0, 0, 0);
#endif
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
prctl(PR_SET_DUMPABLE, 0);
execl("/bin/date", "date", 0, NULL);
exit(EXIT_SUCCESS);
} else { /* Code executed by parent */
printf("parent %d\n", cpid);
do {
if (waitpid(cpid, &wstatus, WUNTRACED | WCONTINUED) == -1) {
exit(EXIT_FAILURE);
}
#ifdef PTRACE
ptrace(PTRACE_SETOPTIONS, cpid, 0, PTRACE_O_TRACESECCOMP);
ptrace(PTRACE_GETREGS, cpid, NULL, ®s);
fprintf(stderr, "syscall(%lld)\n", REG(regs));
ptrace(PTRACE_SYSCALL, cpid, NULL, NULL);
#endif
if (WIFEXITED(wstatus)) {
fprintf(stdout, "exited, status=%d\n", WEXITSTATUS(wstatus));
} else if (WIFSIGNALED(wstatus)) {
fprintf(stdout, "killed by signal %d\n", WTERMSIG(wstatus));
}
} while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus));
exit(EXIT_SUCCESS);
}
return 0;
}
|
the_stack_data/150139479.c
|
#include <ncurses.h>
WINDOW *create_newwin(int height, int width, int starty, int startx);
void destroy_win(WINDOW *local_win);
int main(int argc, char *argv[])
{ WINDOW *my_win;
int startx, starty, width, height;
int ch;
initscr(); /* Start curses mode */
cbreak(); /* Line buffering disabled, Pass on
* everty thing to me */
keypad(stdscr, TRUE); /* I need that nifty F1 */
height = 3;
width = 10;
starty = (LINES - height) / 2; /* Calculating for a center placement */
startx = (COLS - width) / 2; /* of the window */
printw("Press F1 to exit");
refresh();
my_win = create_newwin(height, width, starty, startx);
while((ch = getch()) != KEY_F(1))
{ switch(ch)
{ case KEY_LEFT:
destroy_win(my_win);
my_win = create_newwin(height, width, starty,--startx);
break;
case KEY_RIGHT:
destroy_win(my_win);
my_win = create_newwin(height, width, starty,++startx);
break;
case KEY_UP:
destroy_win(my_win);
my_win = create_newwin(height, width, --starty,startx);
break;
case KEY_DOWN:
destroy_win(my_win);
my_win = create_newwin(height, width, ++starty,startx);
break;
}
}
endwin(); /* End curses mode */
return 0;
}
WINDOW *create_newwin(int height, int width, int starty, int startx)
{ WINDOW *local_win;
local_win = newwin(height, width, starty, startx);
box(local_win, 0 , 0); /* 0, 0 gives default characters
* for the vertical and horizontal
* lines */
wrefresh(local_win); /* Show that box */
return local_win;
}
void destroy_win(WINDOW *local_win)
{
/* box(local_win, ' ', ' '); : This won't produce the desired
* result of erasing the window. It will leave it's four corners
* and so an ugly remnant of window.
*/
wborder(local_win, ' ', ' ', ' ',' ',' ',' ',' ',' ');
/* The parameters taken are
* 1. win: the window on which to operate
* 2. ls: character to be used for the left side of the window
* 3. rs: character to be used for the right side of the window
* 4. ts: character to be used for the top side of the window
* 5. bs: character to be used for the bottom side of the window
* 6. tl: character to be used for the top left corner of the window
* 7. tr: character to be used for the top right corner of the window
* 8. bl: character to be used for the bottom left corner of the window
* 9. br: character to be used for the bottom right corner of the window
*/
wrefresh(local_win);
delwin(local_win);
}
|
the_stack_data/423575.c
|
/*
* Abdullah Almarzouq ([email protected])
* 5/22/20
*
* testing: opens, reads and writes to "/sys/module/hw4/parameters/blink_rate"
* module parameter to view and modify the value of
* "blink_rate" in hw4 module. The program also opens "/dev/ece_led" first
* to start the timer.
*
* Note: the user must enter a new value, otherwise blink_rate=2.
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char *argv[]){
int size;
char *val; //to read current value of blink_rate
char *new_val; //new value to be assigned to blink_rate
new_val = (char*)malloc(10*sizeof(char));
if(argc<2){
new_val = "2"; //default value if user didn't enter a value
}
else{
if(atoi(argv[1])<=0){
free(new_val);
fprintf(stderr, "ERROR: Invalid Argument\n");
exit(-1);
}
else{
new_val = (argv[1]); //assigning new_val with a value entered by user
}
}
/*opening the kernel module node file /dev/ece_led */
int fd1 = open("/dev/ece_led", O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO );
/*if open failed*/
if(fd1<0){
perror("ERROR: ");
free(new_val);
exit(1);
}
int fd2 = open("/sys/module/hw4/parameters/blink_rate", O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO );
/*if open failed*/
if(fd2<0){
perror("ERROR: ");
close(fd1);
free(new_val);
exit(1);
}
val = (char*)malloc(10*sizeof(char));
/*reading parameter value*/
size = read(fd2,val,10); //current value of blink_rate
/*if reading fails*/
if(size<0){
perror("ERROR: ");
close(fd1);
close(fd2);
free(new_val);
free(val);
exit(1);
}
val[size-1]='\0';
/*print read value*/
printf("Current value of blink_rate: %s\n",val);
/*close parameter file*/
if(close(fd2)<0){
perror("ERROR: ");
close(fd1);
free(new_val);
free(val);
exit(1);
}
/*open parameter file again*/
fd2 = open("/sys/module/hw4/parameters/blink_rate", O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO );
/*if open fails*/
if((fd2)<0){
perror("ERROR: ");
close(fd1);
free(new_val);
free(val);
exit(1);
}
/*modify parameter blink_rate*/
size = write(fd2,new_val,10);
/*if writing fails*/
if(size<0){
perror("ERROR: ");
close(fd1);
close(fd2);
free(val);
free(new_val);
exit(1);
}
if(close(fd2)<0){
perror("ERROR: ");
free(val);
close(fd1);
free(new_val);
exit(1);
}
/*open parameter file again*/
fd2 = open("/sys/module/hw4/parameters/blink_rate", O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO );
/*if open fails*/
if((fd2)<0){
perror("ERROR: ");
close(fd1);
free(new_val);
free(val);
exit(1);
}
/*reading new value of parameter blink_rate*/
size = read(fd2,val,10);
val[size-1]='\0';
/*if reading fails*/
if(size<0){
perror("ERROR: ");
close(fd1);
close(fd2);
free(val);
free(new_val);
exit(1);
}
/*print new value*/
printf("New value of blink_rate: %s\n",val);
if(close(fd2)<0){
perror("ERROR: ");
free(val);
close(fd1);
free(new_val);
exit(1);
}
if(close(fd1)<0){
perror("ERROR: ");
free(val);
free(new_val);
exit(1);
}
free(val);
printf("file(s) closed\n");
return 0;
}
|
the_stack_data/85353.c
|
void selectionsort(int *arr, int n) {
int i, j, min, tmp;
for (i = 0; i < n-1; i++) {
min = i;
// Encontro o elemento mínimo em um vetor
for (j = i+1; j < n; j++)
if (arr[j] < arr[min])
min = j;
// Encontrado o valor minimo, realizo o swap de posições
tmp = arr[min];
arr[min] = arr[i];
arr[i] = tmp;
}
}
|
the_stack_data/165767738.c
|
#include <curses.h>
#include <stdio.h>
void open_about(void) {
clear();
refresh();
int c, row, col, x, y;
getmaxyx(stdscr, row, col);
init_pair(1, COLOR_GREEN, COLOR_BLACK);
init_pair(2, COLOR_MAGENTA, COLOR_BLACK);
WINDOW *about_win;
about_win = newwin(row, col, 0, 0);
box(about_win, 0, 0);
y = 1; x = col / 2 - 6;
WINDOW *box0_win;
box0_win = newwin(3, 11, y, x);
box(box0_win, 0, 0);
wbkgd(box0_win, COLOR_PAIR(2));
wattron(box0_win, A_BOLD | A_UNDERLINE | COLOR_PAIR(1));
mvwprintw(box0_win, 1, 3, "ABOUT");
wattroff(box0_win, A_BOLD | A_UNDERLINE | COLOR_PAIR(1));
wrefresh(about_win);
wrefresh(box0_win);
y = 7; x = col / 2 - 40;
mvwprintw(about_win, y, x, "Snake is a video game concept where the player maneuvers a line which grows in");
mvwprintw(about_win, ++y, x, "length when eating food, with the line itself being a primary obstacle.");
mvwprintw(about_win, y += 2, x, "The concept originated in the 1976 arcade game Blockade developed by Gremlin.");
mvwprintw(about_win, ++y, x, "Nowadays there are over hundreds of versions of this game.");
mvwprintw(about_win, y += 2, x, "This version of Snake game has been created as a homework assignment for");
mvwprintw(about_win, ++y, x, "the subject Programming Practicum 2 at the Faculty of Electrical Engineering.");
mvwprintw(about_win, y = 18, x = col - 40, "June 2018, Belgrade");
x = col - 30, y = row - 2;
mvwprintw(about_win, y, x, "Press ESC for menu page");
c = wgetch(about_win);
while (c != 27)
c = wgetch(about_win);
return;
}
|
the_stack_data/42153.c
|
/*
***************************************************************************
* Ralink Tech Inc.
* 4F, No. 2 Technology 5th Rd.
* Science-based Industrial Park
* Hsin-chu, Taiwan, R.O.C.
*
* (c) Copyright 2002-2006, Ralink Technology, Inc.
*
* All rights reserved. Ralink's source code is an unpublished work and the
* use of a copyright notice does not imply otherwise. This source code
* contains confidential trade secret material of Ralink Tech. Any attemp
* or participation in deciphering, decoding, reverse engineering or in any
* way altering the source code is stricitly prohibited, unless the prior
* written consent of Ralink Technology, Inc. is obtained.
***************************************************************************
Module Name:
apcli_ctrl.c
Abstract:
Revision History:
Who When What
-------- ---------- ----------------------------------------------
Fonchi 2006-06-23 modified for rt61-APClinent
*/
#ifdef APCLI_SUPPORT
#include "rt_config.h"
static VOID ApCliCtrlJoinReqAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlJoinReqTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlProbeRspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlAuthRspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlAuth2RspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlAuthReqTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlAuth2ReqTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlAssocRspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlDeAssocRspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlAssocReqTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlDisconnectReqAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlPeerDeAssocReqAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliCtrlDeAssocAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static
VOID ApCliCtrlDeAuthAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliWpaMicFailureReportFrame(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
#ifdef APCLI_CERT_SUPPORT
static VOID ApCliCtrlScanDoneAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
#endif /* APCLI_CERT_SUPPORT */
#ifdef APCLI_CONNECTION_TRIAL
static VOID ApCliCtrlTrialConnectAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliTrialConnectTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliTrialPhase2TimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliTrialConnectRetryTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM * Elem);
static VOID ApCliTrialConnectTimeout(
IN PVOID SystemSpecific1,
IN PVOID FunctionContext,
IN PVOID SystemSpecific2,
IN PVOID SystemSpecific3);
static VOID ApCliTrialConnectPhase2Timeout(
IN PVOID SystemSpecific1,
IN PVOID FunctionContext,
IN PVOID SystemSpecific2,
IN PVOID SystemSpecific3);
static VOID ApCliTrialConnectRetryTimeout(
IN PVOID SystemSpecific1,
IN PVOID FunctionContext,
IN PVOID SystemSpecific2,
IN PVOID SystemSpecific3);
DECLARE_TIMER_FUNCTION(ApCliTrialConnectTimeout);
BUILD_TIMER_FUNCTION(ApCliTrialConnectTimeout);
DECLARE_TIMER_FUNCTION(ApCliTrialConnectPhase2Timeout);
BUILD_TIMER_FUNCTION(ApCliTrialConnectPhase2Timeout);
DECLARE_TIMER_FUNCTION(ApCliTrialConnectRetryTimeout);
BUILD_TIMER_FUNCTION(ApCliTrialConnectRetryTimeout);
#endif /* APCLI_CONNECTION_TRIAL */
/*
==========================================================================
Description:
The apcli ctrl state machine,
Parameters:
Sm - pointer to the state machine
Note:
the state machine looks like the following
==========================================================================
*/
VOID ApCliCtrlStateMachineInit(
IN PRTMP_ADAPTER pAd,
IN STATE_MACHINE * Sm,
OUT STATE_MACHINE_FUNC Trans[])
{
UCHAR i;
#ifdef APCLI_CONNECTION_TRIAL
PAPCLI_STRUCT pApCliEntry;
#endif /* APCLI_CONNECTION_TRIAL */
StateMachineInit(Sm, (STATE_MACHINE_FUNC *)Trans,
APCLI_MAX_CTRL_STATE, APCLI_MAX_CTRL_MSG,
(STATE_MACHINE_FUNC)Drop, APCLI_CTRL_DISCONNECTED,
APCLI_CTRL_MACHINE_BASE);
/* disconnected state */
StateMachineSetAction(Sm, APCLI_CTRL_DISCONNECTED, APCLI_CTRL_JOIN_REQ, (STATE_MACHINE_FUNC)ApCliCtrlJoinReqAction);
/* probe state */
StateMachineSetAction(Sm, APCLI_CTRL_PROBE, APCLI_CTRL_PROBE_RSP, (STATE_MACHINE_FUNC)ApCliCtrlProbeRspAction);
StateMachineSetAction(Sm, APCLI_CTRL_PROBE, APCLI_CTRL_JOIN_REQ_TIMEOUT, (STATE_MACHINE_FUNC)ApCliCtrlJoinReqTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_PROBE, APCLI_CTRL_DISCONNECT_REQ, (STATE_MACHINE_FUNC)ApCliCtrlDisconnectReqAction);
/* auth state */
StateMachineSetAction(Sm, APCLI_CTRL_AUTH, APCLI_CTRL_AUTH_RSP, (STATE_MACHINE_FUNC)ApCliCtrlAuthRspAction);
StateMachineSetAction(Sm, APCLI_CTRL_AUTH, APCLI_CTRL_AUTH_REQ_TIMEOUT, (STATE_MACHINE_FUNC)ApCliCtrlAuthReqTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_AUTH, APCLI_CTRL_DISCONNECT_REQ, (STATE_MACHINE_FUNC)ApCliCtrlDisconnectReqAction);
StateMachineSetAction(Sm, APCLI_CTRL_AUTH, APCLI_CTRL_PEER_DISCONNECT_REQ, (STATE_MACHINE_FUNC)ApCliCtrlPeerDeAssocReqAction);
/* auth2 state */
StateMachineSetAction(Sm, APCLI_CTRL_AUTH_2, APCLI_CTRL_AUTH_RSP, (STATE_MACHINE_FUNC)ApCliCtrlAuth2RspAction);
StateMachineSetAction(Sm, APCLI_CTRL_AUTH_2, APCLI_CTRL_AUTH_REQ_TIMEOUT, (STATE_MACHINE_FUNC)ApCliCtrlAuth2ReqTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_AUTH_2, APCLI_CTRL_DISCONNECT_REQ, (STATE_MACHINE_FUNC)ApCliCtrlDisconnectReqAction);
StateMachineSetAction(Sm, APCLI_CTRL_AUTH_2, APCLI_CTRL_PEER_DISCONNECT_REQ, (STATE_MACHINE_FUNC)ApCliCtrlPeerDeAssocReqAction);
/* assoc state */
StateMachineSetAction(Sm, APCLI_CTRL_ASSOC, APCLI_CTRL_ASSOC_RSP, (STATE_MACHINE_FUNC)ApCliCtrlAssocRspAction);
StateMachineSetAction(Sm, APCLI_CTRL_ASSOC, APCLI_CTRL_ASSOC_REQ_TIMEOUT, (STATE_MACHINE_FUNC)ApCliCtrlAssocReqTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_ASSOC, APCLI_CTRL_DISCONNECT_REQ, (STATE_MACHINE_FUNC)ApCliCtrlDeAssocAction);
StateMachineSetAction(Sm, APCLI_CTRL_ASSOC, APCLI_CTRL_PEER_DISCONNECT_REQ, (STATE_MACHINE_FUNC)ApCliCtrlPeerDeAssocReqAction);
/* deassoc state */
StateMachineSetAction(Sm, APCLI_CTRL_DEASSOC, APCLI_CTRL_DEASSOC_RSP, (STATE_MACHINE_FUNC)ApCliCtrlDeAssocRspAction);
/* connected state */
StateMachineSetAction(Sm, APCLI_CTRL_CONNECTED, APCLI_CTRL_DISCONNECT_REQ, (STATE_MACHINE_FUNC)ApCliCtrlDeAuthAction);
StateMachineSetAction(Sm, APCLI_CTRL_CONNECTED, APCLI_CTRL_PEER_DISCONNECT_REQ, (STATE_MACHINE_FUNC)ApCliCtrlPeerDeAssocReqAction);
StateMachineSetAction(Sm, APCLI_CTRL_CONNECTED, APCLI_CTRL_MT2_AUTH_REQ, (STATE_MACHINE_FUNC)ApCliCtrlProbeRspAction);
StateMachineSetAction(Sm, APCLI_CTRL_CONNECTED, APCLI_MIC_FAILURE_REPORT_FRAME, (STATE_MACHINE_FUNC)ApCliWpaMicFailureReportFrame);
#ifdef APCLI_CERT_SUPPORT
StateMachineSetAction(Sm, APCLI_CTRL_CONNECTED, APCLI_CTRL_SCAN_DONE, (STATE_MACHINE_FUNC)ApCliCtrlScanDoneAction);
#endif /* APCLI_CERT_SUPPORT */
#ifdef APCLI_CONNECTION_TRIAL
StateMachineSetAction(Sm, APCLI_CTRL_CONNECTED, APCLI_CTRL_TRIAL_CONNECT, (STATE_MACHINE_FUNC)ApCliCtrlTrialConnectAction);
StateMachineSetAction(Sm, APCLI_CTRL_DISCONNECTED, APCLI_CTRL_TRIAL_CONNECT, (STATE_MACHINE_FUNC)ApCliCtrlTrialConnectAction);
StateMachineSetAction(Sm, APCLI_CTRL_TRIAL_TRIGGERED, APCLI_CTRL_JOIN_REQ_TIMEOUT, (STATE_MACHINE_FUNC)ApCliCtrlTrialConnectAction);/* for retry */
/* Trial Connect Timer Timeout handling */
StateMachineSetAction(Sm, APCLI_CTRL_PROBE, APCLI_CTRL_TRIAL_CONNECT_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialConnectTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_AUTH, APCLI_CTRL_TRIAL_CONNECT_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialConnectTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_ASSOC, APCLI_CTRL_TRIAL_CONNECT_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialConnectTimeoutAction);
/* Trial Phase2 Timer Timeout handling */
StateMachineSetAction(Sm, APCLI_CTRL_PROBE, APCLI_CTRL_TRIAL_PHASE2_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialPhase2TimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_AUTH, APCLI_CTRL_TRIAL_PHASE2_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialPhase2TimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_ASSOC, APCLI_CTRL_TRIAL_PHASE2_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialPhase2TimeoutAction);
/* Trial Retry Timer Timeout handling */
StateMachineSetAction(Sm, APCLI_CTRL_PROBE, APCLI_CTRL_TRIAL_RETRY_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialConnectRetryTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_AUTH, APCLI_CTRL_TRIAL_RETRY_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialConnectRetryTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_ASSOC, APCLI_CTRL_TRIAL_RETRY_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialConnectRetryTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_CONNECTED, APCLI_CTRL_TRIAL_RETRY_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialConnectRetryTimeoutAction);
StateMachineSetAction(Sm, APCLI_CTRL_DISCONNECTED, APCLI_CTRL_TRIAL_RETRY_TIMEOUT, (STATE_MACHINE_FUNC)ApCliTrialConnectRetryTimeoutAction);
#endif /* APCLI_CONNECTION_TRIAL */
for (i = 0; i < MAX_APCLI_NUM; i++) {
pAd->ApCfg.ApCliTab[i].CtrlCurrState = APCLI_CTRL_DISCONNECTED;
pAd->ApCfg.ApCliTab[i].LinkDownReason = APCLI_LINKDOWN_NONE;
pAd->ApCfg.ApCliTab[i].Disconnect_Sub_Reason = APCLI_DISCONNECT_SUB_REASON_NONE;
#ifdef APCLI_CONNECTION_TRIAL
pApCliEntry = &pAd->ApCfg.ApCliTab[i];
/* timer init */
RTMPInitTimer(pAd,
&pApCliEntry->TrialConnectTimer,
GET_TIMER_FUNCTION(ApCliTrialConnectTimeout),
(PVOID)pApCliEntry,
FALSE);
RTMPInitTimer(pAd,
&pApCliEntry->TrialConnectPhase2Timer,
GET_TIMER_FUNCTION(ApCliTrialConnectPhase2Timeout),
(PVOID)pApCliEntry,
FALSE);
RTMPInitTimer(pAd,
&pApCliEntry->TrialConnectRetryTimer,
GET_TIMER_FUNCTION(ApCliTrialConnectRetryTimeout),
pApCliEntry,
FALSE);
#endif /* APCLI_CONNECTION_TRIAL */
}
}
#ifdef FAST_EAPOL_WAR
static VOID ApCliCtrlDeleteMacEntry(
IN PRTMP_ADAPTER pAd,
IN UCHAR ifIndex,
IN UCHAR CliIdx)
{
PAPCLI_STRUCT pApCliEntry = NULL;
#ifdef MAC_REPEATER_SUPPORT
PREPEATER_CLIENT_ENTRY pReptEntry = NULL;
if (CliIdx != 0xff) {
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
} else
#endif
{
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
}
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF) {
if ((pReptEntry->pre_entry_alloc == TRUE) &&
(pReptEntry->CliValid == FALSE)) {
UCHAR MacTabWCID;
MacTabWCID = pReptEntry->MacTabWCID;
MacTableDeleteEntry(pAd, MacTabWCID, pAd->MacTab.Content[MacTabWCID].Addr);
pReptEntry->MacTabWCID = 0xFF;
pReptEntry->pre_entry_alloc = FALSE;
}
} else
#endif
{
if ((pApCliEntry->pre_entry_alloc == TRUE) &&
(pApCliEntry->Valid == FALSE)) {
UCHAR MacTabWCID;
MacTabWCID = pApCliEntry->MacTabWCID;
MacTableDeleteEntry(pAd, MacTabWCID, APCLI_ROOT_BSSID_GET(pAd, MacTabWCID));
pApCliEntry->MacTabWCID = 0;
pApCliEntry->pre_entry_alloc = FALSE;
}
}
}
#endif /* FAST_EAPOL_WAR */
#ifdef APCLI_CONNECTION_TRIAL
static VOID ApCliTrialConnectTimeout(
IN PVOID SystemSpecific1,
IN PVOID FunctionContext,
IN PVOID SystemSpecific2,
IN PVOID SystemSpecific3)
{
PAPCLI_STRUCT pApCliEntry = (APCLI_STRUCT *)FunctionContext;
RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)pApCliEntry->pAd;
UCHAR ifIndex = pApCliEntry->ifIndex;
MlmeEnqueue(pAd, APCLI_CTRL_STATE_MACHINE, APCLI_CTRL_TRIAL_CONNECT_TIMEOUT, 0, NULL, ifIndex);
RTMP_MLME_HANDLER(pAd);
}
static VOID ApCliTrialConnectPhase2Timeout(
IN PVOID SystemSpecific1,
IN PVOID FunctionContext,
IN PVOID SystemSpecific2,
IN PVOID SystemSpecific3)
{
PAPCLI_STRUCT pApCliEntry = (APCLI_STRUCT *)FunctionContext;
RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)pApCliEntry->pAd;
UCHAR ifIndex = pApCliEntry->ifIndex;
MlmeEnqueue(pAd, APCLI_CTRL_STATE_MACHINE, APCLI_CTRL_TRIAL_PHASE2_TIMEOUT, 0, NULL, ifIndex);
RTMP_MLME_HANDLER(pAd);
}
static VOID ApCliTrialConnectRetryTimeout(
IN PVOID SystemSpecific1,
IN PVOID FunctionContext,
IN PVOID SystemSpecific2,
IN PVOID SystemSpecific3)
{
PAPCLI_STRUCT pApCliEntry = (APCLI_STRUCT *)FunctionContext;
RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)pApCliEntry->pAd;
UCHAR ifIndex = pApCliEntry->ifIndex;
MlmeEnqueue(pAd, APCLI_CTRL_STATE_MACHINE, APCLI_CTRL_TRIAL_RETRY_TIMEOUT, 0, NULL, ifIndex);
RTMP_MLME_HANDLER(pAd);
}
static VOID ApCliTrialConnectionBeaconControl(PRTMP_ADAPTER pAd, BOOLEAN start)
{
struct wifi_dev *wdev;
INT IdBss;
INT MaxNumBss;
MaxNumBss = pAd->ApCfg.BssidNum;
for (IdBss = 0; IdBss < MaxNumBss; IdBss++) {
wdev = &pAd->ApCfg.MBSSID[IdBss].wdev;
if (WDEV_BSS_STATE(wdev) == BSS_READY) {
UpdateBeaconHandler(
pAd,
wdev,
(start) ? BCN_UPDATE_ENABLE_TX : BCN_UPDATE_DISABLE_TX);
}
}
}
static VOID ApCliTrialConnectTimeoutAction(PRTMP_ADAPTER pAd, MLME_QUEUE_ELEM *pElem)
{
PAPCLI_STRUCT pApCliEntry;
UCHAR ifIndex;
PULONG pCurrState;
UCHAR ch;
struct freq_oper oper;
ifIndex = pElem->Priv;
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
pCurrState = &pApCliEntry->CtrlCurrState;
/*query physical radio setting by wdev*/
hc_radio_query_by_wdev(&pApCliEntry->wdev, &oper);
ch = oper.prim_ch;
if (pApCliEntry->TrialCh != ch) {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR,
("%s[%d]Change ch %d to %d(%d)\n\r",
__func__, __LINE__,
pApCliEntry->TrialCh, pApCliEntry->wdev.channel, ch));
pApCliEntry->wdev.channel = ch;
wlan_operate_set_prim_ch(&pApCliEntry->wdev, ch);
/* TBD regenerate beacon? */
ApCliTrialConnectionBeaconControl(pAd, TRUE);
}
if (*pCurrState == APCLI_CTRL_ASSOC) {
/* trialConnectTimeout, and currect status is ASSOC, */
/* it means we got Auth Resp from new root AP already, */
/* we shall serve the origin channel traffic first, */
/* and jump back to trial channel to issue Assoc Req later, */
/* and finish four way-handshake if need. */
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("%s, ApCliTrialConnectTimeout APCLI_CTRL_ASSOC set TrialConnectPhase2Timer\n", __func__));
RTMPSetTimer(&(pApCliEntry->TrialConnectPhase2Timer), TRIAL_TIMEOUT);
} else {
/* RTMPCancelTimer(&(pApCliEntry->ApCliMlmeAux.ProbeTimer), &Cancelled); */
pApCliEntry->NewRootApRetryCnt++;
if (pApCliEntry->NewRootApRetryCnt >= 10) {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("%s, RetryCnt:%d, pCurrState = %lu,\n", __func__, pApCliEntry->NewRootApRetryCnt, *pCurrState));
pApCliEntry->TrialCh = 0;
MlmeEnqueue(pAd, APCLI_CTRL_STATE_MACHINE, APCLI_CTRL_DISCONNECT_REQ, 0, NULL, ifIndex);
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].CfgSsid, MAX_LEN_OF_SSID);/* cleanup CfgSsid. */
pApCliEntry->CfgSsidLen = 0;
pApCliEntry->NewRootApRetryCnt = 0;/* cleanup retry count */
pApCliEntry->Enable = FALSE;
} else {
/* trial connection probe fail */
/* change apcli sync state machine to idle state to reset sync state machine */
PULONG pSync_CurrState = &pAd->ApCfg.ApCliTab[ifIndex].SyncCurrState;
*pSync_CurrState = APCLI_SYNC_IDLE;
*pCurrState = APCLI_CTRL_DISCONNECTED;/* Disconnected State will bring the next probe req, auth req. */
}
}
}
static VOID ApCliTrialPhase2TimeoutAction(PRTMP_ADAPTER pAd, MLME_QUEUE_ELEM *pElem)
{
PAPCLI_STRUCT pApCliEntry;
MLME_ASSOC_REQ_STRUCT AssocReq;
UCHAR ifIndex;
struct wifi_dev *wdev;
struct freq_oper oper;
ifIndex = pElem->Priv;
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
wdev = &pApCliEntry->wdev;
/*query physical radio setting by wdev*/
hc_radio_query_by_wdev(wdev, &oper);
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("ApCli_SYNC - %s,\nJump back to trial channel:%d\nto issue Assoc Req to new root AP\n",
__func__, pApCliEntry->TrialCh));
if (pApCliEntry->TrialCh != oper.prim_ch) {
/* TBD disable beacon? */
ApCliTrialConnectionBeaconControl(pAd, FALSE);
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR,
("%s[%d]Change ch %d to %d\n\r",
__func__, __LINE__,
wdev->channel, pApCliEntry->TrialCh));
/* switch channel to trial channel */
wlan_operate_scan(wdev, pApCliEntry->TrialCh);
}
ApCliLinkDown(pAd, ifIndex);
/* if (wdev->AuthMode >= Ndis802_11AuthModeWPA) */
if (IS_AKM_WPA_CAPABILITY(wdev->SecConfig.AKMMap)) {
RTMPSetTimer(&(pApCliEntry->TrialConnectRetryTimer), (800 + pApCliEntry->NewRootApRetryCnt*200));
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("(%s) set TrialConnectRetryTimer(%d ms)\n", __func__, (800 + pApCliEntry->NewRootApRetryCnt*200)));
} else {
RTMPSetTimer(&(pApCliEntry->TrialConnectRetryTimer), TRIAL_TIMEOUT);
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("(%s) set TrialConnectRetryTimer(%d ms)\n", __func__, TRIAL_TIMEOUT));
}
AssocParmFill(pAd, &AssocReq, pAd->ApCfg.ApCliTab[pApCliEntry->ifIndex].MlmeAux.Bssid, pAd->ApCfg.ApCliTab[pApCliEntry->ifIndex].MlmeAux.CapabilityInfo,
ASSOC_TIMEOUT, 5);
MlmeEnqueue(pAd, APCLI_ASSOC_STATE_MACHINE, APCLI_MT2_MLME_ASSOC_REQ,
sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq, pApCliEntry->ifIndex);
RTMP_MLME_HANDLER(pAd);
}
static VOID ApCliTrialConnectRetryTimeoutAction(PRTMP_ADAPTER pAd, MLME_QUEUE_ELEM *pElem)
{
PAPCLI_STRUCT pApCliEntry;
PULONG pCurrState;
UCHAR ifIndex;
UCHAR ch;
PMAC_TABLE_ENTRY pMacEntry;
STA_TR_ENTRY *tr_entry;
struct freq_oper oper;
/* PMAC_TABLE_ENTRY pOldRootAp = &pApCliEntry->oldRootAP; */
ifIndex = pElem->Priv;
pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
pMacEntry = MacTableLookup(pAd, pApCliEntry->MlmeAux.Bssid);
/*query physical radio setting by wdev*/
hc_radio_query_by_wdev(&pApCliEntry->wdev, &oper);
if (pMacEntry == NULL) {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("ApCli_SYNC - %s, no CfgApCliBssid in mactable!\n", __func__));
/* *pCurrState = APCLI_CTRL_DISCONNECTED; */
pApCliEntry->NewRootApRetryCnt++;
if (pApCliEntry->NewRootApRetryCnt >= 10) {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("%s, RetryCnt:%d, pCurrState = %lu,\n", __func__, pApCliEntry->NewRootApRetryCnt, *pCurrState));
pApCliEntry->TrialCh = 0;
ApCliLinkDown(pAd, ifIndex);
MlmeEnqueue(pAd, APCLI_CTRL_STATE_MACHINE, APCLI_CTRL_DISCONNECT_REQ, 0, NULL, ifIndex);
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].CfgSsid, MAX_LEN_OF_SSID);/* cleanup CfgSsid. */
pApCliEntry->CfgSsidLen = 0;
pApCliEntry->NewRootApRetryCnt = 0;/* cleanup retry count */
pApCliEntry->Enable = FALSE;
}
if (pApCliEntry->TrialCh != oper.prim_ch) {
ch = oper.prim_ch;
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR,
("%s[%d]Change ch %d to %d(%d)\n\r",
__func__, __LINE__,
pApCliEntry->TrialCh, pApCliEntry->wdev.channel, ch));
/* switch channel to orignal channel */
pApCliEntry->wdev.channel = ch;
wlan_operate_set_prim_ch(&pApCliEntry->wdev, ch);
/* TBD enable beacon? */
ApCliTrialConnectionBeaconControl(pAd, TRUE);
}
*pCurrState = APCLI_CTRL_DISCONNECTED;
return;
}
tr_entry = &pAd->MacTab.tr_entry[pMacEntry->wcid];
if ((tr_entry->PortSecured == WPA_802_1X_PORT_SECURED) && (*pCurrState == APCLI_CTRL_CONNECTED)) {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("ApCli_SYNC - %s, new rootAP connected!!\n", __func__));
/* connected to new ap ok, change common channel to new channel */
/* AsicSetApCliBssid(pAd, pApCliEntry->ApCliMlmeAux.Bssid, 1); */
/* MacTableDeleteEntry(pAd, pApCliEntry->MacTabWCID, APCLI_ROOT_BSSID_GET(pAd, pApCliEntry->MacTabWCID)); */
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("ApCli_SYNC - %s, jump back to origin channel to wait for User's operation!\n", __func__));
if (pApCliEntry->TrialCh != oper.prim_ch) {
ch = oper.prim_ch;
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR,
("%s[%d]Change ch %d to %d(%d)\n\r",
__func__, __LINE__,
pApCliEntry->TrialCh, pApCliEntry->wdev.channel, ch));
/* switch channel to orignal channel */
pApCliEntry->wdev.channel = ch;
wlan_operate_set_prim_ch(&pApCliEntry->wdev, ch);
/* TBD enable beacon? */
ApCliTrialConnectionBeaconControl(pAd, TRUE);
}
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].CfgSsid, MAX_LEN_OF_SSID);/* cleanup CfgSsid. */
pApCliEntry->CfgSsidLen = 0;
pApCliEntry->NewRootApRetryCnt = 0;/* cleanup retry count */
/* pApCliEntry->Enable = FALSE; */
/* sprintf(tempBuf, "%d", pApCliEntry->TrialCh); */
/* MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("Follow new rootAP Switch to channel :%s\n", tempBuf)); */
/* Set_Channel_Proc(pAd, tempBuf);//APStartUp will regenerate beacon. */
pApCliEntry->TrialCh = 0;
} else {
/*
Apcli does not connect to new root ap successfully yet,
jump back to origin channel to serve old rootap traffic.
re-issue assoc_req to go later.
*/
/* pApCliEntry->MacTabWCID = pOldRootAp->Aid; */
pApCliEntry->NewRootApRetryCnt++;
if (pApCliEntry->NewRootApRetryCnt < 10) {
if ((tr_entry->PortSecured != WPA_802_1X_PORT_SECURED) && (*pCurrState == APCLI_CTRL_CONNECTED))
; /* *pCurrState = APCLI_CTRL_DISCONNECTED; */
else
RTMPSetTimer(&(pApCliEntry->TrialConnectPhase2Timer), TRIAL_TIMEOUT);
} else {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("%s, RetryCnt:%d, pCurrState = %lu,\n", __func__, pApCliEntry->NewRootApRetryCnt, *pCurrState));
pApCliEntry->TrialCh = 0;
MlmeEnqueue(pAd, APCLI_CTRL_STATE_MACHINE, APCLI_CTRL_DISCONNECT_REQ, 0, NULL, ifIndex);
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].CfgSsid, MAX_LEN_OF_SSID);/* cleanup CfgSsid. */
pApCliEntry->CfgSsidLen = 0;
pApCliEntry->NewRootApRetryCnt = 0;/* cleanup retry count */
pApCliEntry->Enable = FALSE;
ApCliLinkDown(pAd, ifIndex);
}
if (pApCliEntry->TrialCh != oper.prim_ch) {
ch = oper.prim_ch;
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR,
("%s[%d]Change ch %d to %d(%d)\n\r",
__func__, __LINE__,
pApCliEntry->TrialCh, pApCliEntry->wdev.channel, ch));
/* switch channel to orignal channel */
pApCliEntry->wdev.channel = ch;
wlan_operate_set_prim_ch(&pApCliEntry->wdev, ch);
/* TBD enable beacon? */
ApCliTrialConnectionBeaconControl(pAd, TRUE);
}
if ((tr_entry->PortSecured != WPA_802_1X_PORT_SECURED) && (*pCurrState == APCLI_CTRL_CONNECTED))
*pCurrState = APCLI_CTRL_DISCONNECTED;
}
}
#endif /* APCLI_CONNECTION_TRIAL */
/*
==========================================================================
Description:
APCLI MLME JOIN req state machine procedure
==========================================================================
*/
static VOID ApCliCtrlJoinReqAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
APCLI_MLME_JOIN_REQ_STRUCT JoinReq;
PAPCLI_STRUCT pApCliEntry;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
#ifdef WSC_AP_SUPPORT
PWSC_CTRL pWpsCtrl = &pAd->ApCfg.ApCliTab[ifIndex].wdev.WscControl;
#endif /* WSC_AP_SUPPORT */
struct wifi_dev *wdev = NULL;
PULONG pLinkDownReason = &pAd->ApCfg.ApCliTab[ifIndex].LinkDownReason;
wdev = &pAd->ApCfg.ApCliTab[ifIndex].wdev;
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Start Probe Req.\n", __func__));
if (ifIndex >= MAX_APCLI_NUM)
return;
if (ApScanRunning(pAd, wdev) == TRUE)
return;
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
NdisZeroMemory(&JoinReq, sizeof(APCLI_MLME_JOIN_REQ_STRUCT));
#ifdef APCLI_OWE_SUPPORT
if (IS_AKM_OWE(wdev->SecConfig.AKMMap))
BssTableInit(&pApCliEntry->MlmeAux.owe_bss_tab);
#endif
if (!MAC_ADDR_EQUAL(pApCliEntry->CfgApCliBssid, ZERO_MAC_ADDR))
COPY_MAC_ADDR(JoinReq.Bssid, pApCliEntry->CfgApCliBssid);
#ifdef WSC_AP_SUPPORT
if ((pWpsCtrl->WscConfMode != WSC_DISABLE) &&
(pWpsCtrl->bWscTrigger == TRUE)) {
ULONG bss_idx = 0;
NdisZeroMemory(JoinReq.Ssid, MAX_LEN_OF_SSID);
JoinReq.SsidLen = pWpsCtrl->WscSsid.SsidLength;
NdisMoveMemory(JoinReq.Ssid, pWpsCtrl->WscSsid.Ssid, JoinReq.SsidLen);
if (pWpsCtrl->WscMode == 1) { /* PIN */
INT old_conf_mode = pWpsCtrl->WscConfMode;
UCHAR channel = wdev->channel, RootApChannel;
#ifdef AP_SCAN_SUPPORT
if ((pWpsCtrl->WscApCliScanMode == TRIGGER_PARTIAL_SCAN) &&
pAd->ScanCtrl.PartialScan.bScanning &&
pAd->ScanCtrl.PartialScan.LastScanChannel != 0)
return;
#endif /* AP_SCAN_SUPPORT */
bss_idx = BssSsidTableSearchBySSID(&pAd->ScanTab, (PUCHAR)(JoinReq.Ssid), JoinReq.SsidLen);
if (bss_idx == BSS_NOT_FOUND) {
#ifdef AP_SCAN_SUPPORT
if (pWpsCtrl->WscApCliScanMode == TRIGGER_PARTIAL_SCAN) {
if (!pAd->ScanCtrl.PartialScan.bScanning &&
(pAd->ScanCtrl.PartialScan.LastScanChannel == 0)) {
pAd->ScanCtrl.PartialScan.pwdev = wdev;
pAd->ScanCtrl.PartialScan.bScanning = TRUE;
}
}
#endif /* AP_SCAN_SUPPORT */
ApSiteSurvey_by_wdev(pAd, NULL, SCAN_WSC_ACTIVE, FALSE, wdev);
return;
}
RootApChannel = pAd->ScanTab.BssEntry[bss_idx].Channel;
if (RootApChannel != channel) {
rtmp_set_channel(pAd, wdev, RootApChannel);
wdev->channel = RootApChannel;
/*
ApStop will call WscStop, we need to reset WscConfMode, WscMode & bWscTrigger here.
*/
pWpsCtrl->WscState = WSC_STATE_START;
pWpsCtrl->WscStatus = STATUS_WSC_START_ASSOC;
pWpsCtrl->WscMode = 1;
pWpsCtrl->WscConfMode = old_conf_mode;
pWpsCtrl->bWscTrigger = TRUE;
return;
}
}
} else
#endif /* WSC_AP_SUPPORT */
{
#ifdef APCLI_OWE_SUPPORT
/*owe_trans_ssid present then update join request with OWE ssid, bssid parameters */
if (pApCliEntry->owe_trans_ssid_len > 0) {
NdisMoveMemory(&(JoinReq.Ssid), pApCliEntry->owe_trans_ssid, pApCliEntry->owe_trans_ssid_len);
COPY_MAC_ADDR(JoinReq.Bssid, pApCliEntry->owe_trans_bssid);
} else
#endif
if (pApCliEntry->CfgSsidLen != 0) {
#if defined(RT_CFG80211_P2P_CONCURRENT_DEVICE) || defined(CFG80211_MULTI_STA) || defined(APCLI_CFG80211_SUPPORT)
ULONG bss_idx = BSS_NOT_FOUND;
bss_idx = BssSsidTableSearchBySSID(&pAd->ScanTab, (PCHAR)pApCliEntry->CfgSsid, pApCliEntry->CfgSsidLen);
if (bss_idx == BSS_NOT_FOUND) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("%s:: can't find SSID[%s] in ScanTab.\n", __func__, pApCliEntry->CfgSsid));
*pCurrState = APCLI_CTRL_PROBE;
CFG80211_checkScanTable(pAd);
RT_CFG80211_P2P_CLI_CONN_RESULT_INFORM(pAd, JoinReq.Bssid, NULL, 0, NULL, 0, 0);
return;
}
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("%s:: find SSID[%ld][%s] channel[%d-%d] in ScanTab.\n", __func__,
bss_idx, pApCliEntry->CfgSsid, pAd->ScanTab.BssEntry[bss_idx].Channel,
pAd->ScanTab.BssEntry[bss_idx].CentralChannel));
/* TODO */
/* BssSearch Table has found the pEntry, send Prob Req. directly */
/* if (wdev->channel != pAd->ScanTab.BssEntry[bss_idx].Channel) */
{
pApCliEntry->MlmeAux.Channel = pAd->ScanTab.BssEntry[bss_idx].Channel;
pApCliEntry->wdev.channel = pApCliEntry->MlmeAux.Channel;
#ifdef CONFIG_MULTI_CHANNEL
/* should be check and update in in asso to check ==> ApCliCheckHt() */
pApCliEntry->wdev.channel = pApCliEntry->MlmeAux.Channel;
wlan_operate_set_ht_bw(wdev, HT_BW_20, EXTCHA_NONE);
#endif /* CONFIG_MULTI_CHANNEL */
wlan_operate_set_prim_ch(&pApCliEntry->wdev, pApCliEntry->wdev.channel);
}
#endif /* RT_CFG80211_P2P_CONCURRENT_DEVICE || CFG80211_MULTI_STA */
JoinReq.SsidLen = pApCliEntry->CfgSsidLen;
NdisMoveMemory(&(JoinReq.Ssid), pApCliEntry->CfgSsid, JoinReq.SsidLen);
}
}
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Probe Ssid=%s, Bssid=%02x:%02x:%02x:%02x:%02x:%02x\n",
__func__, JoinReq.Ssid, PRINT_MAC(JoinReq.Bssid)));
*pCurrState = APCLI_CTRL_PROBE;
*pLinkDownReason = APCLI_LINKDOWN_NONE;
MlmeEnqueue(pAd, APCLI_SYNC_STATE_MACHINE, APCLI_MT2_MLME_PROBE_REQ,
sizeof(APCLI_MLME_JOIN_REQ_STRUCT), &JoinReq, ifIndex);
}
/*
==========================================================================
Description:
APCLI MLME JOIN req timeout state machine procedure
==========================================================================
*/
static VOID ApCliCtrlJoinReqTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
APCLI_MLME_JOIN_REQ_STRUCT JoinReq;
PAPCLI_STRUCT pApCliEntry = NULL;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
USHORT apcli_ifIndex = (USHORT)(Elem->Priv);
#endif
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Probe Req Timeout.\n", __func__));
if (ifIndex >= MAX_APCLI_NUM)
return;
if (ApScanRunning(pAd, &pAd->ApCfg.ApCliTab[ifIndex].wdev) == TRUE) {
*pCurrState = APCLI_CTRL_DISCONNECTED;
return;
}
#ifdef APCLI_AUTO_CONNECT_SUPPORT
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
pApCliEntry->ProbeReqCnt++;
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Probe Req Timeout. ProbeReqCnt=%d\n",
__func__, pApCliEntry->ProbeReqCnt));
if (pApCliEntry->ProbeReqCnt > 7) {
/*
if exceed the APCLI_MAX_PROBE_RETRY_NUM (7),
switch to try next candidate AP.
*/
*pCurrState = APCLI_CTRL_DISCONNECTED;
NdisZeroMemory(pApCliEntry->MlmeAux.Bssid, MAC_ADDR_LEN);
NdisZeroMemory(pApCliEntry->MlmeAux.Ssid, MAX_LEN_OF_SSID);
pApCliEntry->ProbeReqCnt = 0;
#ifdef APCLI_OWE_SUPPORT
apcli_reset_owe_parameters(pAd, ifIndex);
#endif
/* Driver Trigger New Scan Mode for Sigma DUT usage */
if ((pAd->ApCfg.ApCliAutoConnectType[apcli_ifIndex] == TRIGGER_SCAN_BY_DRIVER
#ifdef FOLLOW_HIDDEN_SSID_FEATURE
|| (pAd->ApCfg.ApCliAutoConnectType[apcli_ifIndex] == TRIGGER_SCAN_BY_USER
&& pAd->ApCfg.ApCliTab[ifIndex].AutoConnectFlag == TRUE)
#endif
) && pAd->ScanCtrl.PartialScan.bScanning == FALSE
) {
if (pApCliEntry->CfgSsidLen) {
NDIS_802_11_SSID Ssid;
NdisCopyMemory(Ssid.Ssid, &pApCliEntry->CfgSsid, pApCliEntry->CfgSsidLen);
Ssid.SsidLength = pApCliEntry->CfgSsidLen;
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].CfgApCliBssid, MAC_ADDR_LEN);
pAd->ApCfg.ApCliAutoConnectRunning[apcli_ifIndex] = TRUE;
pAd->ApCfg.ApCliAutoBWAdjustCnt[apcli_ifIndex] = 0;
ApSiteSurvey_by_wdev(pAd, &Ssid, SCAN_ACTIVE, FALSE, &pApCliEntry->wdev);
return;
}
}
if (pAd->ApCfg.ApCliAutoConnectRunning[apcli_ifIndex] == TRUE &&
(pAd->ApCfg.ApCliAutoConnectType[apcli_ifIndex] != TRIGGER_SCAN_BY_DRIVER))
ApCliSwitchCandidateAP(pAd, &pApCliEntry->wdev);
return;
}
#else
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
/* stay in same state. */
*pCurrState = APCLI_CTRL_PROBE;
/* continue Probe Req. */
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Send Probe Req.\n", __func__));
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
NdisZeroMemory(&JoinReq, sizeof(APCLI_MLME_JOIN_REQ_STRUCT));
if (!MAC_ADDR_EQUAL(pApCliEntry->CfgApCliBssid, ZERO_MAC_ADDR))
COPY_MAC_ADDR(JoinReq.Bssid, pApCliEntry->CfgApCliBssid);
#ifdef WSC_AP_SUPPORT
if ((pAd->ApCfg.ApCliTab[ifIndex].wdev.WscControl.WscConfMode != WSC_DISABLE) &&
(pAd->ApCfg.ApCliTab[ifIndex].wdev.WscControl.bWscTrigger == TRUE)) {
NdisZeroMemory(JoinReq.Ssid, MAX_LEN_OF_SSID);
JoinReq.SsidLen = pAd->ApCfg.ApCliTab[ifIndex].wdev.WscControl.WscSsid.SsidLength;
NdisMoveMemory(JoinReq.Ssid, pAd->ApCfg.ApCliTab[ifIndex].wdev.WscControl.WscSsid.Ssid, JoinReq.SsidLen);
} else
#endif /* WSC_AP_SUPPORT */
{
#ifdef APCLI_OWE_SUPPORT
/*Configure OWE ssid and bssid Join request parameters */
if (IS_AKM_OWE(pApCliEntry->wdev.SecConfig.AKMMap) && (pApCliEntry->owe_trans_ssid_len != 0)) {
JoinReq.SsidLen = pApCliEntry->owe_trans_ssid_len;
NdisMoveMemory(&(JoinReq.Ssid), pApCliEntry->owe_trans_ssid, JoinReq.SsidLen);
COPY_MAC_ADDR(JoinReq.Bssid, pApCliEntry->owe_trans_bssid);
} else
#endif
if (pApCliEntry->CfgSsidLen != 0) {
JoinReq.SsidLen = pApCliEntry->CfgSsidLen;
NdisMoveMemory(&(JoinReq.Ssid), pApCliEntry->CfgSsid, JoinReq.SsidLen);
}
}
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Probe Ssid=%s, Bssid=%02x:%02x:%02x:%02x:%02x:%02x\n",
__func__, JoinReq.Ssid, JoinReq.Bssid[0], JoinReq.Bssid[1], JoinReq.Bssid[2],
JoinReq.Bssid[3], JoinReq.Bssid[4], JoinReq.Bssid[5]));
MlmeEnqueue(pAd, APCLI_SYNC_STATE_MACHINE, APCLI_MT2_MLME_PROBE_REQ,
sizeof(APCLI_MLME_JOIN_REQ_STRUCT), &JoinReq, ifIndex);
return;
}
/*
==========================================================================
Description:
APCLI MLME Probe Rsp state machine procedure
==========================================================================
*/
static VOID ApCliCtrlProbeRspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
APCLI_CTRL_MSG_STRUCT *Info = (APCLI_CTRL_MSG_STRUCT *)(Elem->Msg);
USHORT Status = Info->Status;
PAPCLI_STRUCT pApCliEntry;
MLME_AUTH_REQ_STRUCT AuthReq;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
struct wifi_dev *wdev;
#ifdef MAC_REPEATER_SUPPORT
UCHAR CliIdx = 0xFF;
REPEATER_CLIENT_ENTRY *pReptCliEntry = NULL;
#endif /* MAC_REPEATER_SUPPORT */
#ifdef APCLI_AUTO_CONNECT_SUPPORT
USHORT apcli_ifIndex = (USHORT)(Elem->Priv);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
struct _SECURITY_CONFIG *pProfile_SecConfig = NULL;
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
) {
MTWF_LOG(DBG_CAT_CLIENT, DBG_SUBCAT_ALL, DBG_LVL_OFF,
("%s, wrong ifIndex:%d\n", __func__, ifIndex));
return;
}
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptCliEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptCliEntry->wdev->func_idx;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
apcli_ifIndex = ifIndex;
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
}
/*Carter: Tricky point, rept used CliLink's idx to enq mlme.*/
if (Info->CliIdx != 0xFF) {
CliIdx = Info->CliIdx;
pReptCliEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptCliEntry->wdev->func_idx;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
apcli_ifIndex = ifIndex;
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
}
#endif /* MAC_REPEATER_SUPPORT */
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
wdev = &pApCliEntry->wdev;
pProfile_SecConfig = &wdev->SecConfig;
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
pCurrState = &pReptCliEntry->CtrlCurrState;
else
#endif /* MAC_REPEATER_SUPPORT */
pCurrState = &pApCliEntry->CtrlCurrState;
if (Status == MLME_SUCCESS) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("%s():ProbeResp success. SSID=%s, Bssid=%02x:%02x:%02x:%02x:%02x:%02x\n",
__func__, pApCliEntry->Ssid, PRINT_MAC(pApCliEntry->MlmeAux.Bssid)));
*pCurrState = APCLI_CTRL_AUTH;
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
pReptCliEntry->AuthReqCnt = 0;
else
#endif /* MAC_REPEATER_SUPPORT */
pApCliEntry->AuthReqCnt = 0;
COPY_MAC_ADDR(AuthReq.Addr, pApCliEntry->MlmeAux.Bssid);
#if defined(APCLI_SAE_SUPPORT) || defined(APCLI_OWE_SUPPORT)
#ifdef FAST_EAPOL_WAR
/*Shifted from Fast Eapol War from assoc req phase to probe response phase as SAE and OWE update the PMK *
per mactable entry */
{
PMAC_TABLE_ENTRY pmac_entry = NULL;
#ifdef MAC_REPEATER_SUPPORT
if ((pAd->ApCfg.bMACRepeaterEn) &&
(IS_HIF_TYPE(pAd, HIF_MT)) &&
(CliIdx != 0xFF)
) {
if (pReptCliEntry->pre_entry_alloc == TRUE)
ApCliCtrlDeleteMacEntry(pAd, ifIndex, CliIdx);
{
pmac_entry = MacTableInsertEntry(
pAd,
(PUCHAR)(pApCliEntry->MlmeAux.Bssid),
pReptCliEntry->wdev,
ENTRY_REPEATER,
OPMODE_AP,
TRUE);
if (pmac_entry) {
pReptCliEntry->MacTabWCID = pmac_entry->wcid;
pReptCliEntry->pre_entry_alloc = TRUE;
} else {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("repeater pEntry insert fail"));
*pCurrState = APCLI_CTRL_DISCONNECTED;
return;
}
}
} else
#endif /* MAC_REPEATER_SUPPORT */
{
if (pApCliEntry->pre_entry_alloc == TRUE)
ApCliCtrlDeleteMacEntry(pAd, ifIndex, CliIdx);
{
pmac_entry = MacTableInsertEntry(
pAd,
(PUCHAR)(pApCliEntry->MlmeAux.Bssid),
&pApCliEntry->wdev,
ENTRY_APCLI,
OPMODE_AP,
TRUE);
if (pmac_entry) {
pApCliEntry->pre_entry_alloc = TRUE;
pApCliEntry->MacTabWCID = pmac_entry->wcid;
} else {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("apcli pEntry insert fail"));
*pCurrState = APCLI_CTRL_DISCONNECTED;
return;
}
}
}
/*With Fast Eaol War the mactable entry sec_config parameters can be updated here instead of during linkup*/
if (pmac_entry) {
struct _SECURITY_CONFIG *pProfile_SecConfig = &wdev->SecConfig;
struct _SECURITY_CONFIG *pEntry_SecConfig = &pmac_entry->SecConfig;
#ifdef DOT11W_PMF_SUPPORT
/*fill the pmac_entry's PMF parameters*/
{
RSN_CAPABILITIES RsnCap;
NdisMoveMemory(&RsnCap, &pApCliEntry->MlmeAux.RsnCap, sizeof(RSN_CAPABILITIES));
RsnCap.word = cpu2le16(RsnCap.word);
/*mismatch case*/
if (((pProfile_SecConfig->PmfCfg.MFPR) && (RsnCap.field.MFPC == FALSE))
|| ((pProfile_SecConfig->PmfCfg.MFPC == FALSE) && (RsnCap.field.MFPR))) {
pEntry_SecConfig->PmfCfg.UsePMFConnect = FALSE;
pEntry_SecConfig->key_deri_alg = SEC_KEY_DERI_SHA1;
}
if ((pProfile_SecConfig->PmfCfg.MFPC) && (RsnCap.field.MFPC)) {
pEntry_SecConfig->PmfCfg.UsePMFConnect = TRUE;
if ((pApCliEntry->MlmeAux.IsSupportSHA256KeyDerivation) || (RsnCap.field.MFPR))
pEntry_SecConfig->key_deri_alg = SEC_KEY_DERI_SHA256;
pEntry_SecConfig->PmfCfg.MFPC = RsnCap.field.MFPC;
pEntry_SecConfig->PmfCfg.MFPR = RsnCap.field.MFPR;
}
pEntry_SecConfig->PmfCfg.igtk_cipher = pApCliEntry->MlmeAux.IntegrityGroupCipher;
}
#endif /* DOT11W_PMF_SUPPORT */
if (IS_CIPHER_WEP(pEntry_SecConfig->PairwiseCipher)) {
os_move_mem(pEntry_SecConfig->WepKey, pProfile_SecConfig->WepKey, sizeof(SEC_KEY_INFO)*SEC_KEY_NUM);
pProfile_SecConfig->GroupKeyId = pProfile_SecConfig->PairwiseKeyId;
pEntry_SecConfig->PairwiseKeyId = pProfile_SecConfig->PairwiseKeyId;
} else {
CHAR rsne_idx = 0;
if (!(IS_AKM_SAE_SHA256(pEntry_SecConfig->AKMMap) || IS_AKM_OWE(pEntry_SecConfig->AKMMap)
|| IS_AKM_OPEN(pEntry_SecConfig->AKMMap))) {
{
SetWPAPSKKey(pAd, pProfile_SecConfig->PSK, strlen(pProfile_SecConfig->PSK),
pApCliEntry->MlmeAux.Ssid, pApCliEntry->MlmeAux.SsidLen, pEntry_SecConfig->PMK);
DebugLevel = DBG_LVL_TRACE;
hex_dump("pmkfromPSK:", (char *)pEntry_SecConfig->PMK, LEN_PMK);
DebugLevel = DBG_LVL_ERROR;
}
}
#ifdef MAC_REPEATER_SUPPORT
if ((pAd->ApCfg.bMACRepeaterEn) && (IS_HIF_TYPE(pAd, HIF_MT)) && (CliIdx != 0xFF)) {
os_move_mem(pEntry_SecConfig->Handshake.AAddr, pmac_entry->Addr, MAC_ADDR_LEN);
os_move_mem(pEntry_SecConfig->Handshake.SAddr, pReptCliEntry->CurrentAddress, MAC_ADDR_LEN);
} else
#endif /* MAC_REPEATER_SUPPORT */
{
os_move_mem(pEntry_SecConfig->Handshake.AAddr, pmac_entry->Addr, MAC_ADDR_LEN);
os_move_mem(pEntry_SecConfig->Handshake.SAddr, wdev->if_addr, MAC_ADDR_LEN);
}
os_zero_mem(pEntry_SecConfig->Handshake.ReplayCounter, LEN_KEY_DESC_REPLAY);
for (rsne_idx = 0; rsne_idx < SEC_RSNIE_NUM; rsne_idx++) {
pEntry_SecConfig->RSNE_Type[rsne_idx] = pProfile_SecConfig->RSNE_Type[rsne_idx];
if (pEntry_SecConfig->RSNE_Type[rsne_idx] == SEC_RSNIE_NONE)
continue;
os_move_mem(pEntry_SecConfig->RSNE_EID[rsne_idx], pProfile_SecConfig->RSNE_EID[rsne_idx], sizeof(UCHAR));
pEntry_SecConfig->RSNE_Len[rsne_idx] = pProfile_SecConfig->RSNE_Len[rsne_idx];
os_move_mem(pEntry_SecConfig->RSNE_Content[rsne_idx], pProfile_SecConfig->RSNE_Content[rsne_idx], sizeof(UCHAR)*MAX_LEN_OF_RSNIE);
}
pmac_entry->SecConfig.Handshake.WpaState = AS_INITPSK;
}
pEntry_SecConfig->GroupKeyId = pProfile_SecConfig->GroupKeyId;
MTWF_LOG(DBG_CAT_CLIENT, DBG_SUBCAT_ALL, DBG_LVL_TRACE,
("%s: (apcli%d) connect AKM(0x%x)=%s, PairwiseCipher(0x%x)=%s, GroupCipher(0x%x)=%s\n",
__func__, ifIndex,
pEntry_SecConfig->AKMMap, GetAuthModeStr(pEntry_SecConfig->AKMMap),
pEntry_SecConfig->PairwiseCipher, GetEncryModeStr(pEntry_SecConfig->PairwiseCipher),
pEntry_SecConfig->GroupCipher, GetEncryModeStr(pEntry_SecConfig->GroupCipher)));
MTWF_LOG(DBG_CAT_CLIENT, DBG_SUBCAT_ALL, DBG_LVL_TRACE,
("%s(): PairwiseKeyId=%d, GroupKeyId=%d\n",
__func__, pEntry_SecConfig->PairwiseKeyId, pEntry_SecConfig->GroupKeyId));
}
}
#endif /* FAST_EAPOL_WAR */
#endif
#ifdef APCLI_SAE_SUPPORT
if (IS_AKM_SAE_SHA256(pApCliEntry->MlmeAux.AKMMap)) {
UCHAR if_addr[MAC_ADDR_LEN];
UCHAR pmkid[LEN_PMKID];
UCHAR pmk[LEN_PMK];
UCHAR has_pmkid = FALSE;
NdisZeroMemory(if_addr, MAC_ADDR_LEN);
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
NdisCopyMemory(if_addr, &pReptCliEntry->CurrentAddress, MAC_ADDR_LEN);
else
#endif /* MAC_REPEATER_SUPPORT */
NdisCopyMemory(if_addr, &pApCliEntry->wdev.if_addr, MAC_ADDR_LEN);
if (sae_get_pmk_cache(&pAd->SaeCfg, if_addr, pApCliEntry->MlmeAux.Bssid, pmkid, pmk)) {
apcli_add_pmkid_cache(pAd, pApCliEntry->MlmeAux.Bssid, pmkid, pmk, LEN_PMK, ifIndex, CliIdx);
has_pmkid = TRUE;
}
if (has_pmkid == TRUE) {
COPY_MAC_ADDR(AuthReq.Addr, pApCliEntry->MlmeAux.Bssid);
AuthReq.Alg = AUTH_MODE_OPEN;
MTWF_LOG(DBG_CAT_SEC, CATSEC_SAE, DBG_LVL_OFF,
("(%s) - use pmkid\n", __func__));
} else {
COPY_MAC_ADDR(AuthReq.Addr, pApCliEntry->MlmeAux.Bssid);
AuthReq.Alg = AUTH_MODE_SAE;
MTWF_LOG(DBG_CAT_SEC, CATSEC_SAE, DBG_LVL_OFF,
("(%s) - use SAE\n", __func__));
}
} else
#endif/* APCLI_SAE_SUPPORT */
/* start Authentication Req. */
/* If AuthMode is Auto, try shared key first */
if (IS_AKM_SHARED(pApCliEntry->MlmeAux.AKMMap) ||
IS_AKM_AUTOSWITCH(pApCliEntry->MlmeAux.AKMMap))
AuthReq.Alg = Ndis802_11AuthModeShared;
else
AuthReq.Alg = Ndis802_11AuthModeOpen;
AuthReq.Timeout = AUTH_TIMEOUT;
#ifdef MAC_REPEATER_SUPPORT
AuthReq.BssIdx = ifIndex;
AuthReq.CliIdx = CliIdx;
if (CliIdx != 0xFF) {
ifIndex = (REPT_MLME_START_IDX + CliIdx);
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_INFO,
("(%s) Repeater Cli Trigger Auth Req ifIndex = %d, CliIdx = %d !!!\n",
__func__, ifIndex, CliIdx));
}
#endif /* MAC_REPEATER_SUPPORT */
#ifdef APCLI_SAE_SUPPORT
if (AuthReq.Alg == AUTH_MODE_SAE)
MlmeEnqueue(pAd, APCLI_AUTH_STATE_MACHINE, APCLI_MT2_MLME_SAE_AUTH_REQ,
sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq, ifIndex);
else {
#endif
#if (!(defined(APCLI_SAE_SUPPORT) || defined(APCLI_OWE_SUPPORT)))
/*Skip pEntry PMK update from wdev->seconfig for SAE and OWE*/
/* Calculate PMK */
if (!IS_CIPHER_WEP(pProfile_SecConfig->PairwiseCipher)) {
SetWPAPSKKey(pAd, pProfile_SecConfig->PSK, strlen(pProfile_SecConfig->PSK),
pApCliEntry->MlmeAux.Ssid, pApCliEntry->MlmeAux.SsidLen, pProfile_SecConfig->PMK);
}
#endif
MlmeEnqueue(pAd, APCLI_AUTH_STATE_MACHINE, APCLI_MT2_MLME_AUTH_REQ,
sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq, ifIndex);
#ifdef APCLI_SAE_SUPPORT
}
#endif
RTMP_MLME_HANDLER(pAd);
} else {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Probe response fail.\n", __func__));
*pCurrState = APCLI_CTRL_DISCONNECTED;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
if ((pAd->ApCfg.ApCliAutoConnectRunning[apcli_ifIndex] == TRUE)
#ifdef MAC_REPEATER_SUPPORT
&& (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
)
ApCliSwitchCandidateAP(pAd, wdev);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
}
}
/*
==========================================================================
Description:
APCLI MLME AUTH Rsp state machine procedure
==========================================================================
*/
static VOID ApCliCtrlAuthRspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
APCLI_CTRL_MSG_STRUCT *Info = (APCLI_CTRL_MSG_STRUCT *)(Elem->Msg);
USHORT Status = Info->Status;
MLME_ASSOC_REQ_STRUCT AssocReq;
MLME_AUTH_REQ_STRUCT AuthReq;
PAPCLI_STRUCT pApCliEntry;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
PULONG pAssocCurrState = NULL;
USHORT Timeout = ASSOC_TIMEOUT;
#ifdef MAC_REPEATER_SUPPORT
UCHAR CliIdx = 0xFF;
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
#endif /* MAC_REPEATER_SUPPORT */
#ifdef APCLI_AUTO_CONNECT_SUPPORT
USHORT apcli_ifIndex = (USHORT)(Elem->Priv);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->wdev->func_idx;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
apcli_ifIndex = ifIndex;
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
}
#endif /* MAC_REPEATER_SUPPORT */
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_INFO,
("(%s) Repeater Cli Receive ifIndex = %d, CliIdx = %d !!!\n",
__func__, ifIndex, CliIdx));
pCurrState = &pReptEntry->CtrlCurrState;
pAssocCurrState = &pReptEntry->AssocCurrState;
} else
#endif /* MAC_REPEATER_SUPPORT */
{
pCurrState = &pApCliEntry->CtrlCurrState;
pAssocCurrState = &pApCliEntry->AssocCurrState;
}
if (Status == MLME_SUCCESS) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE,
("(%s) Auth Rsp Success.\n",
__func__));
*pCurrState = APCLI_CTRL_ASSOC;
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
pReptEntry->AssocReqCnt = 0;
else
#endif /* MAC_REPEATER_SUPPORT */
pApCliEntry->AssocReqCnt = 0;
#if defined(APCLI_SAE_SUPPORT) || defined(APCLI_OWE_SUPPORT)
if (IS_AKM_SAE_SHA256(pApCliEntry->MlmeAux.AKMMap)
|| IS_AKM_OWE(pApCliEntry->MlmeAux.AKMMap)
|| IS_AKM_FT_SAE_SHA256(pApCliEntry->MlmeAux.AKMMap)) {
pAssocCurrState = ASSOC_IDLE;
Timeout = 5000;
}
#endif
#ifdef APCLI_CONNECTION_TRIAL
/* if connection trying, wait until trialtimeout and enqueue Assoc REQ then. */
/* TrialCh == 0 means trial has not been triggered. */
if (pApCliEntry->TrialCh == 0) {
#endif /* APCLI_CONNECTION_TRIAL */
AssocParmFill(pAd,
&AssocReq,
pApCliEntry->MlmeAux.Bssid,
pApCliEntry->MlmeAux.CapabilityInfo,
Timeout,
5);
#ifdef APCLI_CONNECTION_TRIAL
}
#endif /* APCLI_CONNECTION_TRIAL */
#ifdef APCLI_CONNECTION_TRIAL
/* if connection trying, wait until trialtimeout and enqueue Assoc REQ then. */
/* TrialCh == 0 means trial has not been triggered. */
if (pApCliEntry->TrialCh == 0) {
#endif /* APCLI_CONNECTION_TRIAL */
#ifdef MAC_REPEATER_SUPPORT
ifIndex = (USHORT)(Elem->Priv);
#endif /* MAC_REPEATER_SUPPORT */
MlmeEnqueue(pAd, APCLI_ASSOC_STATE_MACHINE, APCLI_MT2_MLME_ASSOC_REQ,
sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq, ifIndex);
RTMP_MLME_HANDLER(pAd);
#ifdef APCLI_CONNECTION_TRIAL
}
#endif /* APCLI_CONNECTION_TRIAL */
} else {
if (IS_AKM_AUTOSWITCH(pApCliEntry->wdev.SecConfig.AKMMap) &&
(pAd->ApCfg.ApCliTab[ifIndex].bBlockAssoc == FALSE)) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Shared Auth Rsp Failure.\n", __func__));
*pCurrState = APCLI_CTRL_AUTH_2;
/* start Second Authentication Req. */
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) IN WEPAUTO Mode, Start Second Auth Req with OPEN.\n", __func__));
COPY_MAC_ADDR(AuthReq.Addr, pApCliEntry->MlmeAux.Bssid);
AuthReq.Alg = Ndis802_11AuthModeOpen;
AuthReq.Timeout = AUTH_TIMEOUT;
#ifdef MAC_REPEATER_SUPPORT
AuthReq.BssIdx = ifIndex;
AuthReq.CliIdx = CliIdx;
ifIndex = (USHORT)(Elem->Priv);
#endif /* MAC_REPEATER_SUPPORT */
MlmeEnqueue(pAd, APCLI_AUTH_STATE_MACHINE, APCLI_MT2_MLME_AUTH_REQ,
sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq, ifIndex);
} else {
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
pReptEntry->AuthReqCnt = 0;
else
#endif /* MAC_REPEATER_SUPPORT */
{
NdisZeroMemory(pApCliEntry->MlmeAux.Bssid, MAC_ADDR_LEN);
NdisZeroMemory(pApCliEntry->MlmeAux.Ssid, MAX_LEN_OF_SSID);
pApCliEntry->AuthReqCnt = 0;
#ifdef APCLI_OWE_SUPPORT
apcli_reset_owe_parameters(pAd, ifIndex);
#endif
}
#if defined(APCLI_SAE_SUPPORT) || defined(APCLI_OWE_SUPPORT)
#ifdef FAST_EAPOL_WAR
ApCliCtrlDeleteMacEntry(pAd, apcli_ifIndex, CliIdx);
#endif /* FAST_EAPOL_WAR */
#endif
*pCurrState = APCLI_CTRL_DISCONNECTED;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
if ((pAd->ApCfg.ApCliAutoConnectRunning[apcli_ifIndex] == TRUE)
#ifdef MAC_REPEATER_SUPPORT
&& (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
)
ApCliSwitchCandidateAP(pAd, &pApCliEntry->wdev);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
}
}
}
/*
==========================================================================
Description:
APCLI MLME AUTH2 Rsp state machine procedure
==========================================================================
*/
static VOID ApCliCtrlAuth2RspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
APCLI_CTRL_MSG_STRUCT *Info = (APCLI_CTRL_MSG_STRUCT *)(Elem->Msg);
USHORT Status = Info->Status;
MLME_ASSOC_REQ_STRUCT AssocReq;
PAPCLI_STRUCT pApCliEntry;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
PULONG pAssocCurrState = NULL;
#ifdef MAC_REPEATER_SUPPORT
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
UCHAR CliIdx = 0xFF;
#endif /* MAC_REPEATER_SUPPORT */
#ifdef APCLI_AUTO_CONNECT_SUPPORT
USHORT apcli_ifIndex = (USHORT)(Elem->Priv);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->wdev->func_idx;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
apcli_ifIndex = ifIndex;
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
}
#endif /* MAC_REPEATER_SUPPORT */
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF) {
pCurrState = &pReptEntry->CtrlCurrState;
pAssocCurrState = &pReptEntry->AssocCurrState;
}
else
#endif /* MAC_REPEATER_SUPPORT */
{
pCurrState = &pApCliEntry->CtrlCurrState;
pAssocCurrState = &pApCliEntry->AssocCurrState;
}
if (Status == MLME_SUCCESS) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Auth2 Rsp Success.\n", __func__));
*pCurrState = APCLI_CTRL_ASSOC;
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
pReptEntry->AssocReqCnt = 0;
else
#endif /* MAC_REPEATER_SUPPORT */
pApCliEntry->AssocReqCnt = 0;
AssocParmFill(pAd, &AssocReq, pApCliEntry->MlmeAux.Bssid, pApCliEntry->MlmeAux.CapabilityInfo,
ASSOC_TIMEOUT, 5);
#ifdef MAC_REPEATER_SUPPORT
ifIndex = (USHORT)(Elem->Priv);
#endif /* MAC_REPEATER_SUPPORT */
MlmeEnqueue(pAd, APCLI_ASSOC_STATE_MACHINE, APCLI_MT2_MLME_ASSOC_REQ,
sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq, ifIndex);
RTMP_MLME_HANDLER(pAd);
} else {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Apcli Auth Rsp Failure.\n", __func__));
*pCurrState = APCLI_CTRL_DISCONNECTED;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
if ((pAd->ApCfg.ApCliAutoConnectRunning[apcli_ifIndex] == TRUE)
#ifdef MAC_REPEATER_SUPPORT
&& (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
)
ApCliSwitchCandidateAP(pAd, &pApCliEntry->wdev);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
}
}
/*
==========================================================================
Description:
APCLI MLME Auth Req timeout state machine procedure
==========================================================================
*/
static VOID ApCliCtrlAuthReqTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
MLME_AUTH_REQ_STRUCT AuthReq;
PAPCLI_STRUCT pApCliEntry;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
#ifdef MAC_REPEATER_SUPPORT
UCHAR CliIdx = 0xFF;
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
#endif /* MAC_REPEATER_SUPPORT */
#ifdef APCLI_AUTO_CONNECT_SUPPORT
USHORT apcli_ifIndex = (USHORT)(Elem->Priv);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->wdev->func_idx;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
apcli_ifIndex = ifIndex;
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
pCurrState = &pReptEntry->CtrlCurrState;
} else
#endif /* MAC_REPEATER_SUPPORT */
pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s) Auth Req Timeout.\n", __func__));
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF) {
pReptEntry->AuthReqCnt++;
if (pReptEntry->AuthReqCnt > 5) {
/* TODO: recycle pReptEntry. */
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR,
("(%s) Rept CliIdx:%d Auth Req Timeout over 5 times.\n",
__func__, CliIdx));
#if defined(APCLI_SAE_SUPPORT) || defined(APCLI_OWE_SUPPORT)
#ifdef FAST_EAPOL_WAR
ApCliCtrlDeleteMacEntry(pAd, apcli_ifIndex, CliIdx);
#endif /* FAST_EAPOL_WAR */
#endif
*pCurrState = APCLI_CTRL_DISCONNECTED;
pReptEntry->AuthReqCnt = 0;
return;
}
} else
#endif /* MAC_REPEATER_SUPPORT */
{
pApCliEntry->AuthReqCnt++;
if (pApCliEntry->AuthReqCnt > 5) {
#if defined(APCLI_SAE_SUPPORT) || defined(APCLI_OWE_SUPPORT)
#ifdef FAST_EAPOL_WAR
ApCliCtrlDeleteMacEntry(pAd, apcli_ifIndex, CliIdx);
#endif /* FAST_EAPOL_WAR */
#endif
*pCurrState = APCLI_CTRL_DISCONNECTED;
NdisZeroMemory(pApCliEntry->MlmeAux.Bssid, MAC_ADDR_LEN);
NdisZeroMemory(pApCliEntry->MlmeAux.Ssid, MAX_LEN_OF_SSID);
pApCliEntry->AuthReqCnt = 0;
#ifdef APCLI_OWE_SUPPORT
apcli_reset_owe_parameters(pAd, ifIndex);
#endif
#ifdef APCLI_AUTO_CONNECT_SUPPORT
if ((pAd->ApCfg.ApCliAutoConnectRunning[apcli_ifIndex] == TRUE)
#ifdef MAC_REPEATER_SUPPORT
&& (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
)
ApCliSwitchCandidateAP(pAd, &pApCliEntry->wdev);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
return;
}
}
/* stay in same state. */
*pCurrState = APCLI_CTRL_AUTH;
/* retry Authentication. */
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Retry Auth Req.\n", __func__));
COPY_MAC_ADDR(AuthReq.Addr, pApCliEntry->MlmeAux.Bssid);
AuthReq.Alg = pApCliEntry->MlmeAux.Alg; /*Ndis802_11AuthModeOpen; */
AuthReq.Timeout = AUTH_TIMEOUT;
#ifdef MAC_REPEATER_SUPPORT
AuthReq.BssIdx = ifIndex;
AuthReq.CliIdx = CliIdx;
ifIndex = (USHORT)(Elem->Priv);
#endif /* MAC_REPEATER_SUPPORT */
MlmeEnqueue(pAd, APCLI_AUTH_STATE_MACHINE, APCLI_MT2_MLME_AUTH_REQ,
sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq, ifIndex);
}
/*
==========================================================================
Description:
APCLI MLME Auth2 Req timeout state machine procedure
==========================================================================
*/
static VOID ApCliCtrlAuth2ReqTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
}
/*
==========================================================================
Description:
APCLI MLME ASSOC RSP state machine procedure
==========================================================================
*/
static VOID ApCliCtrlAssocRspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
PAPCLI_STRUCT pApCliEntry;
APCLI_CTRL_MSG_STRUCT *Info = (APCLI_CTRL_MSG_STRUCT *)(Elem->Msg);
USHORT Status = Info->Status;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
#ifdef MAC_REPEATER_SUPPORT
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
#endif /* MAC_REPEATER_SUPPORT */
#if defined(FAST_EAPOL_WAR) || defined(MAC_REPEATER_SUPPORT)
UCHAR CliIdx = 0xFF;
#endif /* defined(FAST_EAPOL_WAR) || defined (MAC_REPEATER_SUPPORT) */
#if defined(FAST_EAPOL_WAR) || defined(APCLI_AUTO_CONNECT_SUPPORT)
USHORT apcli_ifIndex = (USHORT)(Elem->Priv);
#endif /* defined(FAST_EAPOL_WAR) || defined(APCLI_AUTO_CONNECT_SUPPORT) */
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->wdev->func_idx;
#if defined(FAST_EAPOL_WAR) || defined(APCLI_AUTO_CONNECT_SUPPORT)
apcli_ifIndex = ifIndex;
#endif /* defined(FAST_EAPOL_WAR) || defined(APCLI_AUTO_CONNECT_SUPPORT) */
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_INFO,
("(%s) Repeater Cli Receive Assoc Rsp ifIndex = %d, CliIdx = %d.\n",
__func__, ifIndex, CliIdx));
pCurrState = &pReptEntry->CtrlCurrState;
} else
#endif /* MAC_REPEATER_SUPPORT */
pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
if (Status == MLME_SUCCESS) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_INFO,
("(%s) apCliIf = %d, Receive Assoc Rsp Success.\n",
__func__, ifIndex));
#ifdef MAC_REPEATER_SUPPORT
ifIndex = (USHORT)(Elem->Priv);
#endif /* MAC_REPEATER_SUPPORT */
if (ApCliLinkUp(pAd, ifIndex)) {
*pCurrState = APCLI_CTRL_CONNECTED;
#if defined(RT_CFG80211_P2P_CONCURRENT_DEVICE) || defined(CFG80211_MULTI_STA) || defined(APCLI_CFG80211_SUPPORT)
CFG80211_checkScanTable(pAd);
RT_CFG80211_P2P_CLI_CONN_RESULT_INFORM(pAd, pApCliEntry->MlmeAux.Bssid,
pApCliEntry->ReqVarIEs, pApCliEntry->ReqVarIELen,
pApCliEntry->ResVarIEs, pApCliEntry->ResVarIELen, TRUE);
#ifndef APCLI_CFG80211_SUPPORT
if (pAd->cfg80211_ctrl.bP2pCliPmEnable == TRUE)
CmdP2pNoaOffloadCtrl(pAd, P2P_NOA_RX_ON);
#endif /* APCLI_CFG80211_SUPPORT */
#endif /* RT_CFG80211_P2P_CONCURRENT_DEVICE || CFG80211_MULTI_STA || APCLI_CFG80211_SUPPORT */
} else {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) apCliIf = %d, Insert Remote AP to MacTable failed.\n", __func__, ifIndex));
/* Reset the apcli interface as disconnected and Invalid. */
*pCurrState = APCLI_CTRL_DISCONNECTED;
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
pAd->ApCfg.pRepeaterCliPool[CliIdx].CliValid = FALSE;
else
#endif /* MAC_REPEATER_SUPPORT */
pApCliEntry->Valid = FALSE;
#ifdef FAST_EAPOL_WAR
ApCliCtrlDeleteMacEntry(pAd, apcli_ifIndex, CliIdx);
#endif /* FAST_EAPOL_WAR */
#ifdef APCLI_AUTO_CONNECT_SUPPORT
if ((pAd->ApCfg.ApCliAutoConnectRunning[apcli_ifIndex] == TRUE)
#ifdef MAC_REPEATER_SUPPORT
&& (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
)
ApCliSwitchCandidateAP(pAd, &pApCliEntry->wdev);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
#if defined(RT_CFG80211_P2P_CONCURRENT_DEVICE) || defined(CFG80211_MULTI_STA) || defined(APCLI_CFG80211_SUPPORT)
CFG80211_checkScanTable(pAd);
RT_CFG80211_P2P_CLI_CONN_RESULT_INFORM(pAd, pApCliEntry->MlmeAux.Bssid,
NULL, 0, NULL, 0, 0);
#endif /* RT_CFG80211_P2P_CONCURRENT_DEVICE || CFG80211_MULTI_STA || APCLI_CFG80211_SUPPORT */
}
} else {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR,
("(%s) apCliIf = %d, Receive Assoc Rsp Failure.\n", __func__, ifIndex));
*pCurrState = APCLI_CTRL_DISCONNECTED;
/* set the apcli interface be valid. */
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
pAd->ApCfg.pRepeaterCliPool[CliIdx].CliValid = FALSE;
else
#endif /* MAC_REPEATER_SUPPORT */
pApCliEntry->Valid = FALSE;
#ifdef FAST_EAPOL_WAR
ApCliCtrlDeleteMacEntry(pAd, apcli_ifIndex, CliIdx);
#endif /* FAST_EAPOL_WAR */
#ifdef APCLI_SAE_SUPPORT
if (Status == MLME_INVALID_PMKID) {
#ifdef APCLI_SAE_SUPPORT
UCHAR if_addr[MAC_ADDR_LEN];
#endif
INT CachedIdx;
UCHAR pmkid[LEN_PMKID];
UCHAR pmk[LEN_PMK];
#ifdef APCLI_SAE_SUPPORT
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
NdisCopyMemory(if_addr, &pReptEntry->CurrentAddress, MAC_ADDR_LEN);
else
#endif /* MAC_REPEATER_SUPPORT */
NdisCopyMemory(if_addr, &pApCliEntry->wdev.if_addr, MAC_ADDR_LEN);
/*Received PMK invalid status from AP delete entry from SavedPMK and delete SAE instance*/
if (IS_AKM_SAE(pApCliEntry->MlmeAux.AKMMap) &&
sae_get_pmk_cache(&pAd->SaeCfg, if_addr, pApCliEntry->MlmeAux.Bssid, pmkid, pmk)
) {
CachedIdx = apcli_search_pmkid_cache(pAd, pApCliEntry->MlmeAux.Bssid, ifIndex, CliIdx);
if (CachedIdx != INVALID_PMKID_IDX) {
SAE_INSTANCE *pSaeIns = search_sae_instance(&pAd->SaeCfg, if_addr, pApCliEntry->MlmeAux.Bssid);
MTWF_LOG(DBG_CAT_SEC, CATSEC_SAE, DBG_LVL_ERROR,
("[SAE]Reconnection falied with pmkid ,delete cache entry and sae instance \n"));
if (pSaeIns != NULL) {
delete_sae_instance(pSaeIns);
}
apcli_delete_pmkid_cache(pAd, pApCliEntry->MlmeAux.Bssid, ifIndex, CliIdx);
}
}
#endif
}
#endif/*APCLI_SAE_SUPPORT*/
#ifdef APCLI_AUTO_CONNECT_SUPPORT
if ((pAd->ApCfg.ApCliAutoConnectRunning[apcli_ifIndex] == TRUE)
#ifdef MAC_REPEATER_SUPPORT
&& (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
&& (pApCliEntry->bBlockAssoc == FALSE))
ApCliSwitchCandidateAP(pAd, &pApCliEntry->wdev);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
#if defined(RT_CFG80211_P2P_CONCURRENT_DEVICE) || defined(CFG80211_MULTI_STA) || defined(APCLI_CFG80211_SUPPORT)
CFG80211_checkScanTable(pAd);
RT_CFG80211_P2P_CLI_CONN_RESULT_INFORM(pAd, pApCliEntry->MlmeAux.Bssid, NULL, 0, NULL, 0, 0);
#endif /* RT_CFG80211_P2P_CONCURRENT_DEVICE || CFG80211_MULTI_STA || APCLI_CFG80211_SUPPORT */
}
}
/*
==========================================================================
Description:
APCLI MLME DeASSOC RSP state machine procedure
==========================================================================
*/
static VOID ApCliCtrlDeAssocRspAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
PAPCLI_STRUCT pApCliEntry;
APCLI_CTRL_MSG_STRUCT *Info = (APCLI_CTRL_MSG_STRUCT *)(Elem->Msg);
USHORT Status = Info->Status;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
BOOLEAN bValid = FALSE;
#ifdef MAC_REPEATER_SUPPORT
UCHAR CliIdx = 0xFF;
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
#endif /* MAC_REPEATER_SUPPORT */
PULONG pLinkDownReason = NULL;
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->wdev->func_idx;
pCurrState = &pReptEntry->CtrlCurrState;
pLinkDownReason = &pReptEntry->LinkDownReason;
} else
#endif /* MAC_REPEATER_SUPPORT */
{
pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
pLinkDownReason = &pAd->ApCfg.ApCliTab[ifIndex].LinkDownReason;
}
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
if (Status == MLME_SUCCESS)
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Receive DeAssoc Rsp Success.\n", __func__));
else
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Receive DeAssoc Rsp Failure.\n", __func__));
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
bValid = pReptEntry->CliValid;
else
#endif /* MAC_REPEATER_SUPPORT */
bValid = pApCliEntry->Valid;
#ifdef MAC_REPEATER_SUPPORT
ifIndex = (USHORT)(Elem->Priv);
#endif /* MAC_REPEATER_SUPPORT */
if (bValid) {
*pLinkDownReason = APCLI_LINKDOWN_PEER_DEASSOC_RSP;
ApCliLinkDown(pAd, ifIndex);
}
*pCurrState = APCLI_CTRL_DISCONNECTED;
}
/*
==========================================================================
Description:
APCLI MLME Assoc Req timeout state machine procedure
==========================================================================
*/
static VOID ApCliCtrlAssocReqTimeoutAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
MLME_ASSOC_REQ_STRUCT AssocReq;
PAPCLI_STRUCT pApCliEntry;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
#ifdef MAC_REPEATER_SUPPORT
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
UCHAR CliIdx = 0xFF;
#endif /* MAC_REPEATER_SUPPORT */
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s) Assoc Req Timeout.\n", __func__));
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->wdev->func_idx;
pCurrState = &pReptEntry->CtrlCurrState;
} else
#endif /* MAC_REPEATER_SUPPORT */
pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
/* give up to retry authentication req after retry it 5 times. */
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF) {
pReptEntry->AssocReqCnt++;
if (pReptEntry->AssocReqCnt > 5) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE,
("(%s) Rept CliIdx:%d, Assoc Req Timeout over 5 times\n", __func__, CliIdx));
#ifdef FAST_EAPOL_WAR
ApCliCtrlDeleteMacEntry(pAd, ifIndex, CliIdx);
#endif /* FAST_EAPOL_WAR */
*pCurrState = APCLI_CTRL_DISCONNECTED;
pReptEntry->AssocReqCnt = 0;
return;
}
} else
#endif /* MAC_REPEATER_SUPPORT */
{
pApCliEntry->AssocReqCnt++;
if (pApCliEntry->AssocReqCnt > 5) {
*pCurrState = APCLI_CTRL_DISCONNECTED;
#ifdef FAST_EAPOL_WAR
ApCliCtrlDeleteMacEntry(pAd, ifIndex, CliIdx);
#endif /* FAST_EAPOL_WAR */
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Bssid, MAC_ADDR_LEN);
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Ssid, MAX_LEN_OF_SSID);
pApCliEntry->AssocReqCnt = 0;
#ifdef APCLI_OWE_SUPPORT
apcli_reset_owe_parameters(pAd, ifIndex);
#endif
#ifdef APCLI_AUTO_CONNECT_SUPPORT
if ((pAd->ApCfg.ApCliAutoConnectRunning[ifIndex] == TRUE)
#ifdef MAC_REPEATER_SUPPORT
&& (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
)
ApCliSwitchCandidateAP(pAd, &pApCliEntry->wdev);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
return;
}
}
/* stay in same state. */
*pCurrState = APCLI_CTRL_ASSOC;
/* retry Association Req. */
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("(%s) Retry Association Req.\n", __func__));
AssocParmFill(pAd, &AssocReq, pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Bssid, pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.CapabilityInfo,
ASSOC_TIMEOUT, 5);
#ifdef MAC_REPEATER_SUPPORT
ifIndex = (USHORT)(Elem->Priv);
#endif /* MAC_REPEATER_SUPPORT */
MlmeEnqueue(pAd, APCLI_ASSOC_STATE_MACHINE, APCLI_MT2_MLME_ASSOC_REQ,
sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq, ifIndex);
}
/*
==========================================================================
Description:
APCLI MLME Disconnect Rsp state machine procedure
==========================================================================
*/
static VOID ApCliCtrlDisconnectReqAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
PAPCLI_STRUCT pApCliEntry;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
PULONG pAuthCurrState = NULL;
BOOLEAN bValid = FALSE;
#ifdef MAC_REPEATER_SUPPORT
UCHAR CliIdx = 0xFF;
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
#endif /* MAC_REPEATER_SUPPORT */
PULONG pLinkDownReason = NULL;
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s) MLME Request disconnect.\n", __func__));
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->wdev->func_idx;
pAuthCurrState = &pReptEntry->AuthCurrState;
pCurrState = &pReptEntry->CtrlCurrState;
pLinkDownReason = &pReptEntry->LinkDownReason;
} else
#endif /* MAC_REPEATER_SUPPORT */
{
pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
pAuthCurrState = &pAd->ApCfg.ApCliTab[ifIndex].AuthCurrState;
pLinkDownReason = &pAd->ApCfg.ApCliTab[ifIndex].LinkDownReason;
}
if (ifIndex >= MAX_APCLI_NUM) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s)(%d) ifIndex = %d is out of boundary\n", __func__, __LINE__, ifIndex));
return;
}
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
bValid = pReptEntry->CliValid;
else
#endif /* MAC_REPEATER_SUPPORT */
bValid = pApCliEntry->Valid;
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s) 2. Before do ApCliLinkDown. ifIndex = %d, CliIdx = %d, bValid = %d\n", __func__, ifIndex, CliIdx, bValid));
else
#endif
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s) 2. Before do ApCliLinkDown. ifIndex = %d, bValid = %d\n", __func__, ifIndex, bValid));
#ifdef FAST_EAPOL_WAR
ApCliCtrlDeleteMacEntry(pAd, ifIndex, CliIdx);
#endif /* FAST_EAPOL_WAR */
if (bValid) {
#ifdef MAC_REPEATER_SUPPORT
ifIndex = (USHORT)(Elem->Priv);
#endif /* MAC_REPEATER_SUPPORT */
*pLinkDownReason = APCLI_LINKDOWN_DISCONNECT_REQ;
ApCliLinkDown(pAd, ifIndex);
}
/* set the apcli interface be invalid. */
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
{
if (ifIndex >= MAX_APCLI_NUM) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s)(%d) ifIndex = %d is out of boundary\n", __func__, __LINE__, ifIndex));
return;
}
pApCliEntry->Valid = FALSE;
/* clear MlmeAux.Ssid and Bssid. */
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Bssid, MAC_ADDR_LEN);
pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.SsidLen = 0;
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Ssid, MAX_LEN_OF_SSID);
pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Rssi = 0;
}
{
*pAuthCurrState = AUTH_REQ_IDLE;
*pCurrState = APCLI_CTRL_DISCONNECTED;
}
}
/*
==========================================================================
Description:
APCLI MLME Peer DeAssoc Req state machine procedure
==========================================================================
*/
static VOID ApCliCtrlPeerDeAssocReqAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
PAPCLI_STRUCT pApCliEntry;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
BOOLEAN bValid = FALSE;
#ifdef MAC_REPEATER_SUPPORT
UCHAR index;
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
UCHAR CliIdx = 0xFF;
RTMP_CHIP_CAP *cap = hc_get_chip_cap(pAd->hdev_ctrl);
#endif /* MAC_REPEATER_SUPPORT */
#ifdef APCLI_AUTO_CONNECT_SUPPORT
USHORT apcli_ifIndex = (USHORT)(Elem->Priv);
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
PULONG pLinkDownReason = NULL;
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s) Peer DeAssoc Req.\n", __func__));
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->wdev->func_idx;
#ifdef APCLI_AUTO_CONNECT_SUPPORT
apcli_ifIndex = ifIndex;
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
pCurrState = &pReptEntry->CtrlCurrState;
pLinkDownReason = &pReptEntry->LinkDownReason;
} else
#endif /* MAC_REPEATER_SUPPORT */
{
pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
pLinkDownReason = &pAd->ApCfg.ApCliTab[ifIndex].LinkDownReason;
}
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
#ifdef MAC_REPEATER_SUPPORT
/*check the rept entry which is linked to the CliLink should be disabled, too.*/
if (CliIdx == 0xFF) {
if (pAd->ApCfg.bMACRepeaterEn == TRUE) {
for (index = 0; index < GET_MAX_REPEATER_ENTRY_NUM(cap); index++) {
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[index];
if ((pReptEntry->CliEnable) && (pReptEntry->wdev == &pApCliEntry->wdev)) {
if (pReptEntry->CliValid) {
pReptEntry->LinkDownReason = APCLI_LINKDOWN_PEER_DEASSOC_REQ;
ApCliLinkDown(pAd, (REPT_MLME_START_IDX + index));
}
}
}
}
}
#endif /* MAC_REPEATER_SUPPORT */
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
bValid = pReptEntry->CliValid;
else
#endif /* MAC_REPEATER_SUPPORT */
bValid = pApCliEntry->Valid;
if (bValid) {
*pLinkDownReason = APCLI_LINKDOWN_PEER_DEASSOC_REQ;
ApCliLinkDown(pAd, (UCHAR)(Elem->Priv));
}
#ifdef APCLI_AUTO_CONNECT_SUPPORT
if ((pAd->ApCfg.ApCliAutoConnectRunning[apcli_ifIndex] == TRUE)
#ifdef MAC_REPEATER_SUPPORT
&& (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
) {
STA_TR_ENTRY *tr_entry = &pAd->MacTab.tr_entry[pApCliEntry->MacTabWCID];
if (tr_entry->PortSecured == WPA_802_1X_PORT_NOT_SECURED)
ApCliSwitchCandidateAP(pAd, &pApCliEntry->wdev);
}
#endif /* APCLI_AUTO_CONNECT_SUPPORT */
/* set the apcli interface be invalid. */
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
{
pApCliEntry->Valid = FALSE;
/* clear MlmeAux.Ssid and Bssid. */
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Bssid, MAC_ADDR_LEN);
pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.SsidLen = 0;
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Ssid, MAX_LEN_OF_SSID);
pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Rssi = 0;
#ifdef APCLI_OWE_SUPPORT
apcli_reset_owe_parameters(pAd, ifIndex);
#endif
}
{
*pCurrState = APCLI_CTRL_DISCONNECTED;
}
}
/*
==========================================================================
Description:
APCLI MLME Disconnect Req state machine procedure
==========================================================================
*/
static VOID ApCliCtrlDeAssocAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
PAPCLI_STRUCT pApCliEntry;
MLME_DISASSOC_REQ_STRUCT DisassocReq;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
BOOLEAN bValid = FALSE;
#ifdef MAC_REPEATER_SUPPORT
UCHAR CliIdx = 0xFF;
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
#endif /* MAC_REPEATER_SUPPORT */
PULONG pLinkDownReason = NULL;
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s) MLME Request Disconnect.\n", __func__));
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->wdev->func_idx;
pCurrState = &pReptEntry->CtrlCurrState;
pLinkDownReason = &pReptEntry->LinkDownReason;
} else
#endif /* MAC_REPEATER_SUPPORT */
{
pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
pLinkDownReason = &pAd->ApCfg.ApCliTab[ifIndex].LinkDownReason;
}
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
DisassocParmFill(pAd, &DisassocReq, pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Bssid, REASON_DISASSOC_STA_LEAVING);
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
bValid = pReptEntry->CliValid;
else
#endif /* MAC_REPEATER_SUPPORT */
bValid = pApCliEntry->Valid;
MlmeEnqueue(pAd, APCLI_ASSOC_STATE_MACHINE, APCLI_MT2_MLME_DISASSOC_REQ,
sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq, (ULONG)(Elem->Priv));
RTMP_MLME_HANDLER(pAd);
if (bValid) {
*pLinkDownReason = APCLI_LINKDOWN_DEASSOC_REQ;
ApCliLinkDown(pAd, (UCHAR)(Elem->Priv));
}
/* set the apcli interface be invalid. */
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
{
pApCliEntry->Valid = FALSE;
/* clear MlmeAux.Ssid and Bssid. */
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Bssid, MAC_ADDR_LEN);
pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.SsidLen = 0;
NdisZeroMemory(pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Ssid, MAX_LEN_OF_SSID);
pAd->ApCfg.ApCliTab[ifIndex].MlmeAux.Rssi = 0;
}
*pCurrState = APCLI_CTRL_DEASSOC;
}
/*
==========================================================================
Description:
APCLI MLME Disconnect Req state machine procedure
==========================================================================
*/
static
VOID ApCliCtrlDeAuthAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
PAPCLI_STRUCT pApCliEntry;
MLME_DEAUTH_REQ_STRUCT DeAuthFrame;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = NULL;
BOOLEAN bValid = FALSE;
PULONG pLinkDownReason = NULL;
MLME_AUX *apcli_mlme_aux;
MLME_QUEUE_ELEM *mlmeDeauth_Elem;
#ifdef MAC_REPEATER_SUPPORT
UCHAR CliIdx = 0xFF;
REPEATER_CLIENT_ENTRY *pReptEntry = NULL;
#endif /* MAC_REPEATER_SUPPORT */
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s) MLME Request Disconnect.\n", __func__));
if ((ifIndex >= MAX_APCLI_NUM)
#ifdef MAC_REPEATER_SUPPORT
&& (ifIndex < REPT_MLME_START_IDX)
#endif /* MAC_REPEATER_SUPPORT */
)
return;
#ifdef MAC_REPEATER_SUPPORT
if (ifIndex >= REPT_MLME_START_IDX) {
CliIdx = ifIndex - REPT_MLME_START_IDX;
pReptEntry = &pAd->ApCfg.pRepeaterCliPool[CliIdx];
ifIndex = pReptEntry->MatchApCliIdx;
pCurrState = &pReptEntry->CtrlCurrState;
pLinkDownReason = &pReptEntry->LinkDownReason;
} else
#endif /* MAC_REPEATER_SUPPORT */
{
pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
pLinkDownReason = &pAd->ApCfg.ApCliTab[ifIndex].LinkDownReason;
}
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
apcli_mlme_aux = &pAd->ApCfg.ApCliTab[ifIndex].MlmeAux;
/* Fill in the related information */
DeAuthFrame.Reason = (USHORT)REASON_DEAUTH_STA_LEAVING;
COPY_MAC_ADDR(DeAuthFrame.Addr, apcli_mlme_aux->Bssid);
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx != 0xFF)
bValid = pReptEntry->CliValid;
else
#endif /* MAC_REPEATER_SUPPORT */
bValid = pApCliEntry->Valid;
os_alloc_mem(pAd, (UCHAR **)&mlmeDeauth_Elem, sizeof(MLME_QUEUE_ELEM));
if(mlmeDeauth_Elem == NULL)
{
MTWF_LOG(DBG_CAT_CFG, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("%s: Send Deauth Failed!!\n", __func__));
return;
}
mlmeDeauth_Elem->Priv = Elem->Priv;
NdisCopyMemory(mlmeDeauth_Elem->Msg, &DeAuthFrame, sizeof(MLME_DEAUTH_REQ_STRUCT));
mlmeDeauth_Elem->MsgLen = sizeof(MLME_DEAUTH_REQ_STRUCT);
ApCliMlmeDeauthReqAction(pAd, mlmeDeauth_Elem);
os_free_mem(mlmeDeauth_Elem);
if (bValid) {
*pLinkDownReason = APCLI_LINKDOWN_DEAUTH_REQ;
ApCliLinkDown(pAd, (UCHAR)(Elem->Priv));
}
/* set the apcli interface be invalid. */
#ifdef MAC_REPEATER_SUPPORT
if (CliIdx == 0xFF)
#endif /* MAC_REPEATER_SUPPORT */
{
pApCliEntry->Valid = FALSE;
/* clear MlmeAux.Ssid and Bssid. */
NdisZeroMemory(apcli_mlme_aux->Bssid, MAC_ADDR_LEN);
apcli_mlme_aux->SsidLen = 0;
NdisZeroMemory(apcli_mlme_aux->Ssid, MAX_LEN_OF_SSID);
apcli_mlme_aux->Rssi = 0;
}
*pCurrState = APCLI_CTRL_DISCONNECTED;
}
static VOID ApCliWpaMicFailureReportFrame(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
PUCHAR pOutBuffer = NULL;
UCHAR Header802_3[14];
ULONG FrameLen = 0;
UCHAR *mpool;
PEAPOL_PACKET pPacket;
UCHAR Mic[16];
BOOLEAN bUnicast;
UCHAR Wcid;
PMAC_TABLE_ENTRY pMacEntry = NULL;
USHORT ifIndex = (USHORT)(Elem->Priv);
APCLI_STRUCT *apcli_entry;
struct wifi_dev *wdev;
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_TRACE, ("ApCliWpaMicFailureReportFrame ----->\n"));
apcli_entry = &pAd->ApCfg.ApCliTab[ifIndex];
wdev = &apcli_entry->wdev;
if (ifIndex >= MAX_APCLI_NUM)
return;
bUnicast = (Elem->Msg[0] == 1 ? TRUE:FALSE);
pAd->Sequence = ((pAd->Sequence) + 1) & (MAX_SEQ_NUMBER);
/* init 802.3 header and Fill Packet */
pMacEntry = &pAd->MacTab.Content[apcli_entry->MacTabWCID];
if (!IS_ENTRY_APCLI(pMacEntry)) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("(%s) pMacEntry is not ApCli Entry\n", __func__));
return;
}
Wcid = apcli_entry->MacTabWCID;
MAKE_802_3_HEADER(Header802_3, pAd->MacTab.Content[Wcid].Addr, wdev->if_addr, EAPOL);
/* Allocate memory for output */
os_alloc_mem(NULL, (PUCHAR *)&mpool, TX_EAPOL_BUFFER);
if (mpool == NULL) {
MTWF_LOG(DBG_CAT_CLIENT, CATCLIENT_APCLI, DBG_LVL_ERROR, ("!!!(%s) : no memory!!!\n", __func__));
return;
}
pPacket = (PEAPOL_PACKET)mpool;
NdisZeroMemory(pPacket, TX_EAPOL_BUFFER);
pPacket->ProVer = EAPOL_VER;
pPacket->ProType = EAPOLKey;
pPacket->KeyDesc.Type = WPA1_KEY_DESC;
/* Request field presented */
pPacket->KeyDesc.KeyInfo.Request = 1;
if (IS_CIPHER_CCMP128(wdev->SecConfig.PairwiseCipher))
pPacket->KeyDesc.KeyInfo.KeyDescVer = 2;
else /* TKIP */
pPacket->KeyDesc.KeyInfo.KeyDescVer = 1;
pPacket->KeyDesc.KeyInfo.KeyType = (bUnicast ? PAIRWISEKEY : GROUPKEY);
/* KeyMic field presented */
pPacket->KeyDesc.KeyInfo.KeyMic = 1;
/* Error field presented */
pPacket->KeyDesc.KeyInfo.Error = 1;
/* Update packet length after decide Key data payload */
SET_UINT16_TO_ARRARY(pPacket->Body_Len, MIN_LEN_OF_EAPOL_KEY_MSG);
/* Key Replay Count */
NdisMoveMemory(pPacket->KeyDesc.ReplayCounter, apcli_entry->ReplayCounter, LEN_KEY_DESC_REPLAY);
/* inc_byte_array(apcli_entry->ReplayCounter, 8); */
ADD_ONE_To_64BIT_VAR(apcli_entry->ReplayCounter);
/* Convert to little-endian format. */
*((USHORT *)&pPacket->KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&pPacket->KeyDesc.KeyInfo));
MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer); /* allocate memory */
if (pOutBuffer == NULL) {
os_free_mem(mpool);
return;
}
/*
Prepare EAPOL frame for MIC calculation
Be careful, only EAPOL frame is counted for MIC calculation
*/
MakeOutgoingFrame(pOutBuffer, &FrameLen,
CONV_ARRARY_TO_UINT16(pPacket->Body_Len) + 4, pPacket,
END_OF_ARGS);
/*
Prepare EAPOL frame for MIC calculation
Be careful, only EAPOL frame is counted for MIC calculation
*/
MakeOutgoingFrame(pOutBuffer, &FrameLen,
CONV_ARRARY_TO_UINT16(pPacket->Body_Len) + 4, pPacket,
END_OF_ARGS);
/* Prepare and Fill MIC value */
NdisZeroMemory(Mic, sizeof(Mic));
if (IS_CIPHER_CCMP128(wdev->SecConfig.PairwiseCipher)) {
/* AES */
UCHAR digest[20] = {0};
RT_HMAC_SHA1(pMacEntry->SecConfig.PTK, LEN_PTK_KCK, pOutBuffer, FrameLen, digest, SHA1_DIGEST_SIZE);
NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
} else {
/* TKIP */
RT_HMAC_MD5(pMacEntry->SecConfig.PTK, LEN_PTK_KCK, pOutBuffer, FrameLen, Mic, MD5_DIGEST_SIZE);
}
NdisMoveMemory(pPacket->KeyDesc.KeyMicAndData, Mic, LEN_KEY_DESC_MIC);
/* copy frame to Tx ring and send MIC failure report frame to authenticator */
RTMPToWirelessSta(pAd, &pAd->MacTab.Content[Wcid],
Header802_3, LENGTH_802_3,
(PUCHAR)pPacket,
CONV_ARRARY_TO_UINT16(pPacket->Body_Len) + 4, FALSE);
MlmeFreeMemory((PUCHAR)pOutBuffer);
os_free_mem(mpool);
MTWF_LOG(DBG_CAT_CLIENT, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("ApCliWpaMicFailureReportFrame <-----\n"));
}
#ifdef APCLI_CERT_SUPPORT
static VOID ApCliCtrlScanDoneAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
#ifdef DOT11N_DRAFT3
USHORT ifIndex = (USHORT)(Elem->Priv);
UCHAR i;
RTMP_CHIP_CAP *cap = hc_get_chip_cap(pAd->hdev_ctrl);
/* AP sent a 2040Coexistence mgmt frame, then station perform a scan, and then send back the respone. */
if ((pAd->CommonCfg.BSSCoexist2040.field.InfoReq == 1)
&& OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SCAN_2040)) {
MTWF_LOG(DBG_CAT_CLIENT, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("Update2040CoexistFrameAndNotify @%s\n", __func__));
for (i = 0; i < MAX_LEN_OF_MAC_TABLE; i++) {
if (IS_ENTRY_APCLI(&pAd->MacTab.Content[i]) && (pAd->MacTab.Content[i].func_tb_idx == ifIndex)) {
Update2040CoexistFrameAndNotify(pAd, i, TRUE);
#ifdef RACTRL_FW_OFFLOAD_SUPPORT
if (cap->fgRateAdaptFWOffload == TRUE) {
CMD_STAREC_AUTO_RATE_UPDATE_T rRaParam;
NdisZeroMemory(&rRaParam, sizeof(CMD_STAREC_AUTO_RATE_UPDATE_T));
rRaParam.u4Field = RA_PARAM_HT_2040_COEX;
RAParamUpdate(pAd, &pAd->MacTab.Content[i], &rRaParam);
}
#endif /* RACTRL_FW_OFFLOAD_SUPPORT */
}
}
}
#endif /* DOT11N_DRAFT3 */
}
#endif /* APCLI_CERT_SUPPORT */
#ifdef APCLI_CONNECTION_TRIAL
/*
==========================================================================
Description:
APCLI trigger JOIN req state machine procedure
for connect the another rootAP
==========================================================================
*/
static VOID ApCliCtrlTrialConnectAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
APCLI_MLME_JOIN_REQ_STRUCT JoinReq;
PAPCLI_STRUCT pApCliEntry;
USHORT ifIndex = (USHORT)(Elem->Priv);
PULONG pCurrState = &pAd->ApCfg.ApCliTab[ifIndex].CtrlCurrState;
BOOLEAN Cancelled;
struct wifi_dev *wdev = &pAd->ApCfg.ApCliTab[ifIndex].wdev;
struct freq_oper oper;
hc_radio_query_by_wdev(wdev, &oper);
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("(%s) Start Probe Req Trial.\n", __func__));
if (ifIndex >= MAX_APCLI_NUM || ifIndex == 0) {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("(%s) Index: %d error!!\n", __func__, ifIndex));
return;
}
if (ApScanRunning(pAd, wdev) == TRUE) {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("(%s) Ap Scanning.....\n", __func__));
return;
}
pApCliEntry = &pAd->ApCfg.ApCliTab[ifIndex];
if (!(pApCliEntry->TrialCh)) {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("(%s) Didn't assign the RootAP channel\n", __func__));
return;
}
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("(%s) channel TrialConnectTimer\n", __func__));
RTMPCancelTimer(&(pApCliEntry->TrialConnectTimer), &Cancelled);
if (pApCliEntry->TrialCh != oper.prim_ch) {
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("(%s) Jump to CH:%d\n", __func__, pApCliEntry->TrialCh));
/* TBD disable beacon? */
ApCliTrialConnectionBeaconControl(pAd, FALSE);
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR,
("%s[%d]Change ch %d to %d\n\r",
__func__, __LINE__,
pApCliEntry->wdev.channel, pApCliEntry->TrialCh));
/* switch channel to trial channel */
wlan_operate_scan(wdev, pApCliEntry->TrialCh);
}
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("(%s) set TrialConnectTimer(%d ms)\n", __func__, TRIAL_TIMEOUT));
RTMPSetTimer(&(pApCliEntry->TrialConnectTimer), TRIAL_TIMEOUT);
NdisZeroMemory(&JoinReq, sizeof(APCLI_MLME_JOIN_REQ_STRUCT));
if (!MAC_ADDR_EQUAL(pApCliEntry->CfgApCliBssid, ZERO_MAC_ADDR))
COPY_MAC_ADDR(JoinReq.Bssid, pApCliEntry->CfgApCliBssid);
if (pApCliEntry->CfgSsidLen != 0) {
JoinReq.SsidLen = pApCliEntry->CfgSsidLen;
NdisMoveMemory(&(JoinReq.Ssid), pApCliEntry->CfgSsid, JoinReq.SsidLen);
}
MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_TRACE, ("(%s) Probe Ssid=%s, Bssid=%02x:%02x:%02x:%02x:%02x:%02x\n",
__func__, JoinReq.Ssid, JoinReq.Bssid[0], JoinReq.Bssid[1], JoinReq.Bssid[2],
JoinReq.Bssid[3], JoinReq.Bssid[4], JoinReq.Bssid[5]));
*pCurrState = APCLI_CTRL_PROBE;
MlmeEnqueue(pAd, APCLI_SYNC_STATE_MACHINE, APCLI_MT2_MLME_PROBE_REQ,
sizeof(APCLI_MLME_JOIN_REQ_STRUCT), &JoinReq, ifIndex);
}
#endif /* APCLI_CONNECTION_TRIAL */
#endif /* APCLI_SUPPORT */
|
the_stack_data/65615.c
|
int main(){
int a = 5;
int b = 6;
int c;
c = a + b;
if(c == 11){
c = c -1;
if(c == 10){
c = 172; //entra aqui
}
else{
c = 474; //nao entra
}
}
return c;
}
|
the_stack_data/90764836.c
|
// 18 . WAP to convert Fahrenheit to Celsius . c =(f-32)*5/9.
#include <stdio.h>
int celsiusConverter(int temp){
temp = (temp - 32) * 5 / 9 ;
return temp;
}
int main()
{
int temp ;
printf("Enter Temperature in Fahrenheit : ");
scanf("%d", &temp);
printf("Temeperature in celsius : %d", celsiusConverter(temp) );
return 0;
}
|
the_stack_data/173578019.c
|
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>
void
exits(char *unused)
{
exit(-1);
}
int
readn(int fd, unsigned char *buf, int len)
{
int r;
int i = 0;
while ((r = read(fd, &buf[i], len - i)) > 0)
i += r;
return i;
}
int
main(int argc, char **argv)
{
int pid;
int fd;
unsigned char in[16384];
unsigned char out;
int inlen, outlen;
struct termios tty;
if (argc < 2)
exits("args");
fd = open(argv[1], O_RDWR);
if (fd < 0)
exits("%r");
if (tcgetattr(fd, &tty) != 0)
exit(-2);
cfsetspeed(&tty, B115200);
tty.c_cflag &= ~PARENB;
tty.c_cflag |= CS8;
if (tcsetattr(fd, TCSANOW, &tty) != 0)
exit(-3);
pid = fork();
if (pid < 0)
exits("%r");
else if (pid == 0) {
while(1) {
if (readn(fd, in, 4) != 4)
exits("%r");
inlen = in[0] | in[1] << 8 | in[2] << 16 | in[3] << 24;
inlen -= 4;
if (readn(fd, &in[4], inlen) != inlen)
exits("%r");
inlen += 4;
write(1, in, inlen);
}
}
else {
while(read(0, &out, 1) == 1) {
if (write(fd, &out, 1) != 1)
exits("%r");
}
}
}
|
the_stack_data/28642.c
|
/*firmware_tools.c*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
void swag_logo()
{
system("cls");
printf(" ____ _ ___\n");
printf("| _ \\ ___ ___ _ __ _ _ _ __ | |_ / _ \\ _ __\n");
printf("| | | |/ _ \\/ __| '__| | | | '_ \\| __| | | | '__|\n");
printf("| |_| | __/ (__| | | |_| | |_) | |_| |_| | |\n");
printf("|____/ \\___|\\___|_| \\__, | .__/ \\__|\\___/|_|\n");
printf(" |___/|_| by matteyeux\n\n");
}
void init_process (){
/* TODO
* - Check if bin directory is not missing (including all bins)
*/
}
int im4p = 0;
int check4im4p (char *name)
{
char begin_file[12], filetype[5];
int fd=0, nb;
memset(begin_file, 0, 12);
memset(filetype, 0, 5);
fd = open(name, O_RDONLY);
if (fd == -1)
{
printf("Could not open %s : %s\n", name, strerror(errno));
exit(1);
}
nb = read(fd, begin_file, 11);
strncpy(filetype, begin_file+7, 4);
printf("%s\n",filetype);
if(strcmp(filetype, "IM4P")==0)
{
im4p = 1;
}
else {
strncpy(filetype, begin_file+0, 4);
if (strcmp(filetype, "3gmI")==0)
{
im4p = 0;
printf("%s\n",filetype);
}
else {
printf("%s is not an IM4P nor an IMG3 file\n", name);
exit(1);
}
}
close(fd);
return 0;
}
int unziper()
{
char choice[10];
char firmware[1024];
char buildCommand[1024];
printf("\n\nDecompress firmware ?\n");
printf("1) YES\n");
printf("2) NO\n");
fget(choice, 10);
if (strcmp(choice, "yes")==0 || strcmp(choice, "1")==0)
{
printf("Drag the ipsw here : ");
fget(firmware, 1024);
printf("Extracting firmware in the IPSW folder...\n");
sprintf(buildCommand, "bin\\7z.exe x -oIPSW %s", firmware);
system(buildCommand);
}
else if (strcmp(choice, "no")== 0 || strcmp(choice, "2")==0 )
{
//HAXX
}
return 0;
}
int ipswDownloader()
{
char model[10];
char choice1[10];
char version[7];
char link[1024];
char rep2[3];
char firmware [80];
printf("Download firmware ?\n");
printf("1) YES\n");
printf("2) NO\n");
fget(choice1, 10);
if (strcmp(choice1, "yes")==0 || strcmp(choice1, "1")==0)
{
printf("Model : ");
fget(model, 10);
printf("Version : ");
fget(version, 7);
printf("The firmware will be automaticaly extracted\n");
printf("Downloading IPSW, please wait...\n");
sprintf(link,"wget http://api.ipsw.me/v2/%s/%s/url/dl -O firmware.ipsw",model,version);
/*sprintf(link,"bin\\wget.exe http://api.ipsw.me/v2/%s/%s/url/dl -O firmware.ipsw",model,version);*/
system(link);
system("bin\\7z.exe x -oIPSW firmware.ipsw");
return 0;
}
else if(strcmp(choice1, "no")==0 || strcmp(choice1, "2")==0)
{
printf("\n");
}
return 0;
}
int rootfs()
{
char choice[10];
char rootfs[80];
char buildCommand[1024];
char buildCommand2[1024];
char key[80];
char keyiv[80];
char decrypt[256];
unziper();
printf("Entrer rootfs name : ");
fget(rootfs, 80);
chdir("IPSW");
printf("Enter the firmware key : ");
fget(key, 80);
sprintf(decrypt, "..\\bin\\dmg.exe extract %s rootfs_decrypt.dmg -k %s", rootfs, key);
system(decrypt);
printf("Decrypting finished\n");
sleep(2);
printf("Do you want to reencrypt the firmware ? \n");
printf("1) YES\n");
printf("2) NO\n");
fget(choice, 10);
if (strcmp(choice, "yes")==0 || strcmp(choice, "1")==0)
{
printf("Building rootfs...\n");
sprintf(buildCommand2, "%s", rootfs);
remove(buildCommand2);
sprintf(buildCommand,"..\\bin\\dmg.exe build rootfs_decrypt.dmg %s", rootfs);
system(buildCommand);
printf("Compressing IPSW...\n");
system("..\\bin\\7z.exe u -tzip -mx0 custom_firmware.ipsw -x!7z.exe");
printf("Your custom firmware has been created\n");
}
else if(strcmp(choice, "no")==0 || strcmp(choice, "2")==0)
{
return EXIT_SUCCESS;
}
return 0;
}
int Ramdisk() //Not a priority yet I'll work on after Christmas
{
char name[120];
char buildCommand[1024];
char key[80];
char keyiv[80];
unziper();
chdir("IPSW");
printf("Enter the Ramdisk name : ");
fget(name, 120);
if (fopen(name,"r")==NULL){
printf("File %s is missing\n", name);
exit(1);
}
printf("Enter key for Ramdisk : ");
fget(key, 80);
printf("Enter the IV key for the Update Ramdisk : ");
fget(keyiv, 80);
sprintf(buildCommand, "..\\bin\\xpwntool IPSW\\%s %s.dec -k %s -iv %s ", name, name, key, keyiv);
system(buildCommand);
printf("%s.dec copied at the folder's root\n", name);
return 0;
}
int IMG3()
{
char name[120], buildCommand[1024], key[80], keyiv[80], boardID[10], img3_dir[1024];
unziper();
printf("Board ID (e.g n49ap for iPhone5,4) : ");
fget(boardID, 10);
printf("Enter the IMG3 filename : ");
fget(name, 120);
sprintf(img3_dir,"IPSW/Firmware/all_flash/all_flash.%s.production", boardID);
chdir(img3_dir);
if (fopen(name,"r")==NULL){
printf("File %s is missing\n", name);
exit(1);
}
rename(name, "target");
printf("Enter the key for %s: ", name);
fget(key, 80);
printf("Enter the key IV for %s: ", name);
fget(keyiv, 80);
if (im4p == 0) {
sprintf(buildCommand, "..\\..\\..\\bin\\xpwntool.exe target %s.dec -k %s -iv %s", name, key, keyiv);
}
else if (im4p == 1){
sprintf(buildCommand, "dd if=target bs=52 skip=1 | openssl aes-256-cbc -K %s -iv %s -nopad -d > %s.dec", keyiv, key, name);
}
else {
printf("im4p value : %d\n Wat?", im4p);
}
system(buildCommand);
rename("target", name);
printf("%s.dec created at IPSW/Firmware/all_flash/all_flash.%s.production\n", name, boardID);
return 0;
}
int DFU_file()
{
char name[120];
char buildCommand[1024];
char key[80];
char keyiv[80];
char dfu_dir[80];
unziper();
sprintf(dfu_dir, "IPSW/Firmware/dfu/");
chdir(dfu_dir);
printf("Enter the name of the iBEC/iBSS : ");
fget(name, 120);
if (fopen(name,"r")==NULL){
printf("File %s is missing\n", name);
exit(1);
}
rename(name, "target");
printf("Enter the key for %s: ", name);
fget(key, 80);
printf("Enter the key IV for %s: ", name);
fget(keyiv, 80);
if (im4p == 0) {
sprintf(buildCommand, "..\\..\\..\\bin\\xpwntool.exe target %s.dec -k %s -iv %s", name, key, keyiv);
}
else if (im4p == 1){
sprintf(buildCommand, "dd if=target bs=52 skip=1 | openssl aes-256-cbc -K %s -iv %s -nopad -d > %s.dec", keyiv, key, name);
}
else {
printf("im4p value : %d\n Wat?", im4p);
return -1;
}
system(buildCommand);
rename("target", name);
printf("%s.dec created at IPSW/Firmware/dfu\n", name);
return 0;
}
int kernelcache()
{
char name[120];
char buildCommand[1024];
char key[80];
char keyiv[80];
char boardID[10];
unziper();
chdir("IPSW");
printf("Enter the kernel filename : ");
fget(name, 120);
printf("Enter the key for %s: ", name);
fget(key, 80);
printf("Enter the key IV for %s: ", name);
fget(keyiv, 80);
sprintf(buildCommand, "..\\bin\\xpwntool IPSW\\%s %s.dec -k %s -iv %s",name, name, key, keyiv);
system(buildCommand);
printf("%s.dec copied at the folder's root\n", name);
return 0;
}
int get_keybags()
{
char file_here[1024], buildCommand[1024];
printf("Drag file here : ");
fget(file_here, 1024);
sprintf(buildCommand, "bin\\xpwntool %s nul | cut -f2 -d ' '", file_here);
system(buildCommand);
remove("nul");
return 0;
}
void nBuffer()
{
int c;
while (c != '\n' && c != EOF)
{
c = getchar();
}
}
int fget(char *chain, int sizee)
{
char *charn = NULL;
if (fgets(chain, sizee, stdin) != NULL)
{
charn = strchr(chain, '\n');
if (charn != NULL)
{
*charn = '\0';
}
else
{
nBuffer();
}
return(EXIT_SUCCESS);
}
else
{
nBuffer();
return(EXIT_FAILURE);
}
}
int fgetn()
{
char chain[64];
fget(chain, 64);
return atoi(chain);
}
float fgetf()
{
char chain[64];
fgetf(chain, 64);
return atof(chain);
}
|
the_stack_data/32949600.c
|
#include <stdio.h>
int main()
{
double comprimento, largura, valorq, valorterreno, area;
printf("largura do terreno: ");
scanf("%lf", &largura);
printf("comprimento do terreno: ");
scanf("%lf", &comprimento);
printf("valor do metro quadrado: ");
scanf("%lf", &valorq);
//leitura das variaveis
area = comprimento * largura;
valorterreno = area * valorq;
//manipulando variaveis
printf("area do terreno: %.2lf\n", area);
printf("valor do terreno: %.2lf\n", valorterreno);
//saida de valores
return 0;
}
|
the_stack_data/31388730.c
|
#include <stdio.h>
//Referenciación: Es la obtención de la dirección de una variable
int main() {
int x = 33;
int y;
int *p;
p = &x;
printf("El valor de p es de %d", *p);
y = *p + 10;
printf("El valor de y es %d", y);
return 0;
}
|
the_stack_data/90766565.c
|
/* This testcase is part of GDB, the GNU debugger.
Copyright 2008-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/>. */
/*
Purpose of this test: to test breakpoints on consecutive instructions.
*/
int a[7] = {1, 2, 3, 4, 5, 6, 7};
/* assert: first line of foo has more than one instruction. */
int foo ()
{
return a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + a[6];
}
int
main()
{
foo ();
} /* end of main */
|
the_stack_data/609036.c
|
/* Copyright (C) 2003 Free Software Foundation.
Test equal pointer optimizations don't break anything.
Written by Roger Sayle, July 14, 2003. */
extern void abort ();
typedef __SIZE_TYPE__ size_t;
extern void *memcpy (void *, const void *, size_t);
extern void *mempcpy (void *, const void *, size_t);
extern void *memmove (void *, const void *, size_t);
extern char *strcpy (char *, const char *);
extern int memcmp (const void *, const void *, size_t);
extern int strcmp (const char *, const char *);
extern int strncmp (const char *, const char *, size_t);
void test1 (void *ptr) {
if (memcpy (ptr, ptr, 8) != ptr) abort ();
}
void test2 (char *ptr) {
#if !defined(__APPLE__) && !defined(_WIN32)
if (mempcpy (ptr, ptr, 8) != ptr + 8) abort ();
#endif
}
void test3 (void *ptr) {
if (memmove (ptr, ptr, 8) != ptr) abort ();
}
void test4 (char *ptr) {
if (strcpy (ptr, ptr) != ptr) abort ();
}
void test5 (void *ptr) {
if (memcmp (ptr, ptr, 8) != 0) abort ();
}
void test6 (const char *ptr) {
if (strcmp (ptr, ptr) != 0) abort ();
}
void test7 (const char *ptr) {
if (strncmp (ptr, ptr, 8) != 0) abort ();
}
int main () {
char buf[10];
test1 (buf);
test2 (buf);
test3 (buf);
test4 (buf);
test5 (buf);
test6 (buf);
test7 (buf);
return 0;
}
|
the_stack_data/48576666.c
|
/**********************************************************************\
* To commemorate the 1996 RSA Data Security Conference, the following *
* code is released into the public domain by its author. Prost! *
* *
* This cipher uses 16-bit words and little-endian byte ordering. *
* I wonder which processor it was optimized for? *
* *
* Thanks to CodeView, SoftIce, and D86 for helping bring this code to *
* the public. *
\**********************************************************************/
#include <string.h>
#include <assert.h>
/**********************************************************************\
* Expand a variable-length user key (between 1 and 128 bytes) to a *
* 64-short working rc2 key, of at most "bits" effective key bits. *
* The effective key bits parameter looks like an export control hack. *
* For normal use, it should always be set to 1024. For convenience, *
* zero is accepted as an alias for 1024. *
\**********************************************************************/
void rc2_keyschedule( unsigned short xkey[64],
const unsigned char *key,
unsigned len,
unsigned bits )
{
unsigned char x;
unsigned i;
/* 256-entry permutation table, probably derived somehow from pi */
static const unsigned char permute[256] = {
217,120,249,196, 25,221,181,237, 40,233,253,121, 74,160,216,157,
198,126, 55,131, 43,118, 83,142, 98, 76,100,136, 68,139,251,162,
23,154, 89,245,135,179, 79, 19, 97, 69,109,141, 9,129,125, 50,
189,143, 64,235,134,183,123, 11,240,149, 33, 34, 92,107, 78,130,
84,214,101,147,206, 96,178, 28,115, 86,192, 20,167,140,241,220,
18,117,202, 31, 59,190,228,209, 66, 61,212, 48,163, 60,182, 38,
111,191, 14,218, 70,105, 7, 87, 39,242, 29,155,188,148, 67, 3,
248, 17,199,246,144,239, 62,231, 6,195,213, 47,200,102, 30,215,
8,232,234,222,128, 82,238,247,132,170,114,172, 53, 77,106, 42,
150, 26,210,113, 90, 21, 73,116, 75,159,208, 94, 4, 24,164,236,
194,224, 65,110, 15, 81,203,204, 36,145,175, 80,161,244,112, 57,
153,124, 58,133, 35,184,180,122,252, 2, 54, 91, 37, 85,151, 49,
45, 93,250,152,227,138,146,174, 5,223, 41, 16,103,108,186,201,
211, 0,230,207,225,158,168, 44, 99, 22, 1, 63, 88,226,137,169,
13, 56, 52, 27,171, 51,255,176,187, 72, 12, 95,185,177,205, 46,
197,243,219, 71,229,165,156,119, 10,166, 32,104,254,127,193,173
};
assert(len > 0 && len <= 128);
assert(bits <= 1024);
if (!bits)
bits = 1024;
memcpy(xkey, key, len);
/* Phase 1: Expand input key to 128 bytes */
if (len < 128) {
i = 0;
x = ((unsigned char *)xkey)[len-1];
do {
x = permute[(x + ((unsigned char *)xkey)[i++]) & 255];
((unsigned char *)xkey)[len++] = x;
} while (len < 128);
}
/* Phase 2 - reduce effective key size to "bits" */
len = (bits+7) >> 3;
i = 128-len;
x = permute[((unsigned char *)xkey)[i] & (255 >> (7 & -bits))];
((unsigned char *)xkey)[i] = x;
while (i--) {
x = permute[ x ^ ((unsigned char *)xkey)[i+len] ];
((unsigned char *)xkey)[i] = x;
}
/* Phase 3 - copy to xkey in little-endian order */
i = 63;
do {
xkey[i] = ((unsigned char *)xkey)[2*i] +
(((unsigned char *)xkey)[2*i+1] << 8);
} while (i--);
}
/**********************************************************************\
* Encrypt an 8-byte block of plaintext using the given key. *
\**********************************************************************/
void rc2_encrypt( const unsigned short xkey[64],
const unsigned char *plain,
unsigned char *cipher )
{
unsigned x76, x54, x32, x10, i;
x76 = (plain[7] << 8) + plain[6];
x54 = (plain[5] << 8) + plain[4];
x32 = (plain[3] << 8) + plain[2];
x10 = (plain[1] << 8) + plain[0];
for (i = 0; i < 16; i++) {
x10 += (x32 & ~x76) + (x54 & x76) + xkey[4*i+0];
x10 = (x10 << 1) + (x10 >> 15 & 1);
x32 += (x54 & ~x10) + (x76 & x10) + xkey[4*i+1];
x32 = (x32 << 2) + (x32 >> 14 & 3);
x54 += (x76 & ~x32) + (x10 & x32) + xkey[4*i+2];
x54 = (x54 << 3) + (x54 >> 13 & 7);
x76 += (x10 & ~x54) + (x32 & x54) + xkey[4*i+3];
x76 = (x76 << 5) + (x76 >> 11 & 31);
if (i == 4 || i == 10) {
x10 += xkey[x76 & 63];
x32 += xkey[x10 & 63];
x54 += xkey[x32 & 63];
x76 += xkey[x54 & 63];
}
}
cipher[0] = (unsigned char)x10;
cipher[1] = (unsigned char)(x10 >> 8);
cipher[2] = (unsigned char)x32;
cipher[3] = (unsigned char)(x32 >> 8);
cipher[4] = (unsigned char)x54;
cipher[5] = (unsigned char)(x54 >> 8);
cipher[6] = (unsigned char)x76;
cipher[7] = (unsigned char)(x76 >> 8);
}
/**********************************************************************\
* Decrypt an 8-byte block of ciphertext using the given key. *
\**********************************************************************/
void rc2_decrypt( const unsigned short xkey[64],
unsigned char *plain,
const unsigned char *cipher )
{
unsigned x76, x54, x32, x10, i;
x76 = (cipher[7] << 8) + cipher[6];
x54 = (cipher[5] << 8) + cipher[4];
x32 = (cipher[3] << 8) + cipher[2];
x10 = (cipher[1] << 8) + cipher[0];
i = 15;
do {
x76 &= 65535;
x76 = (x76 << 11) + (x76 >> 5);
x76 -= (x10 & ~x54) + (x32 & x54) + xkey[4*i+3];
x54 &= 65535;
x54 = (x54 << 13) + (x54 >> 3);
x54 -= (x76 & ~x32) + (x10 & x32) + xkey[4*i+2];
x32 &= 65535;
x32 = (x32 << 14) + (x32 >> 2);
x32 -= (x54 & ~x10) + (x76 & x10) + xkey[4*i+1];
x10 &= 65535;
x10 = (x10 << 15) + (x10 >> 1);
x10 -= (x32 & ~x76) + (x54 & x76) + xkey[4*i+0];
if (i == 5 || i == 11) {
x76 -= xkey[x54 & 63];
x54 -= xkey[x32 & 63];
x32 -= xkey[x10 & 63];
x10 -= xkey[x76 & 63];
}
} while (i--);
plain[0] = (unsigned char)x10;
plain[1] = (unsigned char)(x10 >> 8);
plain[2] = (unsigned char)x32;
plain[3] = (unsigned char)(x32 >> 8);
plain[4] = (unsigned char)x54;
plain[5] = (unsigned char)(x54 >> 8);
plain[6] = (unsigned char)x76;
plain[7] = (unsigned char)(x76 >> 8);
}
|
the_stack_data/184518447.c
|
#include <stddef.h>
static int
utf8_decode_t1(int *x, const char *s, int n)
{
int i;
for (i = 1; i < n; i++) {
if ((*s & 0xc0) != 0x80)
return -1;
*x <<= 6;
*x |= *s++ & 0x7f;
}
return n;
}
int
utf8_decode(int *x, const char *s)
{
if ((*s & 0x80) == 0) {
*x = *s & 0x7f;
return 1;
}
if ((*s & 0xe0) == 0xc0) {
*x = *s & 0x1f;
return utf8_decode_t1(x, s + 1, 2);
}
if ((*s & 0xf0) == 0xe0) {
*x = *s & 0x0f;
return utf8_decode_t1(x, s + 1, 3);
}
if ((*s & 0xf1) == 0xf0) {
*x = *s & 0x07;
return utf8_decode_t1(x, s + 1, 4);
}
return -1;
}
|
the_stack_data/954918.c
|
/*
Copyright (c) 1995-2021 by Arkkra Enterprises.
All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that
the following conditions are met:
1. Redistributions of source code must retain
the above copyright notice, this list of conditions
and the following DISCLAIMER.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and
the following DISCLAIMER in the documentation and/or
other materials provided with the distribution.
3. Any additions, deletions, or changes to the original files
must be clearly indicated in accompanying documentation,
including the reasons for the changes,
and the names of those who made the modifications.
DISCLAIMER
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 THE AUTHORS 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.
*/
/* This file contains functions for displaying Mup output on screen
* via Ghostscript, using the Watcom C for Windows.
*/
#ifdef __WATCOMC__
#include "mupdisp.h"
#include <graph.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
#include <conio.h>
#include <fcntl.h>
#include <io.h>
/* hard code X and Y sizes for the moment */
#define XSIZE 640
#define YSIZE 480
/* image to be calloc'ed has 6 header bytes, then each row consecutively */
#define BITS2BYTES(bits) (((bits) + 7) / 8) /* round upwards */
#define SIZEIMAGE (6 + ((long)BITS2BYTES(XSIZE)*4) * (long)YSIZE)
static char *Image;
static void zapblock P((char *area, long size));
/* initialize graphics driver, etc */
void
dos_setup()
{
struct videoconfig vidinfo;
/* initalize best graphics mode */
if (_setvideomode(_VRES16COLOR) == 0) {
fprintf(stderr, "can't set graphics mode\n");
generalcleanup(1);
}
_getvideoconfig(&vidinfo);
if (vidinfo.numxpixels != XSIZE || vidinfo.numypixels != YSIZE) {
_setvideomode(_DEFAULTMODE);
fprintf(stderr, "video mode %dx%d not supported\n",
vidinfo.numxpixels, vidinfo.numypixels);
generalcleanup(0);
}
/*
* Allocate the image buffer. Note that both parameters must be less
* than 65536, but the total size (product) can be greater. The +1
* is to allow room for the header bytes (and then some).
*/
Image = (char *)calloc(BITS2BYTES(YSIZE)*4 + 1, XSIZE);
if (Image == NULL) {
_setvideomode(_DEFAULTMODE);
fprintf(stderr, "can't allocate image buffer\n");
generalcleanup(0);
}
/* set aspect ratio adjust */
Conf_info_p->adjust = 1.375 * (double) vidinfo.numypixels
/ (double) vidinfo.numxpixels;
Conf_info_p->vlines = vidinfo.numypixels;
/* set screen to all white */
_setbkcolor(_BRIGHTWHITE);
_clearscreen(_GCLEARSCREEN);
}
/* before exiting, clean up graphics, then call the general cleanup routine */
void
dos_cleanup(int status)
{
_setvideomode(_DEFAULTMODE);
generalcleanup(status);
}
/* draw a screen worth of the bitmap, starting at specified raster line */
void
dos_draw(line, small)
int line; /* start at this raster line */
int small; /* YES or NO for small or large page image */
{
int r; /* row index */
long offset; /* into bitmap file */
int fd; /* file descriptor */
int himage_bytes; /* horizontal image bytes */
char *row_ptr; /* point at a row of the image */
int n; /* loop variable */
/* make sure we have a valid page to draw */
if (Currpage_p == (struct Pginfo *) 0) {
( *(Conf_info_p->error) ) ("page # out of range");
return;
}
/* figure out where in the bitmap file this page is */
offset = Currpage_p->seqnum * BYTES_PER_PAGE;
fd = gen1file(small);
lseek(fd, offset + (long)line * BYTES_PER_LINE, SEEK_SET);
/* zero out the image buffer */
zapblock(Image, SIZEIMAGE);
/* number of bytes representing one horizontal row in full page image */
himage_bytes = BITS2BYTES(XSIZE) * 4;
/* set the header bytes in the image */
Image[0] = XSIZE % 256;
Image[1] = XSIZE / 256;
Image[2] = YSIZE % 256;
Image[3] = YSIZE / 256;
Image[4] = 4;
Image[5] = 0;
/* set screen to all white */
_setbkcolor(_BRIGHTWHITE);
_clearscreen(_GCLEARSCREEN);
/* for each row */
for (r = 0; r < Conf_info_p->vlines; r++) {
/* read it directly into the image */
row_ptr = &Image[ 6 + r * himage_bytes ];
if (read(fd, row_ptr, BYTES_PER_LINE) != BYTES_PER_LINE) {
break;
}
if (small) {
/* black out the unused strip on the right */
for (n = BITS_PER_LINE; n < XSIZE; n++)
row_ptr[n/8] |= 1 << (7 - n%8);
}
}
/* put at upper left corner, (0, 0) */
_putimage(0, 0, Image, _GPSET);
}
/* for now we just beep on errors */
/*ARGSUSED*/
void
dos_error(msg)
char *msg;
{
putc('\7', stderr);
}
/* for user interface, call command processor for each character read */
void
dos_user_interf()
{
int c;
int special = 0; /* 1 = got a null, which is first character
* of special key sequence */
for ( ; ; ) {
c = getch();
if (c == '\0') {
special = 1;
continue;
}
if (special == 1) {
switch (c) {
case 0x49:
/* PgUp key */
c = 'p';
break;
case 0x51:
/* PgDown key */
c = 'n';
break;
case 0x48:
/* Up arrow key */
c = 'b';
break;
case 0x50:
/* Down arrow key */
c = 'f';
break;
default:
special = 0;
continue;
}
}
do_cmd(c);
special = 0;
}
}
/* display a raster centered on window */
void
dos_raster(bitmap, width, height)
unsigned char *bitmap; /* what to display */
int width, height; /* of bitmap, width is in bytes */
{
int r, c; /* row and column indices */
int b; /* index through bits */
int x, y; /* upper left corner of where to put bitmap,
* x in bytes */
int himage_bytes; /* bytes needed for one row in image */
int n; /* loop variable */
char *row_ptr; /* point at a row of the image */
himage_bytes = 4 * width;
/* figure out how to center on screen */
x = (BYTES_PER_LINE - width) / 2 * 8;
y = (Conf_info_p->vlines - height) / 2;
/* zero out the image buffer */
zapblock(Image, SIZEIMAGE);
/* set the header bytes in the image */
Image[0] = (width * 8) % 256;
Image[1] = (width * 8) / 256;
Image[2] = height % 256;
Image[3] = height / 256;
Image[4] = 4;
Image[5] = 0;
/* for each row */
for (r = 0; r < height; r++) {
row_ptr = &Image[ 6 + r * himage_bytes ];
for (c = 0; c < width; c++) {
for (b = 0; b < 8; b++) {
if (bitmap[r*width+c] & (1 << (7-b))) {
/* white (15); set 4 copies of bit */
for (n = 0; n < 4; n++)
row_ptr[n*width + c] |=
(1 << (7-b));
} else {
/* black (8); set only the first */
row_ptr[c] |= (1 << (7-b));
}
}
}
}
_putimage(x, y, Image, _GPSET);
}
/* zero out a block of memory that may be bigger than 32K */
#define BLOCKSIZE 0x3fff
static void
zapblock(area, size)
char *area;
long size;
{
long k;
/*
* memset's third parm is "unsigned int", so we can't do the whole
* area at once.
*/
for (k = 0; k < size; k += BLOCKSIZE) {
if (size - k >= BLOCKSIZE)
(void)memset(&area[k], 0, BLOCKSIZE);
else
(void)memset(&area[k], 0, size - k);
}
}
#else
/* some compilers don't like empty files, so if __WATCOMC__ isn't defined,
* put something here to keep those compilers happy */
/* Originally used:
* static short dummy;
* but then gcc stated complaining that was unused.
* So try this to try to keep both happy...
*/
void dummy_dos_func_to_avoid_empty_file_warning()
{
}
#endif
|
the_stack_data/173579391.c
|
#include <stdio.h>
#include <stdlib.h>
#define ll long long
#define f(i,a,b) for(ll i=a;i<b;i++)
#define fd(i,b,a) for(ll i=b;i>=a;i--)
#define nl '\n'
struct node
{
int data;
struct node* left;
struct node* right;
};
typedef struct node node;
node* append(node* leftlist, node* rightlist)
{
if(!leftlist)
return rightlist;
if(!rightlist)
return leftlist;
node* leftlast = leftlist->left;
node* rightlast = rightlist->left;
leftlast->right = rightlist;
rightlist->left = leftlast;
leftlist->left = rightlast;
rightlast->right = leftlist;
return leftlist;
}
node* convertTreetoList(node* root)
{
if(!root) return NULL;
node* left = convertTreetoList(root->left);
node* right = convertTreetoList(root->right);
root->left = root->right = root;
return append(append(left, root), right);
}
node* insert(int data)
{
node* temp = (node*)malloc(sizeof(node));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
void traverse(node* head)
{
printf("Circular Linked List is :\n");
node* i = head;
do
{
if(head!=i->right) printf("%d->", i->data);
else printf("%d",i->data);
i = i->right;
} while(head!=i);
printf("\n");
}
int main()
{
node* root = insert(4);
root->left = insert(2);
root->right = insert(6);
root->left->left = insert(1);
root->left->right = insert(3);
root->right->left = insert(5);
root->right->right = insert(7);
node* head = convertTreetoList(root);
traverse(head);
return 0;
}
|
the_stack_data/79982.c
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <arpa/inet.h>
#define PORT 9600
#define BUF_SIZE 128
int main(int argc, char *argv[]) {
int server_fd = socket(PF_INET, SOCK_DGRAM, 0);
if (server_fd < 0) {
fprintf(stderr, "Cannot create socket\n");
return 1;
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
int ok = inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
if (!ok) {
fprintf(stderr, "Cannot parse IP address\n");
return 1;
}
int err = bind(server_fd, (struct sockaddr *) &server_addr, sizeof(server_addr));
if (err != 0) {
fprintf(stderr, "Cannot bind server\n");
return 1;
}
printf("Server listening on port %d\n", PORT);
char buf[BUF_SIZE];
ssize_t n;
struct sockaddr_in client_addr;
socklen_t client_addr_len;
while (1) {
n = recvfrom(server_fd, &buf, sizeof(buf)-1, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (n < 0) {
fprintf(stderr, "Cannot read from socket\n");
return 1;
}
if (n == 0) {
continue; // EOF
}
buf[n] = '\0';
printf("Received: %s\n", buf);
}
}
|
the_stack_data/97012443.c
|
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
void write_sprr(uint64_t v)
{
__asm__ __volatile__("msr s3_4_C15_C2_7, %0\n"
"isb sy\n" ::"r"(v)
:);
}
uint64_t read_sprr(void)
{
uint64_t v;
__asm__ __volatile__("isb sy\n"
"mrs %0, s3_4_C15_C2_7\n"
: "=r"(v)::"memory");
return v;
}
int main(int argc, char *argv[])
{
for (int i = 0; i < 64; ++i) {
printf("s3_4_C15_C2_7 bit %02d: %016llx\n", i, read_sprr());
}
}
|
the_stack_data/10048.c
|
#include <semaphore.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_PHIL 5
#define NUM_FORK 5
sem_t forks[NUM_FORK];
int randomInRange(int min, int max){
return min + random()%(max-min+1);
}
void *life(void *threadid)
{
long tid;
tid = (long)threadid;
srand((tid+1)*time(NULL));
while(1){
printf("Soy el phil %ld y quiero mis tenedores \n",tid);
if(tid%2 == 0){
//Tomar izquierdo
sem_wait(&forks[(tid+1)%NUM_FORK]);
//Tomar derecho
sem_wait(&forks[tid]);
}else{
//Tomar derecho
sem_wait(&forks[tid]);
//Tomar izquierdo
sem_wait(&forks[(tid+1)%NUM_FORK]);
}
//Comer
printf("Soy el phil %ld y voy a comer\n", tid);
sleep(randomInRange(5, 25));
//Regresa tenedores
sem_post(&forks[tid]);
sem_post(&forks[(tid+1)%NUM_FORK]);
//Piensa
printf("Soy el phil %ld y voy a pensar\n", tid);
sleep(randomInRange(5, 25));
}
}
int main(int argc, char *argv[])
{
pthread_t philosophers[NUM_PHIL];
int rc;
long t;
for(t=0; t<NUM_FORK;t++){
sem_init(&forks[t], 0, 1);
}
for(t=0;t<NUM_PHIL;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&philosophers[t], NULL, life, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
|
the_stack_data/36486.c
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
typedef struct counter {
int dir_count;
int file_count;
} counter_t;
counter_t* counter_build(void) {
counter_t *counter = (counter_t *) malloc(sizeof(counter_t));
counter->dir_count = 0;
counter->file_count = 0;
return counter;
}
void counter_incr_dirs(counter_t *counter) {
counter->dir_count += 1;
}
void counter_incr_files(counter_t *counter) {
counter->file_count += 1;
}
void counter_free(counter_t *counter) {
free(counter);
}
void bubble_sort(int size, char **entries) {
int x_idx;
int y_idx;
char *swap;
for (x_idx = 0; x_idx < size; x_idx++) {
for (y_idx = 0; y_idx < size - 1; y_idx++) {
if (strcmp(entries[y_idx], entries[y_idx + 1]) > 0) {
swap = entries[y_idx];
entries[y_idx] = entries[y_idx + 1];
entries[y_idx + 1] = swap;
}
}
}
}
int dir_entry_count(const char* directory) {
DIR *dir_handle = opendir(directory);
if (dir_handle == NULL) {
printf("Cannot open directory \"%s\"\n", directory);
return -1;
}
int count = 0;
struct dirent *file_dirent;
char *entry_name;
while ((file_dirent = readdir(dir_handle)) != NULL) {
entry_name = file_dirent->d_name;
if (entry_name[0] == '.') {
continue;
}
count++;
}
closedir(dir_handle);
return count;
}
char *join(const char* left, const char* right) {
char *result = malloc(strlen(left) + strlen(right) + 1);
strcpy(result, left);
strcat(result, right);
return result;
}
char *path_join(const char* directory, const char* entry) {
char *result = malloc(strlen(directory) + strlen(entry) + 2);
strcpy(result, directory);
strcat(result, "/");
strcat(result, entry);
return result;
}
int is_dir(const char* entry) {
struct stat entry_stat;
stat(entry, &entry_stat);
return S_ISDIR(entry_stat.st_mode);
}
int walk(const char* directory, const char* prefix, counter_t* counter) {
int entry_count = dir_entry_count(directory);
if (entry_count == -1) {
return -1;
}
int entry_idx = 0;
struct dirent *file_dirent;
DIR *dir_handle = opendir(directory);
char *entry_name;
char **entries = malloc(sizeof(char *) * entry_count);
counter_incr_dirs(counter);
while ((file_dirent = readdir(dir_handle)) != NULL) {
entry_name = file_dirent->d_name;
if (entry_name[0] == '.') {
continue;
}
entries[entry_idx++] = entry_name;
}
closedir(dir_handle);
bubble_sort(entry_count, entries);
char *full_path;
char *prefix_ext;
char *pointer;
for (entry_idx = 0; entry_idx < entry_count; entry_idx++) {
if (entry_idx == entry_count - 1) {
pointer = "└── ";
prefix_ext = " ";
} else {
pointer = "├── ";
prefix_ext = "│ ";
}
printf("%s%s%s\n", prefix, pointer, entries[entry_idx]);
full_path = path_join(directory, entries[entry_idx]);
if (is_dir(full_path)) {
prefix_ext = join(prefix, prefix_ext);
walk(full_path, prefix_ext, counter);
free(prefix_ext);
} else {
counter_incr_files(counter);
}
free(full_path);
}
free(entries);
return 0;
}
int main(int argc, char *argv[]) {
char* directory = ".";
if (argc > 1) {
directory = argv[1];
}
printf("%s\n", directory);
counter_t *counter = counter_build();
walk(directory, "", counter);
printf("\n%d directories, %d files\n", counter->dir_count - 1, counter->file_count);
counter_free(counter);
return 0;
}
|
the_stack_data/119671.c
|
#include <math.h>
float gammln(float xx)
{
double x,y,tmp,ser;
static double cof[6]={76.18009172947146,-86.50532032941677,
24.01409824083091,-1.231739572450155,
0.1208650973866179e-2,-0.5395239384953e-5};
int j;
y=x=xx;
tmp=x+5.5;
tmp -= (x+0.5)*log(tmp);
ser=1.000000000190015;
for (j=0;j<=5;j++) ser += cof[j]/++y;
return -tmp+log(2.5066282746310005*ser/x);
}
|
the_stack_data/154828956.c
|
//
// Created by zing on 2018/2/14.
//
#include <stdio.h>
#include <stdlib.h>
int main() {
long int li;
char buffer[256];
printf("Enter a long number: ");
fgets(buffer, 256, stdin);
li = atol(buffer);
printf("The value entered is %ld. Its double is %ld.\n", li, li * 2);
printf("%ld\n", atol("-123zing"));
printf("%ld\n", atol("0"));
printf("%ld\n", atol("zing")); // 无可进行的转换
printf("%ld\n", atol("2147483648")); // UB :在 int 范围外 2147483648
return 0;
}
|
the_stack_data/738649.c
|
//
// Created by Rahul on 6/25/2019.
//
#include <stdio.h>
int strllen(char s[])
{
int i;
for(i=0;s[i]!='\0';i++);
return i;
}
void reverse(char s[])
{
int c,i,j;
for(i=0,j=strllen(s)-1;i<j;i++,j--)
{
c=s[i];
s[i]=s[j];
s[j]=c;
}
}
void itob(int n,char s[],int b)
{
int i,j,sign;
void reverse(char s[]); //reverse functoin prototype
if((sign=n)<0)
sign=-n; /*record sign make n positive */
i=0;
do {
j = n % b;
s[i++] = (j <= 9) ? j + '0':j + 'A' - 10;
}
while((n/=b)>0);
if(sign<0)
{
s[i++]='-';
s[i]='\0';
}
reverse(s);
}
int main()
{
char s[100];
itob(200,s,16);
printf("%s",s);
}
|
the_stack_data/243893878.c
|
static void foo(int i)
{
int foo;
void * p = (void *) &foo;
/* This is the static version in foo.c */
i++;
printf("This is the static version in foo.c\n");
}
void bar(int i)
{
foo(i);
if(i) {
/* This declaration has no impact on gcc compiled code: the local foo is called */
extern void foo(int i);
foo(i);
}
}
|
the_stack_data/140765684.c
|
/*
*Name: Nikhil Ranjan Nayak
*Regd No: 1641012040
*Desc: Semaphore A
*/
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
//#define KEY (1492)
void main()
{
int id;
struct sembuf operations[1];
int retval;
int KEY = ftok("prog1.c", 65);
id = semget(KEY, 1, 0666 | IPC_CREAT);
if(id < 0)
{
fprintf(stderr, "Program sema cannot find semaphore, exiting.\n");
exit(0);
}
printf("Program sem A about to do a V-operation. \n");
operations[0].sem_num = 0;
operations[0].sem_op = 1;
operations[0].sem_flg = 0;
retval = semop(id, operations, 1);
if(retval == 0)
{
printf("Successful V-operation by program sema.\n");
}
else
{
printf("sema: V-operation did not succeed.\n");
perror("REASON");
}
}
|
the_stack_data/131121.c
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<time.h>
double dist[48][48];
double aleatorioEntero(int li, int ls);
double aleatorio();
int probabilidad(double visi[], double fero[], int vector[], int cities);
void gettingMatrix();
void printMatrix();
int main(){
//Funcion principal
int i, j, cities, ants, condition, iter;
cities=48;
ants=1000;
iter=10000;
srand(time(NULL));
int ant[ants][cities+1]; // Inicializa la matriz de distancia (Fila columna)
double fero[cities][cities], visi[cities][cities], prob[cities][cities]; //dist[cities][cities],
double aux,random;
int k,l,m, cityNow, vector[cities],condicion, contador;
double feroIter[cities], visiIter[cities];
double recorrido[ants], best;//evaluacion
best=10000000;
double rho=0.0001, Q=500; //tasa de evaporacion feromona
gettingMatrix();
//printMatrix();
for (i=0; i<cities; i++){
for (j=0; j<cities; j++){
//dist[i][j]=(i+1)*(j+1); //Porcion inical de feromonas
fero[i][j]=0.1;
if(i!=j){
visi[i][j]=500/dist[i][j];
}
else{
visi[i][j]=0;
}
}
}
//-------------------Probability------------
double sumVF;
for (i=0;i<cities;i++){
sumVF=0;
for(j=0;j<cities;j++){
sumVF+=visi[i][j]*fero[i][j];
}
aux=0;
for(j=0;j<cities;j++){
prob[i][j]=((visi[i][j]*fero[i][j])/(sumVF));
}
}
//----------------------------
//------------ Hormiga solucion---------------
for(m=0;m<iter;m++){
for(i=0;i<=cities;i++){
for(j=0;j<=cities;j++){
ant[i][j]=0;
}
}
for(k=0;k<ants;k++){
ant[k][0]=0;//Inicia en la ciudad cero;
random=aleatorio();
aux=0;
ant[k][cities]=0;
for(j=0;j<cities;j++){// inicia el vector con las N ciudades
vector[j]=j;
}
j=1;
do{
aux+=prob[0][j];
if(random<=aux){
ant[k][1]=j;//Selecciona la primera ciudad partiendo de la ciudad inicial
vector[j]=0;//Anula la ciudad del listado
}
j++;
}while(random>aux && j<cities);
//------------------Resto ciudades----------------------
for(i=2;i<cities;i++){
cityNow=ant[k][i-1];
contador=0;
for(j=0;j<cities;j++){
feroIter[j]=fero[cityNow][j];
visiIter[j]=visi[cityNow][j];
}
ant[k][i]=probabilidad(visiIter, feroIter, vector, cities);
vector[ant[k][i]]=0;
}
//-----------------------------------------------------------
}
//-------------- Evaluacion de las soluciones ---------------
for(k=0;k<ants;k++){
recorrido[k]=0;
for(i=0;i<cities+1;i++){
recorrido[k]+=dist[ant[k][i]][ant[k][i+1]];
}
if(recorrido[k]<best){
best=recorrido[k];
printf("\n El mejor = %.lf la hormina %i iteracion %i", best,k,m);
}
}
//----------------- Actualizacion de las feromonas
for(k=0;k<ants;k++){
for(i=0;i<cities;i++){
fero[ant[k][i]][ant[k][i+1]]+=Q/recorrido[k];
fero[ant[k][i+1]][ant[k][i]]+=Q/recorrido[k];
}
}
for(i=0;i<cities;i++){
for(j=0;j<cities;j++){
fero[i][j]=fero[i][j]*(1-rho);
if(fero[i][j]<0.01){
fero[i][j]=0.01;
}
}
}
}//fin de iteraciones
//------------------------------------------
return 0;
}
double aleatorioEntero(int li, int ls){
double numero;
srand(time(NULL));
numero=li+rand() % ((ls+1)-1);
return numero;
}
double aleatorio(){
//srand(time(NULL));
return (double)rand() / (double)RAND_MAX ;
}
int probabilidad(double visi[], double fero[], int vector[], int cities){
int i, j, city, condicion, contador;
double sumVF, aux, probRel, number;
sumVF=0;
contador=0;
for(j=0;j<cities;j++){
if(vector[j]!=0){
sumVF+=visi[j]*fero[j];
}
if(fero[j]<=0.000001){
contador++;
}
}
number=aleatorio();
aux=0;
city=-1;
condicion=0;
j=0;
while(j<cities && condicion==0){
if(vector[j]!=0){
probRel=(visi[j]*fero[j])/(sumVF);
aux+=probRel;
if(aux!=aux|| aux==INFINITY){
for(i=0;i<cities;i++){
printf("\n visibilidad %.6lf || fero %.6lf || suma %.6lf ||%i", visi[i],fero[i],sumVF,contador);
}
exit(-1);
}
if(number<=aux+0.0001){
//printf("%.3lf || %.6lf\n",number, aux);
city=j;
condicion=1;
}
}
j++;
}
if(city==-1){
printf("NO asigno");
printf("\n %.8lf - %.8lf iter=%i",aux, number,j-1);
exit(-1);
}
return city;
}
void gettingMatrix(){
int i, j;
FILE *inputFile;
inputFile= fopen("matrix.txt", "r");
char help[300], *token;
i=0;
while(!feof(inputFile)){
fscanf(inputFile, "%s", help);
token=strtok(help,",");
j=0;
while(token != NULL){
dist[i][j]=atof(token);
token=strtok(NULL, ",");
j++;
}
i++;
}
}
void printMatrix(){
int i, j;
for(i=0; i<48;i++){
for(j=0;j<48;j++){
printf("%.lf ",dist[i][j]);
}
printf("\n");
}
}
|
the_stack_data/116667.c
|
//---------------------------------------------------------------------
// program IS
//---------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#if !defined(CLASS_W) && !defined(CLASS_S) && !defined(CLASS_A) && !defined(CLASS_B) && !defined(CLASS_C) && !defined(CLASS_D) && !defined(CLASS_E)
# define CLASS_W
#endif
//----------
// Class S:
//----------
#ifdef CLASS_S
# define TOTAL_KEYS_LOG_2 16
# define MAX_KEY_LOG_2 11
# define NUM_BUCKETS_LOG_2 9
# define CLASS 'S'
#endif
//----------
// Class W:
//----------
#ifdef CLASS_W
# define TOTAL_KEYS_LOG_2 20
# define MAX_KEY_LOG_2 16
# define NUM_BUCKETS_LOG_2 10
# define CLASS 'W'
#endif
//----------
// Class A:
//----------
#ifdef CLASS_A
# define TOTAL_KEYS_LOG_2 23
# define MAX_KEY_LOG_2 19
# define NUM_BUCKETS_LOG_2 10
# define CLASS 'A'
#endif
//----------
// Class B:
//----------
#ifdef CLASS_B
# define TOTAL_KEYS_LOG_2 25
# define MAX_KEY_LOG_2 21
# define NUM_BUCKETS_LOG_2 10
# define CLASS 'B'
#endif
//----------
// Class C:
//----------
#ifdef CLASS_C
# define TOTAL_KEYS_LOG_2 27
# define MAX_KEY_LOG_2 23
# define NUM_BUCKETS_LOG_2 10
# define CLASS 'C'
#endif
//----------
// Class D:
//----------
#ifdef CLASS_D
# define TOTAL_KEYS_LOG_2 31
# define MAX_KEY_LOG_2 27
# define NUM_BUCKETS_LOG_2 10
# define CLASS 'D'
#endif
#if CLASS == 'D'
#define TOTAL_KEYS (1L << TOTAL_KEYS_LOG_2)
#else
#define TOTAL_KEYS (1 << TOTAL_KEYS_LOG_2)
#endif
#define MAX_KEY (1 << MAX_KEY_LOG_2)
#define NUM_BUCKETS (1 << NUM_BUCKETS_LOG_2)
#define NUM_KEYS TOTAL_KEYS
#define SIZE_OF_BUFFERS NUM_KEYS
#define MAX_ITERATIONS 10
#define TEST_ARRAY_SIZE 5
/*************************************/
/* Typedef: if necessary, change the */
/* size of int here by changing the */
/* int type to, say, long */
/*************************************/
#if CLASS == 'D'
typedef long INT_TYPE;
#else
typedef int INT_TYPE;
#endif
typedef struct
{
double real;
double imag;
} dcomplex;
#define min(x,y) ((x) < (y) ? (x) : (y))
#define max(x,y) ((x) > (y) ? (x) : (y))
/********************/
/* Some global info */
/********************/
INT_TYPE *key_buff_ptr_global; /* used by full_verify to get */
/* copies of rank info */
int passed_verification;
/************************************/
/* These are the three main arrays. */
/* See SIZE_OF_BUFFERS def above */
/************************************/
INT_TYPE key_array[SIZE_OF_BUFFERS],
key_buff1[MAX_KEY],
key_buff2[SIZE_OF_BUFFERS],
partial_verify_vals[TEST_ARRAY_SIZE];
#ifdef USE_BUCKETS
INT_TYPE bucket_size[NUM_BUCKETS],
bucket_ptrs[NUM_BUCKETS];
#endif
/**********************/
/* Partial verif info */
/**********************/
INT_TYPE test_index_array[TEST_ARRAY_SIZE],
test_rank_array[TEST_ARRAY_SIZE],
S_test_index_array[TEST_ARRAY_SIZE] =
{48427, 17148, 23627, 62548, 4431},
S_test_rank_array[TEST_ARRAY_SIZE] =
{0, 18, 346, 64917, 65463},
W_test_index_array[TEST_ARRAY_SIZE] =
{357773, 934767, 875723, 898999, 404505},
W_test_rank_array[TEST_ARRAY_SIZE] =
{1249, 11698, 1039987, 1043896, 1048018},
A_test_index_array[TEST_ARRAY_SIZE] =
{2112377, 662041, 5336171, 3642833, 4250760},
A_test_rank_array[TEST_ARRAY_SIZE] =
{104, 17523, 123928, 8288932, 8388264},
B_test_index_array[TEST_ARRAY_SIZE] =
{41869, 812306, 5102857, 18232239, 26860214},
B_test_rank_array[TEST_ARRAY_SIZE] =
{33422937, 10244, 59149, 33135281, 99},
C_test_index_array[TEST_ARRAY_SIZE] =
{44172927, 72999161, 74326391, 129606274, 21736814},
C_test_rank_array[TEST_ARRAY_SIZE] =
{61147, 882988, 266290, 133997595, 133525895},
D_test_index_array[TEST_ARRAY_SIZE] =
{1317351170, 995930646, 1157283250, 1503301535, 1453734525},
D_test_rank_array[TEST_ARRAY_SIZE] =
{1, 36538729, 1978098519, 2145192618, 2147425337};
/***********************/
/* function prototypes */
/***********************/
double randlc( double *X, double *A );
void full_verify( void );
void c_print_results( char *name, char class, int n1, int n2, int n3, int niter,
double t, double mops, char *optype, int passed_verification);
double start[64], elapsed[64];
double elapsed_time( void );
void timer_clear( int n );
void timer_start( int n );
void timer_stop( int n );
double timer_read( int n );
void wtime(double *t);
/*****************************************************************/
/************* R A N D L C ************/
/************* ************/
/************* portable random number generator ************/
/*****************************************************************/
double randlc( double *X, double *A )
{
int KS = 0;
double R23, R46, T23, T46;
double T1, T2, T3, T4;
double A1;
double A2;
double X1;
double X2;
double Z;
int i, j;
if (KS == 0)
{
R23 = 1.0;
R46 = 1.0;
T23 = 1.0;
T46 = 1.0;
for (i = 1; i <= 23; i++)
{
R23 = 0.50 * R23;
T23 = 2.0 * T23;
}
for (i = 1; i <= 46; i++)
{
R46 = 0.50 * R46;
T46 = 2.0 * T46;
}
KS = 1;
}
/* Break A into two parts such that A = 2^23 * A1 + A2 and set X = N. */
T1 = R23 * *A;
j = T1;
A1 = j;
A2 = *A - T23 * A1;
/* Break X into two parts such that X = 2^23 * X1 + X2, compute
Z = A1 * X2 + A2 * X1 (mod 2^23), and then
X = 2^23 * Z + A2 * X2 (mod 2^46). */
T1 = R23 * *X;
j = T1;
X1 = j;
X2 = *X - T23 * X1;
T1 = A1 * X2 + A2 * X1;
j = R23 * T1;
T2 = j;
Z = T1 - T23 * T2;
T3 = T23 * Z + A2 * X2;
j = R46 * T3;
T4 = j;
*X = T3 - T46 * T4;
return (R46 * *X);
}
/*****************************************************************/
/************* C R E A T E _ S E Q ************/
/*****************************************************************/
void create_seq( double seed, double a )
{
double x;
INT_TYPE i, k;
k = MAX_KEY / 4;
for (i = 0; i < NUM_KEYS; i++)
{
x = randlc(&seed, &a);
x += randlc(&seed, &a);
x += randlc(&seed, &a);
x += randlc(&seed, &a);
key_array[i] = k * x;
}
}
/*****************************************************************/
/************* F U L L _ V E R I F Y ************/
/*****************************************************************/
void full_verify( void )
{
INT_TYPE i, j;
/* Now, finally, sort the keys: */
#ifdef USE_BUCKETS
/* key_buff2[] already has the proper information, so do nothing */
#else
/* Copy keys into work array; keys in key_array will be reassigned. */
for ( i = 0; i < NUM_KEYS; i++ )
key_buff2[i] = key_array[i];
#endif
for ( i = 0; i < NUM_KEYS; i++ )
key_array[--key_buff_ptr_global[key_buff2[i]]] = key_buff2[i];
/* Confirm keys correctly sorted: count incorrectly sorted keys, if any */
j = 0;
for ( i = 1; i < NUM_KEYS; i++ )
if ( key_array[i - 1] > key_array[i] )
j++;
if ( j != 0 )
{
printf( "Full_verify: number of keys out of sort: %ld\n",
(long)j );
}
else
passed_verification++;
}
/*****************************************************************/
/************* R A N K ****************/
/*****************************************************************/
void rank( int iteration )
{
INT_TYPE i, k;
INT_TYPE *key_buff_ptr, *key_buff_ptr2;
#ifdef USE_BUCKETS
int shift = MAX_KEY_LOG_2 - NUM_BUCKETS_LOG_2;
INT_TYPE key;
#endif
key_array[iteration] = iteration;
key_array[iteration + MAX_ITERATIONS] = MAX_KEY - iteration;
/* Determine where the partial verify test keys are, load into */
/* top of array bucket_size */
for ( i = 0; i < TEST_ARRAY_SIZE; i++ )
partial_verify_vals[i] = key_array[test_index_array[i]];
#ifdef USE_BUCKETS
/* Initialize */
for ( i = 0; i < NUM_BUCKETS; i++ )
bucket_size[i] = 0;
/* Determine the number of keys in each bucket */
for ( i = 0; i < NUM_KEYS; i++ )
bucket_size[key_array[i] >> shift]++;
/* Accumulative bucket sizes are the bucket pointers */
bucket_ptrs[0] = 0;
for ( i = 1; i < NUM_BUCKETS; i++ )
bucket_ptrs[i] = bucket_ptrs[i - 1] + bucket_size[i - 1];
/* Sort into appropriate bucket */
for ( i = 0; i < NUM_KEYS; i++ )
{
key = key_array[i];
key_buff2[bucket_ptrs[key >> shift]++] = key;
}
key_buff_ptr2 = key_buff2;
#else
key_buff_ptr2 = key_array;
#endif
/* Clear the work array */
for ( i = 0; i < MAX_KEY; i++ )
key_buff1[i] = 0;
/* Ranking of all keys occurs in this section: */
key_buff_ptr = key_buff1;
/* In this section, the keys themselves are used as their
own indexes to determine how many of each there are: their
individual population */
for ( i = 0; i < NUM_KEYS; i++ )
key_buff_ptr[key_buff_ptr2[i]]++; /* Now they have individual key */
/* population */
/* To obtain ranks of each key, successively add the individual key
population */
for ( i = 0; i < MAX_KEY - 1; i++ )
key_buff_ptr[i + 1] += key_buff_ptr[i];
/* This is the partial verify test section */
/* Observe that test_rank_array vals are */
/* shifted differently for different cases */
for ( i = 0; i < TEST_ARRAY_SIZE; i++ )
{
k = partial_verify_vals[i]; /* test vals were put here */
if ( 0 < k && k <= NUM_KEYS - 1 )
{
INT_TYPE key_rank = key_buff_ptr[k - 1];
int failed = 0;
switch ( CLASS )
{
case 'S':
if ( i <= 2 )
{
if ( key_rank != test_rank_array[i] + iteration )
failed = 1;
else
passed_verification++;
}
else
{
if ( key_rank != test_rank_array[i] - iteration )
failed = 1;
else
passed_verification++;
}
break;
case 'W':
if ( i < 2 )
{
if ( key_rank != test_rank_array[i] + (iteration - 2) )
failed = 1;
else
passed_verification++;
}
else
{
if ( key_rank != test_rank_array[i] - iteration )
failed = 1;
else
passed_verification++;
}
break;
case 'A':
if ( i <= 2 )
{
if ( key_rank != test_rank_array[i] + (iteration - 1) )
failed = 1;
else
passed_verification++;
}
else
{
if ( key_rank != test_rank_array[i] - (iteration - 1) )
failed = 1;
else
passed_verification++;
}
break;
case 'B':
if ( i == 1 || i == 2 || i == 4 )
{
if ( key_rank != test_rank_array[i] + iteration )
failed = 1;
else
passed_verification++;
}
else
{
if ( key_rank != test_rank_array[i] - iteration )
failed = 1;
else
passed_verification++;
}
break;
case 'C':
if ( i <= 2 )
{
if ( key_rank != test_rank_array[i] + iteration )
failed = 1;
else
passed_verification++;
}
else
{
if ( key_rank != test_rank_array[i] - iteration )
failed = 1;
else
passed_verification++;
}
break;
case 'D':
if ( i < 2 )
{
if ( key_rank != test_rank_array[i] + iteration )
failed = 1;
else
passed_verification++;
}
else
{
if ( key_rank != test_rank_array[i] - iteration )
failed = 1;
else
passed_verification++;
}
break;
}
if ( failed == 1 )
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, (int)i );
}
}
/* Make copies of rank info for use by full_verify: these variables
in rank are local; making them global slows down the code, probably
since they cannot be made register by compiler */
if ( iteration == MAX_ITERATIONS )
key_buff_ptr_global = key_buff_ptr;
}
/*****************************************************************/
/************* M A I N ****************/
/*****************************************************************/
int main( int argc, char **argv )
{
int i, iteration;
double timecounter;
FILE *fp;
/* Initialize timers */
timer_clear( 0 );
/* Initialize the verification arrays if a valid class */
for ( i = 0; i < TEST_ARRAY_SIZE; i++ )
switch ( CLASS )
{
case 'S':
test_index_array[i] = S_test_index_array[i];
test_rank_array[i] = S_test_rank_array[i];
break;
case 'A':
test_index_array[i] = A_test_index_array[i];
test_rank_array[i] = A_test_rank_array[i];
break;
case 'W':
test_index_array[i] = W_test_index_array[i];
test_rank_array[i] = W_test_rank_array[i];
break;
case 'B':
test_index_array[i] = B_test_index_array[i];
test_rank_array[i] = B_test_rank_array[i];
break;
case 'C':
test_index_array[i] = C_test_index_array[i];
test_rank_array[i] = C_test_rank_array[i];
break;
case 'D':
test_index_array[i] = D_test_index_array[i];
test_rank_array[i] = D_test_rank_array[i];
break;
};
/* Printout initial NPB info */
printf
( "\n\n NAS Parallel Benchmarks (NPB3.3-SER) - IS Benchmark\n\n" );
printf( " Size: %ld (class %c)\n", (long)TOTAL_KEYS, CLASS );
printf( " Iterations: %d\n", MAX_ITERATIONS );
/* Generate random number sequence and subsequent keys on all procs */
create_seq( 314159265.00, /* Random number gen seed */
1220703125.00 ); /* Random number gen mult */
/* Do one interation for free (i.e., untimed) to guarantee initialization of
all data and code pages and respective tables */
rank( 1 );
/* Start verification counter */
passed_verification = 0;
if ( CLASS != 'S' ) printf( "\n iteration\n" );
/* Start timer */
timer_start( 0 );
/* This is the main iteration */
#pragma kernel
for ( iteration = 1; iteration <= MAX_ITERATIONS; iteration++ )
{
if ( CLASS != 'S' ) printf( " %d\n", iteration );
rank( iteration );
}
/* End of timing, obtain maximum time of all processors */
timer_stop( 0 );
timecounter = timer_read( 0 );
/* This tests that keys are in sequence: sorting of last ranked key seq
occurs here, but is an untimed operation */
full_verify();
/* The final printout */
if ( passed_verification != 5 * MAX_ITERATIONS + 1 )
passed_verification = 0;
c_print_results( "IS",
CLASS,
(int)(TOTAL_KEYS / 64),
64,
0,
MAX_ITERATIONS,
timecounter,
((double) (MAX_ITERATIONS * TOTAL_KEYS))
/ timecounter / 1000000.,
"keys ranked",
passed_verification);
int exitValue = passed_verification ? 0 : 1;
return exitValue;
}
/**************************/
/* E N D P R O G R A M */
/**************************/
void c_print_results( char *name,
char class,
int n1,
int n2,
int n3,
int niter,
double t,
double mops,
char *optype,
int passed_verification )
{
printf( "\n\n %s Benchmark Completed\n", name );
printf( " Class = %c\n", class );
if ( n3 == 0 )
{
long nn = n1;
if ( n2 != 0 ) nn *= n2;
printf( " Size = %12ld\n", nn ); /* as in IS */
}
else
printf( " Size = %4dx%4dx%4d\n", n1, n2, n3 );
printf( " Iterations = %12d\n", niter );
printf( " Time in seconds = %12.2f\n", t );
printf( " Mop/s total = %12.2f\n", mops );
printf( " Operation type = %24s\n", optype);
if ( passed_verification < 0 )
printf( " Verification = NOT PERFORMED\n" );
else if ( passed_verification )
printf( " Verification = SUCCESSFUL\n" );
else
printf( " Verification = UNSUCCESSFUL\n" );
#ifdef SMP
evalue = getenv("MP_SET_NUMTHREADS");
printf( " MULTICPUS = %s\n", evalue );
#endif
}
void wtime(double *t)
{
static int sec = -1;
struct timeval tv;
gettimeofday(&tv, (void *)0);
if (sec < 0) sec = tv.tv_sec;
*t = (tv.tv_sec - sec) + 1.0e-6 * tv.tv_usec;
}
/*****************************************************************/
/****** E L A P S E D _ T I M E ******/
/*****************************************************************/
double elapsed_time( void )
{
double t;
wtime( &t );
return ( t );
}
/*****************************************************************/
/****** T I M E R _ C L E A R ******/
/*****************************************************************/
void timer_clear( int n )
{
elapsed[n] = 0.0;
}
/*****************************************************************/
/****** T I M E R _ S T A R T ******/
/*****************************************************************/
void timer_start( int n )
{
start[n] = elapsed_time();
}
/*****************************************************************/
/****** T I M E R _ S T O P ******/
/*****************************************************************/
void timer_stop( int n )
{
double t, now;
now = elapsed_time();
t = now - start[n];
elapsed[n] += t;
}
/*****************************************************************/
/****** T I M E R _ R E A D ******/
/*****************************************************************/
double timer_read( int n )
{
return ( elapsed[n] );
}
|
the_stack_data/39490.c
|
/** @file
smuggle_client.c
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <openssl/ssl.h>
#include <fcntl.h>
#include <netinet/tcp.h>
const char *req_and_post_buf =
"GET / HTTP/1.1\r\nConnection: close\r\nHost: foo.com\r\nTransfer-Encoding: chunked\r\nContent-Length: 301\r\n\r\n0\r\n\r\nPOST "
"http://sneaky.com/ HTTP/1.1\r\nContent-Length: 10\r\nConnection: close\r\nX-Foo: Z\r\n\r\n1234567890";
/**
* Connect to a server.
* Handshake
* Exit immediatesly
*/
int
main(int argc, char *argv[])
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s, j;
size_t len;
ssize_t nread;
if (argc < 3) {
fprintf(stderr, "Usage: %s <target addr> <target_port>\n", argv[0]);
exit(1);
}
const char *target = argv[1];
const char *target_port = argv[2];
/* Obtain address(es) matching host/port */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
s = getaddrinfo(target, target_port, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
/* getaddrinfo() returns a list of address structures.
* Try each address until we successfully connect(2).
* socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1)
continue;
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
close(sfd);
}
if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Could not connect\n");
exit(EXIT_FAILURE);
}
SSL_CTX *client_ctx = SSL_CTX_new(TLS_method());
SSL *ssl = SSL_new(client_ctx);
SSL_set_fd(ssl, sfd);
int ret = SSL_connect(ssl);
int read_count = 0;
int write_count = 1;
printf("Send request\n");
if ((ret = SSL_write(ssl, req_and_post_buf, strlen(req_and_post_buf))) <= 0) {
int error = SSL_get_error(ssl, ret);
printf("SSL_write failed %d", error);
exit(1);
}
int read_bytes;
do {
char input_buf[1024];
read_bytes = SSL_read(ssl, input_buf, sizeof(input_buf) - 1);
if (read_bytes > 0) {
input_buf[read_bytes] = '\0';
printf("Received %d bytes %s\n", read_bytes, input_buf);
}
} while (read_bytes > 0);
close(sfd);
exit(0);
}
|
the_stack_data/150143232.c
|
#include <stdio.h>
#include <omp.h>
int main(int argc, char **argv)
{
#pragma omp parallel num_threads(6)
{
printf("Hello, multithreaded world: thread %d of %d\n",
omp_get_thread_num(), omp_get_num_threads());
}
return 0;
}
|
the_stack_data/154827940.c
|
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
void write_sprr(uint64_t v)
{
__asm__ __volatile__("msr s3_5_c15_c10_2, %0\n"
"isb sy\n" ::"r"(v)
:);
}
uint64_t read_sprr(void)
{
uint64_t v;
__asm__ __volatile__("isb sy\n"
"mrs %0, s3_5_c15_c10_2\n"
: "=r"(v)::"memory");
return v;
}
int main(int argc, char *argv[])
{
// {
// for (int j = 0; j < 64; ++j) {
// printf("Read Initial Register bit %02d: %016llx\n", j, read_sprr());
// }
// }
for (int i = 0; i < 64; ++i) {
write_sprr(1ULL<<i);
printf("Flipped Register s3_5_c15_c10_2 bit %02d: %016llx\n", i, read_sprr());
}
}
|
the_stack_data/40763458.c
|
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu \
// RUN: -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu -target-feature +vector \
// RUN: -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu -target-cpu z13 \
// RUN: -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch11 \
// RUN: -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu -target-cpu z14 \
// RUN: -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch12 \
// RUN: -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu -target-cpu z15 \
// RUN: -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch13 \
// RUN: -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu -target-cpu z16 \
// RUN: -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch14 \
// RUN: -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
// Vector types
typedef __attribute__((vector_size(1))) char v1i8;
typedef __attribute__((vector_size(2))) char v2i8;
typedef __attribute__((vector_size(2))) short v1i16;
typedef __attribute__((vector_size(4))) char v4i8;
typedef __attribute__((vector_size(4))) short v2i16;
typedef __attribute__((vector_size(4))) int v1i32;
typedef __attribute__((vector_size(4))) float v1f32;
typedef __attribute__((vector_size(8))) char v8i8;
typedef __attribute__((vector_size(8))) short v4i16;
typedef __attribute__((vector_size(8))) int v2i32;
typedef __attribute__((vector_size(8))) long long v1i64;
typedef __attribute__((vector_size(8))) float v2f32;
typedef __attribute__((vector_size(8))) double v1f64;
typedef __attribute__((vector_size(16))) char v16i8;
typedef __attribute__((vector_size(16))) short v8i16;
typedef __attribute__((vector_size(16))) int v4i32;
typedef __attribute__((vector_size(16))) long long v2i64;
typedef __attribute__((vector_size(16))) __int128 v1i128;
typedef __attribute__((vector_size(16))) float v4f32;
typedef __attribute__((vector_size(16))) double v2f64;
typedef __attribute__((vector_size(16))) long double v1f128;
typedef __attribute__((vector_size(32))) char v32i8;
unsigned int align = __alignof__ (v16i8);
// CHECK: @align ={{.*}} global i32 16
// CHECK-VECTOR: @align ={{.*}} global i32 8
v1i8 pass_v1i8(v1i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v1i8(<1 x i8>* noalias sret(<1 x i8>) align 1 %{{.*}}, <1 x i8>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <1 x i8> @pass_v1i8(<1 x i8> %{{.*}})
v2i8 pass_v2i8(v2i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v2i8(<2 x i8>* noalias sret(<2 x i8>) align 2 %{{.*}}, <2 x i8>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <2 x i8> @pass_v2i8(<2 x i8> %{{.*}})
v4i8 pass_v4i8(v4i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v4i8(<4 x i8>* noalias sret(<4 x i8>) align 4 %{{.*}}, <4 x i8>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <4 x i8> @pass_v4i8(<4 x i8> %{{.*}})
v8i8 pass_v8i8(v8i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v8i8(<8 x i8>* noalias sret(<8 x i8>) align 8 %{{.*}}, <8 x i8>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <8 x i8> @pass_v8i8(<8 x i8> %{{.*}})
v16i8 pass_v16i8(v16i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v16i8(<16 x i8>* noalias sret(<16 x i8>) align 16 %{{.*}}, <16 x i8>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <16 x i8> @pass_v16i8(<16 x i8> %{{.*}})
v32i8 pass_v32i8(v32i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v32i8(<32 x i8>* noalias sret(<32 x i8>) align 32 %{{.*}}, <32 x i8>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_v32i8(<32 x i8>* noalias sret(<32 x i8>) align 8 %{{.*}}, <32 x i8>* %0)
v1i16 pass_v1i16(v1i16 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v1i16(<1 x i16>* noalias sret(<1 x i16>) align 2 %{{.*}}, <1 x i16>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <1 x i16> @pass_v1i16(<1 x i16> %{{.*}})
v2i16 pass_v2i16(v2i16 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v2i16(<2 x i16>* noalias sret(<2 x i16>) align 4 %{{.*}}, <2 x i16>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <2 x i16> @pass_v2i16(<2 x i16> %{{.*}})
v4i16 pass_v4i16(v4i16 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v4i16(<4 x i16>* noalias sret(<4 x i16>) align 8 %{{.*}}, <4 x i16>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <4 x i16> @pass_v4i16(<4 x i16> %{{.*}})
v8i16 pass_v8i16(v8i16 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v8i16(<8 x i16>* noalias sret(<8 x i16>) align 16 %{{.*}}, <8 x i16>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <8 x i16> @pass_v8i16(<8 x i16> %{{.*}})
v1i32 pass_v1i32(v1i32 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v1i32(<1 x i32>* noalias sret(<1 x i32>) align 4 %{{.*}}, <1 x i32>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <1 x i32> @pass_v1i32(<1 x i32> %{{.*}})
v2i32 pass_v2i32(v2i32 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v2i32(<2 x i32>* noalias sret(<2 x i32>) align 8 %{{.*}}, <2 x i32>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <2 x i32> @pass_v2i32(<2 x i32> %{{.*}})
v4i32 pass_v4i32(v4i32 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v4i32(<4 x i32>* noalias sret(<4 x i32>) align 16 %{{.*}}, <4 x i32>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <4 x i32> @pass_v4i32(<4 x i32> %{{.*}})
v1i64 pass_v1i64(v1i64 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v1i64(<1 x i64>* noalias sret(<1 x i64>) align 8 %{{.*}}, <1 x i64>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <1 x i64> @pass_v1i64(<1 x i64> %{{.*}})
v2i64 pass_v2i64(v2i64 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v2i64(<2 x i64>* noalias sret(<2 x i64>) align 16 %{{.*}}, <2 x i64>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <2 x i64> @pass_v2i64(<2 x i64> %{{.*}})
v1i128 pass_v1i128(v1i128 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v1i128(<1 x i128>* noalias sret(<1 x i128>) align 16 %{{.*}}, <1 x i128>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <1 x i128> @pass_v1i128(<1 x i128> %{{.*}})
v1f32 pass_v1f32(v1f32 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v1f32(<1 x float>* noalias sret(<1 x float>) align 4 %{{.*}}, <1 x float>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <1 x float> @pass_v1f32(<1 x float> %{{.*}})
v2f32 pass_v2f32(v2f32 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v2f32(<2 x float>* noalias sret(<2 x float>) align 8 %{{.*}}, <2 x float>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <2 x float> @pass_v2f32(<2 x float> %{{.*}})
v4f32 pass_v4f32(v4f32 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v4f32(<4 x float>* noalias sret(<4 x float>) align 16 %{{.*}}, <4 x float>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <4 x float> @pass_v4f32(<4 x float> %{{.*}})
v1f64 pass_v1f64(v1f64 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v1f64(<1 x double>* noalias sret(<1 x double>) align 8 %{{.*}}, <1 x double>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <1 x double> @pass_v1f64(<1 x double> %{{.*}})
v2f64 pass_v2f64(v2f64 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v2f64(<2 x double>* noalias sret(<2 x double>) align 16 %{{.*}}, <2 x double>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <2 x double> @pass_v2f64(<2 x double> %{{.*}})
v1f128 pass_v1f128(v1f128 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_v1f128(<1 x fp128>* noalias sret(<1 x fp128>) align 16 %{{.*}}, <1 x fp128>* %0)
// CHECK-VECTOR-LABEL: define{{.*}} <1 x fp128> @pass_v1f128(<1 x fp128> %{{.*}})
// Vector-like aggregate types
struct agg_v1i8 { v1i8 a; };
struct agg_v1i8 pass_agg_v1i8(struct agg_v1i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_v1i8(%struct.agg_v1i8* noalias sret(%struct.agg_v1i8) align 1 %{{.*}}, i8 %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_v1i8(%struct.agg_v1i8* noalias sret(%struct.agg_v1i8) align 1 %{{.*}}, <1 x i8> %{{.*}})
struct agg_v2i8 { v2i8 a; };
struct agg_v2i8 pass_agg_v2i8(struct agg_v2i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_v2i8(%struct.agg_v2i8* noalias sret(%struct.agg_v2i8) align 2 %{{.*}}, i16 %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_v2i8(%struct.agg_v2i8* noalias sret(%struct.agg_v2i8) align 2 %{{.*}}, <2 x i8> %{{.*}})
struct agg_v4i8 { v4i8 a; };
struct agg_v4i8 pass_agg_v4i8(struct agg_v4i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_v4i8(%struct.agg_v4i8* noalias sret(%struct.agg_v4i8) align 4 %{{.*}}, i32 %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_v4i8(%struct.agg_v4i8* noalias sret(%struct.agg_v4i8) align 4 %{{.*}}, <4 x i8> %{{.*}})
struct agg_v8i8 { v8i8 a; };
struct agg_v8i8 pass_agg_v8i8(struct agg_v8i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_v8i8(%struct.agg_v8i8* noalias sret(%struct.agg_v8i8) align 8 %{{.*}}, i64 %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_v8i8(%struct.agg_v8i8* noalias sret(%struct.agg_v8i8) align 8 %{{.*}}, <8 x i8> %{{.*}})
struct agg_v16i8 { v16i8 a; };
struct agg_v16i8 pass_agg_v16i8(struct agg_v16i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_v16i8(%struct.agg_v16i8* noalias sret(%struct.agg_v16i8) align 16 %{{.*}}, %struct.agg_v16i8* %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_v16i8(%struct.agg_v16i8* noalias sret(%struct.agg_v16i8) align 8 %{{.*}}, <16 x i8> %{{.*}})
struct agg_v32i8 { v32i8 a; };
struct agg_v32i8 pass_agg_v32i8(struct agg_v32i8 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_v32i8(%struct.agg_v32i8* noalias sret(%struct.agg_v32i8) align 32 %{{.*}}, %struct.agg_v32i8* %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_v32i8(%struct.agg_v32i8* noalias sret(%struct.agg_v32i8) align 8 %{{.*}}, %struct.agg_v32i8* %{{.*}})
// Verify that the following are *not* vector-like aggregate types
struct agg_novector1 { v4i8 a; v4i8 b; };
struct agg_novector1 pass_agg_novector1(struct agg_novector1 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_novector1(%struct.agg_novector1* noalias sret(%struct.agg_novector1) align 4 %{{.*}}, i64 %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_novector1(%struct.agg_novector1* noalias sret(%struct.agg_novector1) align 4 %{{.*}}, i64 %{{.*}})
struct agg_novector2 { v4i8 a; float b; };
struct agg_novector2 pass_agg_novector2(struct agg_novector2 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_novector2(%struct.agg_novector2* noalias sret(%struct.agg_novector2) align 4 %{{.*}}, i64 %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_novector2(%struct.agg_novector2* noalias sret(%struct.agg_novector2) align 4 %{{.*}}, i64 %{{.*}})
struct agg_novector3 { v4i8 a; int : 0; };
struct agg_novector3 pass_agg_novector3(struct agg_novector3 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_novector3(%struct.agg_novector3* noalias sret(%struct.agg_novector3) align 4 %{{.*}}, i32 %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_novector3(%struct.agg_novector3* noalias sret(%struct.agg_novector3) align 4 %{{.*}}, i32 %{{.*}})
struct agg_novector4 { v4i8 a __attribute__((aligned (8))); };
struct agg_novector4 pass_agg_novector4(struct agg_novector4 arg) { return arg; }
// CHECK-LABEL: define{{.*}} void @pass_agg_novector4(%struct.agg_novector4* noalias sret(%struct.agg_novector4) align 8 %{{.*}}, i64 %{{.*}})
// CHECK-VECTOR-LABEL: define{{.*}} void @pass_agg_novector4(%struct.agg_novector4* noalias sret(%struct.agg_novector4) align 8 %{{.*}}, i64 %{{.*}})
// Accessing variable argument lists
v1i8 va_v1i8(__builtin_va_list l) { return __builtin_va_arg(l, v1i8); }
// CHECK-LABEL: define{{.*}} void @va_v1i8(<1 x i8>* noalias sret(<1 x i8>) align 1 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to <1 x i8>**
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to <1 x i8>**
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi <1 x i8>** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: [[INDIRECT_ARG:%[^ ]+]] = load <1 x i8>*, <1 x i8>** [[VA_ARG_ADDR]]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} <1 x i8> @va_v1i8(%struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to <1 x i8>*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[RET:%[^ ]+]] = load <1 x i8>, <1 x i8>* [[MEM_ADDR]]
// CHECK-VECTOR: ret <1 x i8> [[RET]]
v2i8 va_v2i8(__builtin_va_list l) { return __builtin_va_arg(l, v2i8); }
// CHECK-LABEL: define{{.*}} void @va_v2i8(<2 x i8>* noalias sret(<2 x i8>) align 2 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to <2 x i8>**
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to <2 x i8>**
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi <2 x i8>** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: [[INDIRECT_ARG:%[^ ]+]] = load <2 x i8>*, <2 x i8>** [[VA_ARG_ADDR]]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} <2 x i8> @va_v2i8(%struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to <2 x i8>*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[RET:%[^ ]+]] = load <2 x i8>, <2 x i8>* [[MEM_ADDR]]
// CHECK-VECTOR: ret <2 x i8> [[RET]]
v4i8 va_v4i8(__builtin_va_list l) { return __builtin_va_arg(l, v4i8); }
// CHECK-LABEL: define{{.*}} void @va_v4i8(<4 x i8>* noalias sret(<4 x i8>) align 4 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to <4 x i8>**
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to <4 x i8>**
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi <4 x i8>** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: [[INDIRECT_ARG:%[^ ]+]] = load <4 x i8>*, <4 x i8>** [[VA_ARG_ADDR]]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} <4 x i8> @va_v4i8(%struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to <4 x i8>*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[RET:%[^ ]+]] = load <4 x i8>, <4 x i8>* [[MEM_ADDR]]
// CHECK-VECTOR: ret <4 x i8> [[RET]]
v8i8 va_v8i8(__builtin_va_list l) { return __builtin_va_arg(l, v8i8); }
// CHECK-LABEL: define{{.*}} void @va_v8i8(<8 x i8>* noalias sret(<8 x i8>) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to <8 x i8>**
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to <8 x i8>**
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi <8 x i8>** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: [[INDIRECT_ARG:%[^ ]+]] = load <8 x i8>*, <8 x i8>** [[VA_ARG_ADDR]]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} <8 x i8> @va_v8i8(%struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to <8 x i8>*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[RET:%[^ ]+]] = load <8 x i8>, <8 x i8>* [[MEM_ADDR]]
// CHECK-VECTOR: ret <8 x i8> [[RET]]
v16i8 va_v16i8(__builtin_va_list l) { return __builtin_va_arg(l, v16i8); }
// CHECK-LABEL: define{{.*}} void @va_v16i8(<16 x i8>* noalias sret(<16 x i8>) align 16 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to <16 x i8>**
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to <16 x i8>**
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi <16 x i8>** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: [[INDIRECT_ARG:%[^ ]+]] = load <16 x i8>*, <16 x i8>** [[VA_ARG_ADDR]]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} <16 x i8> @va_v16i8(%struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to <16 x i8>*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 16
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[RET:%[^ ]+]] = load <16 x i8>, <16 x i8>* [[MEM_ADDR]]
// CHECK-VECTOR: ret <16 x i8> [[RET]]
v32i8 va_v32i8(__builtin_va_list l) { return __builtin_va_arg(l, v32i8); }
// CHECK-LABEL: define{{.*}} void @va_v32i8(<32 x i8>* noalias sret(<32 x i8>) align 32 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to <32 x i8>**
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to <32 x i8>**
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi <32 x i8>** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: [[INDIRECT_ARG:%[^ ]+]] = load <32 x i8>*, <32 x i8>** [[VA_ARG_ADDR]]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} void @va_v32i8(<32 x i8>* noalias sret(<32 x i8>) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK-VECTOR: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK-VECTOR: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK-VECTOR: br i1 [[FITS_IN_REGS]],
// CHECK-VECTOR: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK-VECTOR: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK-VECTOR: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK-VECTOR: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK-VECTOR: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK-VECTOR: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to <32 x i8>**
// CHECK-VECTOR: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK-VECTOR: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to <32 x i8>**
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[VA_ARG_ADDR:%[^ ]+]] = phi <32 x i8>** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK-VECTOR: [[INDIRECT_ARG:%[^ ]+]] = load <32 x i8>*, <32 x i8>** [[VA_ARG_ADDR]]
// CHECK-VECTOR: ret void
struct agg_v1i8 va_agg_v1i8(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_v1i8); }
// CHECK-LABEL: define{{.*}} void @va_agg_v1i8(%struct.agg_v1i8* noalias sret(%struct.agg_v1i8) align 1 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 23
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_v1i8*
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 7
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_v1i8*
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_v1i8* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} void @va_agg_v1i8(%struct.agg_v1i8* noalias sret(%struct.agg_v1i8) align 1 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to %struct.agg_v1i8*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: ret void
struct agg_v2i8 va_agg_v2i8(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_v2i8); }
// CHECK-LABEL: define{{.*}} void @va_agg_v2i8(%struct.agg_v2i8* noalias sret(%struct.agg_v2i8) align 2 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 22
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_v2i8*
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 6
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_v2i8*
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_v2i8* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} void @va_agg_v2i8(%struct.agg_v2i8* noalias sret(%struct.agg_v2i8) align 2 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to %struct.agg_v2i8*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: ret void
struct agg_v4i8 va_agg_v4i8(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_v4i8); }
// CHECK-LABEL: define{{.*}} void @va_agg_v4i8(%struct.agg_v4i8* noalias sret(%struct.agg_v4i8) align 4 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 20
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_v4i8*
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 4
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_v4i8*
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_v4i8* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} void @va_agg_v4i8(%struct.agg_v4i8* noalias sret(%struct.agg_v4i8) align 4 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to %struct.agg_v4i8*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: ret void
struct agg_v8i8 va_agg_v8i8(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_v8i8); }
// CHECK-LABEL: define{{.*}} void @va_agg_v8i8(%struct.agg_v8i8* noalias sret(%struct.agg_v8i8) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_v8i8*
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_v8i8*
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_v8i8* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} void @va_agg_v8i8(%struct.agg_v8i8* noalias sret(%struct.agg_v8i8) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to %struct.agg_v8i8*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: ret void
struct agg_v16i8 va_agg_v16i8(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_v16i8); }
// CHECK-LABEL: define{{.*}} void @va_agg_v16i8(%struct.agg_v16i8* noalias sret(%struct.agg_v16i8) align 16 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_v16i8**
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_v16i8**
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_v16i8** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: [[INDIRECT_ARG:%[^ ]+]] = load %struct.agg_v16i8*, %struct.agg_v16i8** [[VA_ARG_ADDR]]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} void @va_agg_v16i8(%struct.agg_v16i8* noalias sret(%struct.agg_v16i8) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[OVERFLOW_ARG_AREA]] to %struct.agg_v16i8*
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA1:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 16
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA1]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: ret void
struct agg_v32i8 va_agg_v32i8(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_v32i8); }
// CHECK-LABEL: define{{.*}} void @va_agg_v32i8(%struct.agg_v32i8* noalias sret(%struct.agg_v32i8) align 32 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK: br i1 [[FITS_IN_REGS]],
// CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_v32i8**
// CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_v32i8**
// CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_v32i8** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK: [[INDIRECT_ARG:%[^ ]+]] = load %struct.agg_v32i8*, %struct.agg_v32i8** [[VA_ARG_ADDR]]
// CHECK: ret void
// CHECK-VECTOR-LABEL: define{{.*}} void @va_agg_v32i8(%struct.agg_v32i8* noalias sret(%struct.agg_v32i8) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}})
// CHECK-VECTOR: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0
// CHECK-VECTOR: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]]
// CHECK-VECTOR: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5
// CHECK-VECTOR: br i1 [[FITS_IN_REGS]],
// CHECK-VECTOR: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8
// CHECK-VECTOR: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16
// CHECK-VECTOR: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3
// CHECK-VECTOR: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]]
// CHECK-VECTOR: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]]
// CHECK-VECTOR: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_v32i8**
// CHECK-VECTOR: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1
// CHECK-VECTOR: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]]
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0
// CHECK-VECTOR: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_v32i8**
// CHECK-VECTOR: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8
// CHECK-VECTOR: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]]
// CHECK-VECTOR: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_v32i8** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ]
// CHECK-VECTOR: [[INDIRECT_ARG:%[^ ]+]] = load %struct.agg_v32i8*, %struct.agg_v32i8** [[VA_ARG_ADDR]]
// CHECK-VECTOR: ret void
|
the_stack_data/212643235.c
|
/* (c) 2015-2021 Carlos J. Santisteban */
#include <stdio.h>
int main(void) {
unsigned char rom[1500];
unsigned char ram[65536];
FILE* arch;
unsigned char c, opcode, flag;
int ptr, oldptr, siz, count, scan;
arch=fopen("65C02.bin","rb"); // opcode list
if (arch==NULL) { // not found?
printf("\n***Problem opening Opcode List '65C02.bin'!***\n");
return -1; // ABORT
}
fseek(arch,0,SEEK_END); // go to end
siz=ftell(arch); // get length
fseek(arch,0,SEEK_SET); // back to start
fread(rom,siz,1,arch); // read all
ptr=0; // code begins here
arch=fopen("test.bin","rb"); // code to disassemble
if (arch==NULL) { // not found?
printf("\n***Problem opening CODE!***\n");
return -1; // ABORT
}
fseek(arch,0,SEEK_END); // go to end
siz=ftell(arch); // get length
fseek(arch,0,SEEK_SET); // back to start
fread(&(ram[ptr]),siz,1,arch); // read all there
printf("Go!\n");
do {
opcode = ram[ptr]; // get opcode
oldptr = ptr; // before increasing
printf("%04x: ", ptr); // print initial address
// printf("%04x: %02x... ", ptr, opcode); // print initial values
count = 0; // skipped strings
scan = 0; // opcode list pointer
while (opcode != count && count<256) {
while (rom[scan]<128)
scan++; // fetch next terminator
scan++; // go to next entry
count++; // another opcode skipped
}
siz = 1; // bytes to be dumped
do {
flag = rom[scan] & 128; // bit 7 will exit after processing
c = rom[scan] & 127; // mask bit 7 out
switch(c) {
case '@': // single byte operand
printf("$%02x", ram[++ptr]); // print operand in hex
siz = 2; // 2-byte opcode
break;
case '&': // word operand
printf("$%04x", ram[++ptr]+256*ram[++ptr]); // print address in hex
siz = 3; // 3-byte opcode
break;
default: // generic character
printf("%c", c); // print it
} // end of switch
scan++; // next character!
} while (!flag); // until terminator
ptr++; // next opcode!
printf(" [ "); // tabulate!
for (count=0; count<siz; count++) {
printf("%02x ", ram[oldptr+count]); // dump byte
}
printf("]\n");
} while (ram[ptr]); // until BRK!
return 0;
}
|
the_stack_data/38718.c
|
//
// Created by rahul on 1/8/19.
//
#include <stdio.h>
int getarray(char arr[],int maxsize)
{
int x;
int i=0;
while((x=getchar())!='\n' && i<maxsize)
{
arr[i]=x;
i++;
}
arr[i]='\0';
}
int main()
{
char str[200],pat[20],new_str[400],rep_pat[100];
int i=0,j=0,k,n=0,copy_loop=0,rep_index=0;
printf("enter the string : ");
getarray(str,200);
printf("\n enter the pattern to be replaced");
getarray(pat,20);
printf("\n enter the repacing pattern:");
getarray(rep_pat,100);
while(str[i]!='\0')
{
j=0;
k=i;
while(str[k]==pat[j] && pat[j]!='\0')
{
k++;
j++;
}
if(pat[j]=='\0')
{
copy_loop=k;
while(rep_pat[rep_index]!='\0')
{
new_str[n]=rep_pat[rep_index];
rep_index++;
n++;
}
}
new_str[n]=str[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]='\0';
printf("\n the new string is ");
puts(new_str);
return 0;
}
|
the_stack_data/1189378.c
|
/* Public domain. */
#include <errno.h>
#include "error.h"
/* warning: as coverage improves here, should update error_{str,temp} */
int error_intr =
#ifdef EINTR
EINTR;
#else
-1;
#endif
int error_nomem =
#ifdef ENOMEM
ENOMEM;
#else
-2;
#endif
int error_noent =
#ifdef ENOENT
ENOENT;
#else
-3;
#endif
int error_txtbsy =
#ifdef ETXTBSY
ETXTBSY;
#else
-4;
#endif
int error_io =
#ifdef EIO
EIO;
#else
-5;
#endif
int error_exist =
#ifdef EEXIST
EEXIST;
#else
-6;
#endif
int error_timeout =
#ifdef ETIMEDOUT
ETIMEDOUT;
#else
-7;
#endif
int error_inprogress =
#ifdef EINPROGRESS
EINPROGRESS;
#else
-8;
#endif
int error_wouldblock =
#ifdef EWOULDBLOCK
EWOULDBLOCK;
#else
-9;
#endif
int error_again =
#ifdef EAGAIN
EAGAIN;
#else
-10;
#endif
int error_pipe =
#ifdef EPIPE
EPIPE;
#else
-11;
#endif
int error_perm =
#ifdef EPERM
EPERM;
#else
-12;
#endif
int error_acces =
#ifdef EACCES
EACCES;
#else
-13;
#endif
int error_nodevice =
#ifdef ENXIO
ENXIO;
#else
-14;
#endif
int error_proto =
#ifdef EPROTO
EPROTO;
#else
-15;
#endif
int error_isdir =
#ifdef EISDIR
EISDIR;
#else
-16;
#endif
int error_connrefused =
#ifdef ECONNREFUSED
ECONNREFUSED;
#else
-17;
#endif
int error_notdir =
#ifdef ENOTDIR
ENOTDIR;
#else
-18;
#endif
|
the_stack_data/170452937.c
|
#include <stdio.h>
int main() {
if (isalnum('A'))
printf("is alpha number\n");
return 0;
}
|
the_stack_data/76994.c
|
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
};
int isEmpty(struct Node *root){
return !root;
}
void push( struct Node **root, int data){
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
// New node.
if(isEmpty((*root))){
// printf("Empty Stack \n");
newNode->data = data;
newNode->next = NULL;
(*root) = newNode;
}else{
newNode->data = data;
newNode->next = (*root);
(*root) = newNode;
}
}
void print(struct Node *root)
{
struct Node *temp = root;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int pop( struct Node **root){
if(isEmpty((*root)))
return 0;
int poped_item;
struct Node *temp = *root;
poped_item = temp->data;
(*root) = (*root)->next;
free(temp);
return poped_item;
}
int top(struct Node *root){
if(isEmpty(root))
return 0;
return root->data;
}
int main(){
struct Node *root = NULL;
int poped_item;
push(&root, 10);
push(&root, 20);
push(&root, 30);
push(&root, 40);
push(&root, 50);
print(root);
poped_item = pop(&root);
printf("Poped Item : %d \n", poped_item);
// get the topmost element in the stack.
printf("Top Item in the Stack : %d \n", top(root));
poped_item = pop(&root);
printf("Poped Item : %d \n", poped_item);
// get the topmost element in the stack.
printf("Top Item in the Stack : %d \n", top(root));
poped_item = pop(&root);
printf("Poped Item : %d \n", poped_item);
// get the topmost element in the stack.
printf("Top Item in the Stack : %d \n", top(root));
print(root);
return 0;
}
|
the_stack_data/23574312.c
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float fun(float x);
/**********Main function begins*********/
int main(int argc,char *argv[])
{
float a,b,N,h,f[32],x,ans,n = 0; /* a,b are the limits where N is the number of intervals and x is the interval,f[] maintains function values at each interval,h is interval length */
int i = 0,j = 1; /* These are used to maintain count */
if (argc != 4) {
printf("Syntax: ./trapezoid3 a b h\n"); /* prints error message for wrong syntax */
exit(1); /* exits from the program */
}
a = atof(argv[1]); /* Takes lower bound */
b = atof(argv[2]); /* Takes upper bound */
h = atof(argv[3]); /* interval length */
N = (b - a) / (h); /* number of intervals */
while (i != (N + 1)){
x = a + (i*h); /* calculates x value at each interval */
f[i] = fun(x); /* store f(x) */
printf ("x[%d] = %f, f[%d] = %f\n",i,x,i,f[i]); /* prints x and f(x) at each interval */
i++; /* increments count */
}
i = i - 1; /* here i = N */
ans = ((h*(f[0] + f[i]))/2); /* adds h/2(f(0) + f(N)) to the answer */
while (j < i) {
n = n + f[j];
j++;
}
ans = ans + (n*h); /* adds h(f(x_1) + .........+ f(x_N-1)) to the answer */
printf("Ans = %f\n",ans); /* prints the answer */
}
/************Main function ends************/
float fun(float x)
{
return(1/(1+(x*x))); /* returns f(x) */
}
|
the_stack_data/298640.c
|
#include<stdio.h>
#include<stdlib.h>
typedef struct mk
{
int num;
struct mk *link;
}monkey,*mknode;
int main()
{
int n,m,q;
scanf("%d%d%d",&n,&m,&q);
int i;
mknode head=NULL,p=NULL,r=NULL;
for(i=1;i<=n;i++)
{
p=(mknode)malloc(sizeof(monkey));
p->num=i;
p->link=NULL;
if(head==NULL)
{
head=p;
p->link=p;
}
else
{
r->link=p;
p->link=head;
}
r=p;
}
// p->link=head;
p=head;
while(p->num!=q)
{
p=p->link;
}
while(head->link!=head)
{
for(i=0;i<m-1;i++)
{
p=p->link;
}
if(p==head)
{
r=head;
while(r->link!=head)
{
r=r->link;
}
r->link=p->link;
head=p->link;
free(p);
p=r->link;
}
else
{
r=head;
while(r->link!=p)
{
r=r->link;
}
r->link=p->link;
free(p);
p=r->link;
}
}
printf("%d",head->num);
return 0;
}
|
the_stack_data/178266471.c
|
void foo() {
unsigned X = 1;
for (long I = 0; 10 > I; I = I + X);
}
//CHECK: Printing analysis 'Canonical Form Loop Analysis' for function 'foo':
//CHECK: loop at canonical_loop_17.c:3:3 is semantically canonical
|
the_stack_data/25136546.c
|
/*
* fakepop - A fake POP server used by the nmh test suite
*
* This code is Copyright (c) 2012, by the authors of nmh. See the
* COPYRIGHT file in the root directory of the nmh distribution for
* complete copyright information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <limits.h>
#define PIDFILE "/tmp/fakepop.pid"
#define LINESIZE 1024
#define BUFALLOC 4096
#define CHECKUSER() if (!user) { \
putcrlf(s, "-ERR Aren't you forgetting " \
"something? Like the USER command?"); \
continue; \
}
#define CHECKAUTH() if (!auth) { \
putcrlf(s, "-ERR Um, hello? Forget to " \
"log in?"); \
continue; \
}
void putcrlf(int, char *);
int serve(const char *, const char *);
static void putpopbulk(int, char *);
static int getpop(int, char *, ssize_t);
static char *readmessage(FILE *);
int
main(int argc, char *argv[])
{
FILE **mfiles;
char line[LINESIZE];
int rc, s, user = 0, auth = 0, i, j;
int numfiles;
size_t *octets;
const char *xoauth;
if (argc < 5) {
fprintf(stderr, "Usage: %s port username "
"password mail-file [mail-file ...]\n", argv[0]);
exit(1);
}
if (strcmp(argv[2], "XOAUTH") == 0) {
xoauth = argv[3];
} else {
xoauth = NULL;
}
numfiles = argc - 4;
mfiles = malloc(sizeof(FILE *) * numfiles);
if (! mfiles) {
fprintf(stderr, "Unable to allocate %d bytes for file "
"array\n", (int) (sizeof(FILE *) * numfiles));
exit(1);
}
octets = malloc(sizeof(*octets) * numfiles);
if (! octets) {
fprintf(stderr, "Unable to allocate %d bytes for size "
"array\n", (int) (sizeof(FILE *) * numfiles));
exit(1);
}
for (i = 4, j = 0; i < argc; i++, j++) {
if (!(mfiles[j] = fopen(argv[i], "r"))) {
fprintf(stderr, "Unable to open message file \"%s\""
": %s\n", argv[i], strerror(errno));
exit(1);
}
/*
* POP wants the size of the maildrop in bytes, but
* with \r\n line endings. Calculate that.
*/
octets[j] = 0;
while (fgets(line, sizeof(line), mfiles[j])) {
octets[j] += strlen(line);
if (strrchr(line, '\n'))
octets[j]++;
}
rewind(mfiles[j]);
}
s = serve(PIDFILE, argv[1]);
/*
* Pretend to be a POP server
*/
putcrlf(s, "+OK Not really a POP server, but we play one on TV");
for (;;) {
char linebuf[LINESIZE];
rc = getpop(s, linebuf, sizeof(linebuf));
if (rc <= 0)
break; /* Error or EOF */
if (strcasecmp(linebuf, "CAPA") == 0) {
putpopbulk(s, "+OK We have no capabilities, really\r\n"
"FAKE-CAPABILITY\r\n");
if (xoauth != NULL) {
putcrlf(s, "SASL XOAUTH2");
}
putcrlf(s, ".");
} else if (strncasecmp(linebuf, "USER ", 5) == 0) {
if (strcmp(linebuf + 5, argv[2]) == 0) {
putcrlf(s, "+OK Niiiice!");
user = 1;
} else {
putcrlf(s, "-ERR Don't play me, bro!");
}
} else if (strncasecmp(linebuf, "PASS ", 5) == 0) {
CHECKUSER();
if (strcmp(linebuf + 5, argv[3]) == 0) {
putcrlf(s, "+OK Aren't you a sight "
"for sore eyes!");
auth = 1;
} else {
putcrlf(s, "-ERR C'mon!");
}
} else if (xoauth != NULL
&& strncasecmp(linebuf, "AUTH XOAUTH2", 12) == 0) {
if (strstr(linebuf, xoauth) == NULL) {
putcrlf(s, "+ base64-json-err");
rc = getpop(s, linebuf, sizeof(linebuf));
if (rc != 0)
break; /* Error or EOF */
putcrlf(s, "-ERR [AUTH] Invalid credentials.");
continue;
}
putcrlf(s, "+OK Welcome.");
auth = 1;
} else if (strcasecmp(linebuf, "STAT") == 0) {
size_t total = 0;
CHECKAUTH();
for (i = 0, j = 0; i < numfiles; i++) {
if (mfiles[i]) {
total += octets[i];
j++;
}
}
snprintf(linebuf, sizeof(linebuf),
"+OK %d %d", i, (int) total);
putcrlf(s, linebuf);
} else if (strncasecmp(linebuf, "RETR ", 5) == 0) {
CHECKAUTH();
rc = sscanf(linebuf + 5, "%d", &i);
if (rc != 1) {
putcrlf(s, "-ERR Whaaaa...?");
continue;
}
if (i < 1 || i > numfiles) {
putcrlf(s, "-ERR That message number is "
"out of range, jerkface!");
continue;
}
if (mfiles[i - 1] == NULL) {
putcrlf(s, "-ERR Sorry, don't have it anymore");
} else {
char *buf = readmessage(mfiles[i - 1]);
putcrlf(s, "+OK Here you go ...");
putpopbulk(s, buf);
free(buf);
}
} else if (strncasecmp(linebuf, "DELE ", 5) == 0) {
CHECKAUTH();
rc = sscanf(linebuf + 5, "%d", &i);
if (rc != 1) {
putcrlf(s, "-ERR Whaaaa...?");
continue;
}
if (i < 1 || i > numfiles) {
putcrlf(s, "-ERR That message number is "
"out of range, jerkface!");
continue;
}
if (mfiles[i - 1] == NULL) {
putcrlf(s, "-ERR Um, didn't you tell me "
"to delete it already?");
} else {
fclose(mfiles[i - 1]);
mfiles[i - 1] = NULL;
putcrlf(s, "+OK Alright man, I got rid of it");
}
} else if (strcasecmp(linebuf, "QUIT") == 0) {
putcrlf(s, "+OK See ya, wouldn't want to be ya!");
close(s);
break;
} else {
putcrlf(s, "-ERR Um, what?");
}
}
exit(0);
}
/*
* Put one big buffer to the POP server. Should have already had the line
* endings set up and dot-stuffed if necessary.
*/
static void
putpopbulk(int socket, char *data)
{
ssize_t datalen = strlen(data);
if (write(socket, data, datalen) < 0) {
perror ("write");
}
}
/*
* Get one line from the POP server. We don't do any buffering here.
*/
static int
getpop(int socket, char *data, ssize_t len)
{
int cc;
int offset = 0;
for (;;) {
cc = read(socket, data + offset, len - offset);
if (cc < 0) {
fprintf(stderr, "Read failed: %s\n", strerror(errno));
exit(1);
}
if (cc == 0) {
return 0;
}
offset += cc;
if (offset >= len) {
fprintf(stderr, "Input buffer overflow "
"(%d bytes)\n", (int) len);
exit(1);
}
if (data[offset - 1] == '\n' && data[offset - 2] == '\r') {
data[offset - 2] = '\0';
return offset - 2;
}
}
}
#define HAVEROOM(buf, size, used, new) do { \
if (used + new > size - 1) { \
buf = realloc(buf, size += BUFALLOC); \
} \
} while (0)
/*
* Read a file and return it as one malloc()'d buffer. Convert \n to \r\n
* and dot-stuff if necessary.
*/
static char *
readmessage(FILE *file)
{
char *buffer = malloc(BUFALLOC);
ssize_t bufsize = BUFALLOC, used = 0;
char linebuf[LINESIZE];
int i;
buffer[0] = '\0';
while (fgets(linebuf, sizeof(linebuf), file)) {
if (strcmp(linebuf, ".\n") == 0) {
HAVEROOM(buffer, bufsize, used, 4);
strcat(buffer, "..\r\n");
} else {
i = strlen(linebuf);
if (i && linebuf[i - 1] == '\n') {
HAVEROOM(buffer, bufsize, used, i + 1);
linebuf[i - 1] = '\0';
strcat(buffer, linebuf);
strcat(buffer, "\r\n");
} else {
HAVEROOM(buffer, bufsize, used, i);
strcat(buffer, linebuf);
}
}
}
/*
* Put a terminating dot at the end
*/
HAVEROOM(buffer, bufsize, used, 3);
strcat(buffer, ".\r\n");
rewind(file);
return buffer;
}
|
the_stack_data/184517451.c
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str;
char *stringa;
FILE *fp;
while(1)
{
int ret = system("nc -l 2080 > prova.txt");
scanf("%s",stringa);
int ret1 =system("nc localhost 2080");
printf("DOPO IL NETCAT");
if((fp=fopen("prova.txt","r"))==NULL)
{
return 1;
}
printf("DOPO L'APERTURA FILE");
fprintf(stdout,"Ricevuto");
printf("SONO DOPO IL RICEVUTO");
fprintf(stderr, "Il client ha scritto: ");
while((str = fgetc(fp)) != EOF)
printf("%c", str);
fclose(fp);
}
return 0;
}
|
the_stack_data/31387726.c
|
/*
Project 28 - FINDING THE LIMITS: <limits.h>
Table: Symbols Representing Range Limits for Integer Types
----------------------------------------------------------
-----------------------------------------
Type Lower_limit Upper_limit
---- ----------- -----------
char CHAR_MIN CHAR_MAX
short SHRT_MIN SHRT_MAX
int INT_MIN INT_MAX
long LONG_MIN LONG_MAX
long long LLONG_MIN LLONG_MAX
------------------------------------------
***************************************************************************
Output:
--------------------------------------------------------------------------
Table: Variables types store values from:
--------------------------------------------------------------------------
CHAR: -128 -> 127
UNISIGNED CHAR: 0 -> 255
SHORT (INT): -32768 -> 32767
UNSINED SHORT (INT): 0 -> 65535
INT: -2147483648 -> 2147483647
UNSIGNED INT: 0 -> 4294967295
LONG: -2147483648 -> 2147483647
UNSIGNED LONG: 0 -> 4294967295
LONG LONG: -9223372036854775808 -> 9223372036854775807
UNSIGNED LONG LONG: 0 -> 18446744073709551615
--------------------------------------------------------------------------
SMALLEST POSITIVE NON-ZERO VALUE OF FLOAT is 1.175e-038
LARGEST FLOAT is 3.403e+038
SMALLEST NON-ZERO VALUE OF DOUBLE is 2.225e-308
LARGEST DOUBLE is 1.798e+308
SMALLEST NON-ZERO VALUE OF LONG DOUBLE is 3.205e-317
LARGEST VALUE OF LONG DOUBLE is 3.205e-317
--------------------------------------------------------------------------
***************************************************************************
From Beginning_c_5th_edition, pg 57
Edited by j3
Date: Jun, 22/2020
*/
#include <stdio.h> // For command line input and output
#include <limits.h> // For limits on integer types
#include <float.h> // For limits on floating-point types
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(void) {
printf("--------------------------------------------------------------------------\n");
printf(" Table: Variables types store values from:\n");
printf("--------------------------------------------------------------------------\n");
printf("CHAR:\t\t\t %d -> %d\n", CHAR_MIN, CHAR_MAX);
printf("UNISIGNED CHAR:\t\t 0 -> %u\n", UCHAR_MAX);
printf("SHORT (INT):\t\t %d -> %d\n", SHRT_MIN, SHRT_MAX);
printf("UNSINED SHORT (INT):\t 0 -> %u\n", USHRT_MAX);
printf("INT:\t\t\t %d -> %d\n", INT_MIN, INT_MAX);
printf("UNSIGNED INT:\t\t 0 -> %u\n", UINT_MAX);
printf("LONG:\t\t\t %ld -> %ld\n", LONG_MIN, LONG_MAX);
printf("UNSIGNED LONG:\t\t 0 -> %lu\n", ULONG_MAX);
printf("LONG LONG:\t\t %lld -> %lld\n", LLONG_MIN, LLONG_MAX);
printf("UNSIGNED LONG LONG:\t 0 -> %llu\n", ULLONG_MAX);
printf("--------------------------------------------------------------------------\n");
printf("SMALLEST POSITIVE NON-ZERO VALUE OF FLOAT is %.3e\n", FLT_MIN);
printf("LARGEST FLOAT is %.3e\n", FLT_MAX);
printf("SMALLEST NON-ZERO VALUE OF DOUBLE is %.3e\n", DBL_MIN);
printf("LARGEST DOUBLE is %.3e\n", DBL_MAX);
printf("SMALLEST NON-ZERO VALUE OF LONG DOUBLE is %.3Le\n", LDBL_MIN);
printf("LARGEST VALUE OF LONG DOUBLE is %.3Le\n", LDBL_MAX);
printf("--------------------------------------------------------------------------\n");
//system("pause");
return 0;
}
|
the_stack_data/27654.c
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 0;
int valDigitado = 0;
printf("\t============== ============== ==============\n");
printf("\t Informe a quantidade de repeticao X: ");
scanf("%i", &valDigitado);
while(x < valDigitado){
printf("\t %i \n", x * 10);
x = x + 1;
}
printf("\t============== ============== ==============\n");
return 0;
}
|
the_stack_data/1196234.c
|
#include<stdio.h>
int nsum(int n, int arr[][50])
{
int i, j, sum = 0;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
{
if (i != j)
sum = sum + arr[i][j];
}
return sum;
}
int main()
{
int arr[50][50], n, i, j;
printf("Enter the order of Matrix: ");
scanf("%d", &n);
printf("Enter the elements of Matrix: \n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &arr[i][j]);
printf("Σ of non main-diagonal elements = %d\n", nsum(n, arr));
}
|
the_stack_data/527845.c
|
/* Exercice fait par M. Léry */
#include <stdio.h>
#include <ctype.h>
main()
{
char nom[100] ;
printf("Saisissez votre nom : ") ;
scanf("%s", nom) ;
nom[0] = toupper(nom[0]) ;
printf("%s\n", nom) ;
}
|
the_stack_data/117328219.c
|
typedef volatile unsigned short hword;
#define VRAM 0x06000000
void draw_point(hword,hword,hword);
int main(void){
hword *ptr;
hword color1;
hword color2;
color1=0x7FE0;
color2=0x001F;
int i;
int j;
int Xe=(610*3)%19+101;
int Ye=(1003%19)+61;
int R=(1003%9)+29;
int dx;
int dy;
ptr=(hword *)0x04000000;
*ptr=0x0F03;
ptr=(hword *)VRAM;
for(i=0;i<160;i++){
for(j=0;j<240;j++){
*ptr=color1;
ptr+=1;
}
}
for(i=0;i<160;i++){
for(j=0;j<240;j++){
dx=j-Xe;
dy=i-Ye;
if((dx*dx)+(dy*dy)<=(R*R)){
draw_point(i,j,color2);
}
}
}
while(1);
return 0;
}
void draw_point(hword x,hword y,hword color){
hword *ptr;
ptr=(hword *)(VRAM+(x*2)+(y*480));
*ptr=color;
}
|
the_stack_data/67325310.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcapitalize.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: skuntoji <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/26 01:41:37 by skuntoji #+# #+# */
/* Updated: 2018/06/26 15:57:59 by skuntoji ### ########.fr */
/* */
/* ************************************************************************** */
int c_alpha(char c)
{
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9'))
return (1);
return (0);
}
char *ft_strcapitalize(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
if (i == 0 || !c_alpha(str[i - 1]))
{
if (str[i] >= 'a' && str[i] <= 'z')
str[i] -= 32;
}
else if (str[i] >= 'A' && str[i] <= 'Z')
str[i] += 32;
i++;
}
return (str);
}
|
the_stack_data/178264922.c
|
//Calculo do valor excedente
#include <stdio.h>
int main(void){
float peso,acima;
printf("Qual foi o peso pescado: \n");
scanf("%f",&peso);
if (peso <= 50){
printf("Você esta dentro dos padrões\n");
}else{
acima = (peso - 50) * 4;
printf("Você está acima do peso e terá de pagar R$ %.2f\n",acima);
}
return 0;
}
|
the_stack_data/1015016.c
|
#include <stdio.h>
/* Write a program to copy its input to its output, replacing each tab by \t,
* each backspace by \b, and each backslash by \\. This makes tabs and
* backspaces visible in an unambiguous way. */
int main(){
int c;
while((c = getchar()) != EOF){
/* detect special cases */
if((c == '\t')){
putchar('\\');
putchar('t');
}
else if((c == '\b')){
putchar('\\');
putchar('b');
/* Note: if you don't see backspaces if probably because your
* terminal is in Canonical Mode Input Processing, which means that
* only sends characters after each line.
* Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap11.html#tag_11_01_06 */
}
else if((c == '\\')){
putchar('\\');
putchar('\\');
}
else
putchar(c);
}
}
|
the_stack_data/67324098.c
|
/*
* Copyright (c) 2012-2020, Tiiffi <tiiffi at gmail>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>
#ifdef _WIN32
// for name resolving on windows
// enable this if you get compiler whine about getaddrinfo() on windows
// #define _WIN32_WINNT 0x0501
#include <ws2tcpip.h>
#include <winsock2.h>
#include <windows.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <termios.h>
#endif
#define VERSION "0.7.1"
#define IN_NAME "mcrcon"
#define VER_STR IN_NAME" "VERSION" (built: "__DATE__" "__TIME__")"
#define RCON_EXEC_COMMAND 2
#define RCON_AUTHENTICATE 3
#define RCON_RESPONSEVALUE 0
#define RCON_AUTH_RESPONSE 2
#define RCON_PID 0xBADC0DE
#define DATA_BUFFSIZE 4096
#define MAX_PASSWORD_LENGTH 1024
// rcon packet structure
typedef struct _rc_packet {
int size;
int id;
int cmd;
char data[DATA_BUFFSIZE];
// ignoring string2 for now
} rc_packet;
// ===================================
// FUNCTION DEFINITIONS
// ===================================
// Network related functions
#ifdef _WIN32
void net_init_WSA(void);
#endif
void net_close(int sd);
int net_connect(const char *host, const char *port);
int net_send(int sd, const uint8_t *buffer, size_t size);
int net_send_packet(int sd, rc_packet *packet);
rc_packet* net_recv_packet(int sd);
int net_clean_incoming(int sd, int size);
// Misc stuff
void usage(void);
#ifndef _WIN32
void print_color(int color);
#endif
int get_line(char *buffer, int len);
int run_terminal_mode(int sock);
int run_commands(int argc, char *argv[]);
char* get_pass(char* host);
// Rcon protocol related functions
rc_packet* packet_build(int id, int cmd, char *s1);
void packet_print(rc_packet *packet);
int rcon_auth(int sock, char *passwd);
int rcon_command(int sock, char *command);
// =============================================
// GLOBAL VARIABLES
// =============================================
static int global_raw_output = 0;
static int global_silent_mode = 0;
static int global_disable_colors = 0;
static int global_connection_alive = 1;
static int global_rsock;
static int global_wait_seconds = 0;
#ifdef _WIN32
// console coloring on windows
HANDLE console_handle;
#endif
// safety stuff (windows is still misbehaving)
void exit_proc(void)
{
if (global_rsock != -1)
net_close(global_rsock);
}
// Check windows & linux behaviour !!!
void sighandler(/*int sig*/)
{
global_connection_alive = 0;
#ifndef _WIN32
exit(EXIT_SUCCESS);
#endif
}
#define MAX_WAIT_TIME 600
unsigned int mcrcon_parse_seconds(char *str)
{
char *end;
long result = strtol(str, &end, 10);
if (errno != 0) {
fprintf(stderr, "-w invalid value.\nerror %d: %s\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
if (end == str) {
fprintf(stderr, "-w invalid value (not a number?)\n");
exit(EXIT_FAILURE);
}
if (result <= 0 || result > MAX_WAIT_TIME) {
fprintf(stderr, "-w value out of range.\nAcceptable value is 1 - %d (seconds).\n", MAX_WAIT_TIME);
exit(EXIT_FAILURE);
}
return (unsigned int) result;
}
int main(int argc, char *argv[])
{
int terminal_mode = 0;
char *host = getenv("MCRCON_HOST");
char *pass = getenv("MCRCON_PASS");
char *port = getenv("MCRCON_PORT");
if (!port) port = "25575";
if (!host) host = "localhost";
if(argc < 1 && pass == NULL) usage();
// default getopt error handler enabled
opterr = 1;
int opt;
while ((opt = getopt(argc, argv, "vrtcshw:H:p:P:")) != -1)
{
switch (opt) {
case 'H': host = optarg; break;
case 'P': port = optarg; break;
case 'p': pass = optarg; break;
case 'c': global_disable_colors = 1; break;
case 's': global_silent_mode = 1; break;
case 'i': /* reserved for interp mode */break;
case 't': terminal_mode = 1; break;
case 'r': global_raw_output = 1; break;
case 'w':
global_wait_seconds = mcrcon_parse_seconds(optarg);
break;
case 'v':
puts(VER_STR" - https://github.com/Tiiffi/mcrcon");
puts("Bug reports:\n\ttiiffi+mcrcon at gmail\n\thttps://github.com/Tiiffi/mcrcon/issues/");
exit(EXIT_SUCCESS);
case 'h': usage(); break;
case '?':
default:
puts("Try 'mcrcon -h' or 'man mcrcon' for help.");
exit(EXIT_FAILURE);
}
}
if (pass == NULL) {
// prompt user for password so it isn't displayed in plaintext
pass = get_pass(host);
if (!pass)
{
puts("You must give password (-p password).\nTry 'mcrcon -h' or 'man mcrcon' for help.");
return 0;
}
}
if(optind == argc && terminal_mode == 0)
terminal_mode = 1;
// safety features to prevent "IO: Connection reset" bug on the server side
atexit(&exit_proc);
signal(SIGABRT, &sighandler);
signal(SIGTERM, &sighandler);
signal(SIGINT, &sighandler);
#ifdef _WIN32
net_init_WSA();
console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
if (console_handle == INVALID_HANDLE_VALUE)
console_handle = NULL;
#endif
// open socket
global_rsock = net_connect(host, port);
int exit_code = EXIT_SUCCESS;
// auth & commands
if (rcon_auth(global_rsock, pass)) {
if (terminal_mode)
run_terminal_mode(global_rsock);
else
exit_code = run_commands(argc, argv);
}
else { // auth failed
fprintf(stdout, "Authentication failed!\n");
exit_code = EXIT_FAILURE;
}
net_close(global_rsock);
global_rsock = -1;
return exit_code;
}
void usage(void)
{
puts(
"Usage: "IN_NAME" [OPTIONS] [COMMANDS]\n\n"
"Send rcon commands to Minecraft server.\n\n"
"Options:\n"
" -H\t\tServer address (default: localhost)\n"
" -P\t\tPort (default: 25575)\n"
" -p\t\tRcon password\n"
" -t\t\tTerminal mode\n"
" -s\t\tSilent mode\n"
" -c\t\tDisable colors\n"
" -r\t\tOutput raw packets\n"
" -w\t\tWait for specified duration (seconds) between each command (1 - 600s)\n"
" -h\t\tPrint usage\n"
" -v\t\tVersion information\n\n"
"Server address, port and password can be set with following environment variables:\n"
" MCRCON_HOST\n"
" MCRCON_PORT\n"
" MCRCON_PASS\n"
);
puts (
"- mcrcon will start in terminal mode if no commands are given\n"
"- Command-line options will override environment variables\n"
"- Rcon commands with spaces must be enclosed in quotes\n"
);
puts("Example:\n\t"IN_NAME" -H my.minecraft.server -p password -w 5 \"say Server is restarting!\" save-all stop\n");
#ifdef _WIN32
puts("Press enter to exit.");
getchar();
#endif
exit(EXIT_SUCCESS);
}
#ifdef _WIN32
void net_init_WSA(void)
{
WSADATA wsadata;
// Request winsock 2.2 for now.
// Should be compatible down to Win XP.
WORD version = MAKEWORD(2, 2);
int err = WSAStartup(version, &wsadata);
if (err != 0) {
fprintf(stderr, "WSAStartup failed. Error: %d.\n", err);
exit(EXIT_FAILURE);
}
}
#endif
// socket close and cleanup
void net_close(int sd)
{
#ifdef _WIN32
closesocket(sd);
WSACleanup();
#else
close(sd);
#endif
}
// Opens and connects socket
// http://man7.org/linux/man-pages/man3/getaddrinfo.3.html
// https://bugs.chromium.org/p/chromium/issues/detail?id=44489
int net_connect(const char *host, const char *port)
{
int sd;
struct addrinfo hints;
struct addrinfo *server_info, *p;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
#ifdef _WIN32
net_init_WSA();
#endif
int ret = getaddrinfo(host, port, &hints, &server_info);
if (ret != 0) {
fprintf(stderr, "Name resolution failed.\n");
#ifdef _WIN32
fprintf(stderr, "Error %d: %s", ret, gai_strerror(ret));
#else
fprintf(stderr, "Error %d: %s\n", ret, gai_strerror(ret));
#endif
exit(EXIT_FAILURE);
}
// Go through the hosts and try to connect
for (p = server_info; p != NULL; p = p->ai_next) {
sd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sd == -1)
continue;
ret = connect(sd, p->ai_addr, p->ai_addrlen);
if (ret == -1) {
net_close(sd);
continue;
}
// Get out of the loop when connect is successful
break;
}
if (p == NULL) {
/* TODO (Tiiffi): Check why windows does not report errors */
fprintf(stderr, "Connection failed.\n");
#ifndef _WIN32
fprintf(stderr, "Error %d: %s\n", errno, strerror(errno));
#endif
freeaddrinfo(server_info);
exit(EXIT_FAILURE);
}
freeaddrinfo(server_info);
return sd;
}
int net_send(int sd, const uint8_t *buff, size_t size)
{
size_t sent = 0;
size_t left = size;
while (sent < size) {
int result = send(sd, (const char *) buff + sent, left, 0);
if (result == -1)
return -1;
sent += result;
left -= sent;
}
return 0;
}
int net_send_packet(int sd, rc_packet *packet)
{
int len;
int total = 0; // bytes we've sent
int bytesleft; // bytes left to send
int ret = -1;
bytesleft = len = packet->size + sizeof(int);
while (total < len) {
ret = send(sd, (char *) packet + total, bytesleft, 0);
if(ret == -1) break;
total += ret;
bytesleft -= ret;
}
return ret == -1 ? -1 : 1;
}
rc_packet *net_recv_packet(int sd)
{
int psize;
static rc_packet packet = {0, 0, 0, { 0x00 }};
// packet.size = packet.id = packet.cmd = 0;
int ret = recv(sd, (char *) &psize, sizeof(int), 0);
if (ret == 0) {
fprintf(stderr, "Connection lost.\n");
global_connection_alive = 0;
return NULL;
}
if (ret != sizeof(int)) {
fprintf(stderr, "Error: recv() failed. Invalid packet size (%d).\n", ret);
global_connection_alive = 0;
return NULL;
}
if (psize < 10 || psize > DATA_BUFFSIZE) {
fprintf(stderr, "Warning: invalid packet size (%d). Must over 10 and less than %d.\n", psize, DATA_BUFFSIZE);
if(psize > DATA_BUFFSIZE || psize < 0) psize = DATA_BUFFSIZE;
net_clean_incoming(sd, psize);
return NULL;
}
packet.size = psize;
int received = 0;
while (received < psize) {
ret = recv(sd, (char *) &packet + sizeof(int) + received, psize - received, 0);
if (ret == 0) { /* connection closed before completing receving */
fprintf(stderr, "Connection lost.\n");
global_connection_alive = 0;
return NULL;
}
received += ret;
}
return &packet;
}
int net_clean_incoming(int sd, int size)
{
char tmp[size];
int ret = recv(sd, tmp, size, 0);
if(ret == 0) {
fprintf(stderr, "Connection lost.\n");
global_connection_alive = 0;
}
return ret;
}
void print_color(int color)
{
// sh compatible color array
#ifndef _WIN32
char *colors[] = {
"\033[0;30m", /* 00 BLACK 0x30 */
"\033[0;34m", /* 01 BLUE 0x31 */
"\033[0;32m", /* 02 GREEN 0x32 */
"\033[0;36m", /* 03 CYAN 0x33 */
"\033[0;31m", /* 04 RED 0x34 */
"\033[0;35m", /* 05 PURPLE 0x35 */
"\033[0;33m", /* 06 GOLD 0x36 */
"\033[0;37m", /* 07 GREY 0x37 */
"\033[0;1;30m", /* 08 DGREY 0x38 */
"\033[0;1;34m", /* 09 LBLUE 0x39 */
"\033[0;1;32m", /* 10 LGREEN 0x61 */
"\033[0:1;36m", /* 11 LCYAN 0x62 */
"\033[0;1;31m", /* 12 LRED 0x63 */
"\033[0;1;35m", /* 13 LPURPLE 0x64 */
"\033[0;1;33m", /* 14 YELLOW 0x65 */
"\033[0;1;37m", /* 15 WHITE 0x66 */
"\033[4m" /* 16 UNDERLINE 0x6e */
};
/* 0x72: 'r' */
if (color == 0 || color == 0x72) fputs("\033[0m", stdout); /* CANCEL COLOR */
else
#endif
{
if (color >= 0x61 && color <= 0x66) color -= 0x57;
else if (color >= 0x30 && color <= 0x39)
color -= 0x30;
else if (color == 0x6e)
color = 16; /* 0x6e: 'n' */
else return;
#ifndef _WIN32
fputs(colors[color], stdout);
#else
SetConsoleTextAttribute(console_handle, color);
#endif
}
}
// this hacky mess might use some optimizing
void packet_print(rc_packet *packet)
{
if (global_raw_output == 1) {
for (int i = 0; packet->data[i] != 0; ++i)
putchar(packet->data[i]);
return;
}
int i;
int def_color = 0;
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO console_info;
if (GetConsoleScreenBufferInfo(console_handle, &console_info) != 0) {
def_color = console_info.wAttributes + 0x30;
} else def_color = 0x37;
#endif
// colors enabled so try to handle the bukkit colors for terminal
if (global_disable_colors == 0) {
for (i = 0; (unsigned char) packet->data[i] != 0; ++i) {
if (packet->data[i] == 0x0A) print_color(def_color);
else if((unsigned char) packet->data[i] == 0xc2 && (unsigned char) packet->data[i+1] == 0xa7) {
print_color(packet->data[i+=2]);
continue;
}
putchar(packet->data[i]);
}
print_color(def_color); // cancel coloring
}
// strip colors
else {
for (i = 0; (unsigned char) packet->data[i] != 0; ++i) {
if ((unsigned char) packet->data[i] == 0xc2 && (unsigned char) packet->data[i+1] == 0xa7) {
i+=2;
continue;
}
putchar(packet->data[i]);
}
}
// print newline if string has no newline
if (packet->data[i-1] != 10 && packet->data[i-1] != 13) putchar('\n');
}
rc_packet *packet_build(int id, int cmd, char *s1)
{
static rc_packet packet = {0, 0, 0, { 0x00 }};
// size + id + cmd + s1 + s2 NULL terminator
int s1_len = strlen(s1);
if (s1_len > DATA_BUFFSIZE) {
fprintf(stderr, "Warning: Command string too long (%d). Maximum allowed: %d.\n", s1_len, DATA_BUFFSIZE);
return NULL;
}
packet.size = sizeof(int) * 2 + s1_len + 2;
packet.id = id;
packet.cmd = cmd;
strncpy(packet.data, s1, DATA_BUFFSIZE);
return &packet;
}
int rcon_auth(int sock, char *passwd)
{
int ret;
rc_packet *packet = packet_build(RCON_PID, RCON_AUTHENTICATE, passwd);
if (packet == NULL)
return 0;
ret = net_send_packet(sock, packet);
if (!ret)
return 0; // send failed
packet = net_recv_packet(sock);
if (packet == NULL)
return 0;
// return 1 if authentication OK
return packet->id == -1 ? 0 : 1;
}
int rcon_command(int sock, char *command)
{
rc_packet *packet = packet_build(RCON_PID, RCON_EXEC_COMMAND, command);
if (packet == NULL) {
global_connection_alive = 0;
return 0;
}
net_send_packet(sock, packet);
packet = net_recv_packet(sock);
if (packet == NULL)
return 0;
if (packet->id != RCON_PID)
return 0;
if (!global_silent_mode) {
if (packet->size > 10)
packet_print(packet);
}
return 1;
}
int run_commands(int argc, char *argv[])
{
int i = optind;
for (;;) {
if (!rcon_command(global_rsock, argv[i]))
return EXIT_FAILURE;
if (++i >= argc)
return EXIT_SUCCESS;
if (global_wait_seconds > 0) {
#ifdef _WIN32
Sleep(global_wait_seconds * 1000);
#else
sleep(global_wait_seconds);
#endif
}
}
}
// prompt user for password while hiding input
char* get_pass(char* host)
{
char* pass = malloc(MAX_PASSWORD_LENGTH);
// hide password input
// https://stackoverflow.com/questions/6899025/hide-user-input-on-password-prompt
#ifdef _WIN32
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
#else
struct termios oldt;
tcgetattr(STDIN_FILENO, &oldt);
struct termios newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
#endif
printf("Enter password for %s:", host);
char c;
int i = 0;
while ( (c = getc(stdin)) != '\n' && i < MAX_PASSWORD_LENGTH)
pass[i++] = c;
pass[i] = '\0';
// reset console mode and hash password
#ifdef _WIN32
SetConsoleMode(hStdin, mode);
#else
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
#endif
putc('\n', stdout);
return pass;
}
// interactive terminal mode
int run_terminal_mode(int sock)
{
int ret = 0;
char command[DATA_BUFFSIZE] = {0x00};
puts("Logged in. Type 'quit' or 'exit' to quit.");
while (global_connection_alive) {
putchar('>');
int len = get_line(command, DATA_BUFFSIZE);
if ((strcasecmp(command, "exit") && strcasecmp(command, "quit")) == 0)
break;
if(command[0] == 'Q' && command[1] == 0)
break;
if(len > 0 && global_connection_alive)
ret += rcon_command(sock, command);
/* Special case for "stop" command to prevent server-side bug.
* https://bugs.mojang.com/browse/MC-154617
*
* NOTE: This is hacky workaround which should be handled better to
* ensure compatibility with other servers using source RCON.
* NOTE: strcasecmp() is POSIX function.
*/
if (strcasecmp(command, "stop") == 0) {
break;
}
command[0] = len = 0;
}
return ret;
}
// gets line from stdin and deals with rubbish left in the input buffer
int get_line(char *buffer, int bsize)
{
char *ret = fgets(buffer, bsize, stdin);
if (ret == NULL)
exit(EXIT_FAILURE);
if (buffer[0] == 0)
global_connection_alive = 0;
// remove unwanted characters from the buffer
buffer[strcspn(buffer, "\r\n")] = '\0';
int len = strlen(buffer);
// clean input buffer if needed
if (len == bsize - 1) {
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
return len;
}
|
the_stack_data/117329191.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (c) 2020 Collabora Ltd.
*
* Benchmark and test syscall user dispatch
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/sysinfo.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#ifndef PR_SET_SYSCALL_USER_DISPATCH
# define PR_SET_SYSCALL_USER_DISPATCH 59
# define PR_SYS_DISPATCH_OFF 0
# define PR_SYS_DISPATCH_ON 1
# define SYSCALL_DISPATCH_FILTER_ALLOW 0
# define SYSCALL_DISPATCH_FILTER_BLOCK 1
#endif
#ifdef __NR_syscalls
# define MAGIC_SYSCALL_1 (__NR_syscalls + 1) /* Bad Linux syscall number */
#else
# define MAGIC_SYSCALL_1 (0xff00) /* Bad Linux syscall number */
#endif
/*
* To test returning from a sigsys with selector blocked, the test
* requires some per-architecture support (i.e. knowledge about the
* signal trampoline address). On i386, we know it is on the vdso, and
* a small trampoline is open-coded for x86_64. Other architectures
* that have a trampoline in the vdso will support TEST_BLOCKED_RETURN
* out of the box, but don't enable them until they support syscall user
* dispatch.
*/
#if defined(__x86_64__) || defined(__i386__)
#define TEST_BLOCKED_RETURN
#endif
#ifdef __x86_64__
void* (syscall_dispatcher_start)(void);
void* (syscall_dispatcher_end)(void);
#else
unsigned long syscall_dispatcher_start = 0;
unsigned long syscall_dispatcher_end = 0;
#endif
unsigned long trapped_call_count = 0;
unsigned long native_call_count = 0;
char selector;
#define SYSCALL_BLOCK (selector = SYSCALL_DISPATCH_FILTER_BLOCK)
#define SYSCALL_UNBLOCK (selector = SYSCALL_DISPATCH_FILTER_ALLOW)
#define CALIBRATION_STEP 100000
#define CALIBRATE_TO_SECS 5
int factor;
static double one_sysinfo_step(void)
{
struct timespec t1, t2;
int i;
struct sysinfo info;
clock_gettime(CLOCK_MONOTONIC, &t1);
for (i = 0; i < CALIBRATION_STEP; i++)
sysinfo(&info);
clock_gettime(CLOCK_MONOTONIC, &t2);
return (t2.tv_sec - t1.tv_sec) + 1.0e-9 * (t2.tv_nsec - t1.tv_nsec);
}
static void calibrate_set(void)
{
double elapsed = 0;
printf("Calibrating test set to last ~%d seconds...\n", CALIBRATE_TO_SECS);
while (elapsed < 1) {
elapsed += one_sysinfo_step();
factor += CALIBRATE_TO_SECS;
}
printf("test iterations = %d\n", CALIBRATION_STEP * factor);
}
static double perf_syscall(void)
{
unsigned int i;
double partial = 0;
for (i = 0; i < factor; ++i)
partial += one_sysinfo_step()/(CALIBRATION_STEP*factor);
return partial;
}
static void handle_sigsys(int sig, siginfo_t *info, void *ucontext)
{
char buf[1024];
int len;
SYSCALL_UNBLOCK;
/* printf and friends are not signal-safe. */
len = snprintf(buf, 1024, "Caught sys_%x\n", info->si_syscall);
write(1, buf, len);
if (info->si_syscall == MAGIC_SYSCALL_1)
trapped_call_count++;
else
native_call_count++;
#ifdef TEST_BLOCKED_RETURN
SYSCALL_BLOCK;
#endif
#ifdef __x86_64__
__asm__ volatile("movq $0xf, %rax");
__asm__ volatile("leaveq");
__asm__ volatile("add $0x8, %rsp");
__asm__ volatile("syscall_dispatcher_start:");
__asm__ volatile("syscall");
__asm__ volatile("nop"); /* Landing pad within dispatcher area */
__asm__ volatile("syscall_dispatcher_end:");
#endif
}
int main(void)
{
struct sigaction act;
double time1, time2;
int ret;
sigset_t mask;
memset(&act, 0, sizeof(act));
sigemptyset(&mask);
act.sa_sigaction = handle_sigsys;
act.sa_flags = SA_SIGINFO;
act.sa_mask = mask;
calibrate_set();
time1 = perf_syscall();
printf("Avg syscall time %.0lfns.\n", time1 * 1.0e9);
ret = sigaction(SIGSYS, &act, NULL);
if (ret) {
perror("Error sigaction:");
exit(-1);
}
fprintf(stderr, "Enabling syscall trapping.\n");
if (prctl(PR_SET_SYSCALL_USER_DISPATCH, PR_SYS_DISPATCH_ON,
syscall_dispatcher_start,
(syscall_dispatcher_end - syscall_dispatcher_start + 1),
&selector)) {
perror("prctl failed\n");
exit(-1);
}
SYSCALL_BLOCK;
syscall(MAGIC_SYSCALL_1);
#ifdef TEST_BLOCKED_RETURN
if (selector == SYSCALL_DISPATCH_FILTER_ALLOW) {
fprintf(stderr, "Failed to return with selector blocked.\n");
exit(-1);
}
#endif
SYSCALL_UNBLOCK;
if (!trapped_call_count) {
fprintf(stderr, "syscall trapping does not work.\n");
exit(-1);
}
time2 = perf_syscall();
if (native_call_count) {
perror("syscall trapping intercepted more syscalls than expected\n");
exit(-1);
}
printf("trapped_call_count %lu, native_call_count %lu.\n",
trapped_call_count, native_call_count);
printf("Avg syscall time %.0lfns.\n", time2 * 1.0e9);
printf("Interception overhead: %.1lf%% (+%.0lfns).\n",
100.0 * (time2 / time1 - 1.0), 1.0e9 * (time2 - time1));
return 0;
}
|
the_stack_data/916959.c
|
/* { dg-do compile } */
/* { dg-options "-fcf-protection" } */
/* { dg-error "'-fcf-protection=full' is not supported for this target" "" { target { ! "i?86-*-* x86_64-*-*" } } 0 } */
|
the_stack_data/94181.c
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_ID_LENGHT 50
enum color {BLACK,RED};
struct outputEntItem
{
struct outputEntItem* next;
struct outputEntItem* prev;
char* entID;
int number;
};
struct outputRelItem
{
struct outputRelItem* next;
struct outputRelItem* prev;
char* relID;
struct outputEntItem* firstOutputEntItem;
struct outputEntItem* lastOutputEntItem;
};
struct givingRelNode
{
struct givingRelNode* left;
struct givingRelNode* right;
struct givingRelNode* p;//parent
enum color color;
struct receivingRelItem* receivingRelItem;
struct entRelItem* entRelItem;
};
struct receivingRelItem
{
struct receivingRelItem* next;
struct entRelItem* entRelItem;
struct givingRelNode* givingRelNode;
};
struct entRelItem
{
struct entRelItem* next;
struct entRelItem* prev;
struct outputRelItem* outputRelItem;
struct outputEntItem* outputEntItem;
struct givingRelNode* givingRelRoot;
struct receivingRelItem* firstReceivingRelItem;
struct receivingRelItem* lastReceivingRelItem;
struct entNode* entNode;
};
struct entNode
{
struct entNode* left;
struct entNode* right;
struct entNode* p;//parent
enum color color;
char* entID;
struct entRelItem* entRelList;
};
struct entNode* globalEntRoot;
struct entNode* globalEntNil;
struct givingRelNode* globalRelRoot;
struct givingRelNode* globalRelNil;
struct outputRelItem* globalOutputRelList;
char globalBuffer[MAX_ID_LENGHT];
int globalBufferLenght;
//OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM
//OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM
//OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM
//OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM
//OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM OUTPUT REL ITEM
struct outputRelItem* searchOutputRelItem()
{
struct outputRelItem* currentItem;
int isFound;
int isToBeAdded;
int comparison;
currentItem=globalOutputRelList;
isFound=0;
isToBeAdded=0;
while(currentItem!=NULL&&!isFound&&!isToBeAdded)
{
comparison=strcmp(globalBuffer,currentItem->relID);
if(comparison==0)
isFound=1;
else if(comparison<0)
isToBeAdded=1;
else
currentItem=currentItem->next;
}
if(!isFound)
return NULL;
else
return currentItem;
}
struct outputRelItem* createOutputRelItem()
{
struct outputRelItem* currentItem;
struct outputRelItem* prevItem;
struct outputRelItem* newItem;
int isToBeAdded;
int comparison;
currentItem=globalOutputRelList;
prevItem=NULL;
isToBeAdded=0;
while(currentItem!=NULL&&!isToBeAdded)
{
comparison=strcmp(globalBuffer,currentItem->relID);
if(comparison<0)
isToBeAdded=1;
else
{
prevItem=currentItem;
currentItem=currentItem->next;
}
}
newItem=(struct outputRelItem*)malloc(sizeof(struct outputRelItem));
newItem->firstOutputEntItem=NULL;
newItem->lastOutputEntItem=NULL;
newItem->next=currentItem;
newItem->prev=prevItem;
newItem->relID=(char*)malloc(globalBufferLenght*sizeof(char));
strcpy(newItem->relID,globalBuffer);
if(NULL!=currentItem)
currentItem->prev=newItem;
if(prevItem==NULL)
globalOutputRelList=newItem;
else
prevItem->next=newItem;
return newItem;
}
void deleteOutputRelItem(struct outputRelItem* toDelete)
{
struct outputRelItem* prev;
struct outputRelItem* next;
prev=toDelete->prev;
next=toDelete->next;
if(NULL!=next)
next->prev=prev;
if(NULL==prev)
globalOutputRelList=next;
else
prev->next=next;
free(toDelete->relID);
free(toDelete);
}
//OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM
//OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM
//OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM
//OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM
//OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM OUTPUT ENT ITEM
struct outputEntItem* createOutputEntItem(struct outputRelItem* outputRelItem, char* entID)
{
struct outputEntItem* newItem;
struct outputEntItem* prev;
newItem=(struct outputEntItem*)malloc(sizeof(struct outputEntItem));
newItem->number=1;
newItem->entID=entID;
newItem->next=NULL;
prev=outputRelItem->lastOutputEntItem;
newItem->prev=prev;
if(NULL==prev)
outputRelItem->firstOutputEntItem=newItem;
else
prev->next=newItem;
outputRelItem->lastOutputEntItem=newItem;
return newItem;
}
void outputEntListAddrelFixup(struct outputEntItem* current, struct outputRelItem* outputRelItem)
{
struct outputEntItem* next;
struct outputEntItem* prev;
struct outputEntItem* startingNext;
struct outputEntItem* startingPrev;
prev=current->prev;
next=current->next;
startingPrev=current->prev;
startingNext=current->next;
while(prev!=NULL&¤t->number>prev->number)
{
next=prev;
prev=prev->prev;
}
while(prev!=NULL&¤t->number==prev->number&&strcmp(current->entID,prev->entID)<0)
{
next=prev;
prev=prev->prev;
}
if(prev!=startingPrev)
{
if(prev==NULL)
outputRelItem->firstOutputEntItem=current;
else
prev->next=current;
next->prev=current;
current->prev=prev;
current->next=next;
startingPrev->next=startingNext;
if(startingNext!=NULL)
startingNext->prev=startingPrev;
else
outputRelItem->lastOutputEntItem=startingPrev;
}
}
void outputEntListDelrelFixup(struct outputEntItem* current, struct outputRelItem* outputRelItem)
{
struct outputEntItem* next;
struct outputEntItem* prev;
struct outputEntItem* startingNext;
struct outputEntItem* startingPrev;
prev=current->prev;
next=current->next;
startingPrev=current->prev;
startingNext=current->next;
while(next!=NULL&¤t->number<next->number)
{
prev=next;
next=next->next;
}
while(next!=NULL&¤t->number==next->number&&strcmp(current->entID,next->entID)>0)
{
prev=next;
next=next->next;
}
if(next!=startingNext)
{
if(next==NULL)
outputRelItem->lastOutputEntItem=current;
else
next->prev=current;
prev->next=current;
current->prev=prev;
current->next=next;
startingNext->prev=startingPrev;
if(startingPrev!=NULL)
startingPrev->next=startingNext;
else
outputRelItem->firstOutputEntItem=startingNext;
}
}
void deleteOutputEntItem(struct outputEntItem* toDelete,struct outputRelItem* outputRelItem)
{
struct outputEntItem* prev;
struct outputEntItem* next;
prev=toDelete->prev;
next=toDelete->next;
if(NULL==next)
outputRelItem->lastOutputEntItem=prev;
else
next->prev=prev;
if(NULL==prev)
outputRelItem->firstOutputEntItem=next;
else
prev->next=next;
free(toDelete);
}
//RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM
//RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM
//RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM
//RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM
//RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM RECEIVING REL ITEM
struct receivingRelItem* createReceivingRelItem(struct givingRelNode* givingRelNode,struct entRelItem* entRelItem,struct entRelItem* entRelItemToConnect)
{
struct receivingRelItem* newItem;
struct receivingRelItem* prev;
newItem=(struct receivingRelItem*)malloc(sizeof(struct receivingRelItem));
newItem->givingRelNode=givingRelNode;
newItem->entRelItem=entRelItemToConnect;
newItem->next=NULL;
if(NULL!=entRelItem->lastReceivingRelItem)
entRelItem->lastReceivingRelItem->next=newItem;
else
entRelItem->firstReceivingRelItem=newItem;
prev=entRelItem->lastReceivingRelItem;
entRelItem->lastReceivingRelItem=newItem;
return prev;
}
void deleteReceivingRelItem(struct receivingRelItem* prev, struct entRelItem* entRelItem)
{
struct receivingRelItem* middle;
struct receivingRelItem* next;
if(NULL==prev)
middle=entRelItem->firstReceivingRelItem;
else
middle=prev->next;
next=middle->next;
if(next!=NULL)
next->givingRelNode->receivingRelItem=prev;
if(prev==NULL)
entRelItem->firstReceivingRelItem=next;
else
prev->next=next;
if(next==NULL)
entRelItem->lastReceivingRelItem=prev;
free(middle);
}
void relDelete(struct givingRelNode* z, struct entRelItem* entRelItem);
void deleteReceivingRelList(struct receivingRelItem* currentItem)
{
struct receivingRelItem* toDelete;
while(NULL!=currentItem)
{
relDelete(currentItem->givingRelNode,currentItem->entRelItem);
toDelete=currentItem;
currentItem=currentItem->next;
free(toDelete);
}
}
//REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE
//REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE
//REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE
//REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE
//REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE REL TREE
struct givingRelNode* searchRelNode(struct entRelItem* toFind, struct givingRelNode* root)
{
struct givingRelNode* node;
int comparison;
node=root;
while (node != globalRelNil)
{
comparison=toFind-node->entRelItem;
if (comparison < 0)
node = node->left;
else if (comparison > 0)
node = node->right;
else
return node;
}
return NULL;
}
void relLeftRotate(struct givingRelNode* x)
{
struct givingRelNode* y = x->right;
x->right = y->left;
if (y->left != globalRelNil)
y->left->p = x;
y->p = x->p;
if (x->p == globalRelNil)
globalRelRoot = y;
else if (x == x->p->left)
x->p->left = y;
else
x->p->right = y;
y->left = x;
x->p = y;
}
void relRightRotate(struct givingRelNode* x)
{
struct givingRelNode* y = x->left;
x->left = y->right;
if (y->right != globalRelNil)
y->right->p = x;
y->p = x->p;
if (x->p == globalRelNil)
globalRelRoot = y;
else if (x == x->p->right)
x->p->right = y;
else
x->p->left = y;
y->right = x;
x->p = y;
}
struct givingRelNode* relTreeMinimum(struct givingRelNode* x)
{
while (x->left != globalRelNil)
x = x->left;
return x;
}
struct givingRelNode* relTreeSuccessor(struct givingRelNode* x)
{
struct givingRelNode* y;
if (x->right != globalRelNil)
return relTreeMinimum(x->right);
y = x->p;
while (y != globalRelNil && x == y->right)
{
x = y;
y = y->p;
}
return y;
}
void relInsertFixup(struct givingRelNode* z)
{
struct givingRelNode* x;
struct givingRelNode* y;
if (z == globalRelRoot)
globalRelRoot->color = BLACK;
else
{
x = z->p;
if (x->color == RED)
{
if (x == x->p->left)
{
y = x->p->right;
if (y->color == RED)
{
x->color = BLACK;
y->color = BLACK;
x->p->color = RED;
relInsertFixup(x->p);
}
else
{
if (z == x->right)
{
z = x;
relLeftRotate(z);
x = z->p;
}
x->color = BLACK;
x->p->color = RED;
relRightRotate(x->p);
}
}
else
{
y = x->p->left;
if (y->color == RED)
{
x->color = BLACK;
y->color = BLACK;
x->p->color = RED;
relInsertFixup(x->p);
}
else
{
if (z == x->left)
{
z = x;
relRightRotate(z);
x = z->p;
}
x->color = BLACK;
x->p->color = RED;
relLeftRotate(x->p);
}
}
}
}
}
struct givingRelNode* relInsert(struct entRelItem* toFind)
{
int comparison;
struct givingRelNode* z;
struct givingRelNode* y;
struct givingRelNode* x;
y = globalRelNil;
x = globalRelRoot;
while (x != globalRelNil)
{
y = x;
comparison=toFind-x->entRelItem;
if (comparison < 0)
x = x->left;
else if (comparison > 0)
x = x->right;
else
return NULL;
}
z=(struct givingRelNode*)malloc(sizeof(struct givingRelNode));
z->entRelItem=toFind;
z->p = y;
if (y == globalRelNil)
globalRelRoot = z;
else if (comparison < 0)
y->left = z;
else
y->right = z;
z->left = globalRelNil;
z->right = globalRelNil;
z->color = RED;
relInsertFixup(z);
return z;
}
void relDeleteFixup(struct givingRelNode* x)
{
struct givingRelNode* w;
if (x->color == RED || x->p == globalRelNil)
x->color = BLACK;
else if (x == x->p->left)
{
w = x->p->right;
if (w->color == RED)
{
w->color = BLACK;
x->p->color = RED;
relLeftRotate(x->p);
w = x->p->right;
}
if (w->left->color == BLACK && w->right->color == BLACK)
{
w->color = RED;
relDeleteFixup(x->p);
}
else
{
if (w->right->color == BLACK)
{
w->left->color = BLACK;
w->color = RED;
relRightRotate(w);
w = x->p->right;
}
w->color = x->p->color;
x->p->color = BLACK;
w->right->color = BLACK;
relLeftRotate(x->p);
}
}
else
{
w = x->p->left;
if (w->color == RED)
{
w->color = BLACK;
x->p->color = RED;
relRightRotate(x->p);
w = x->p->left;
}
if (w->right->color == BLACK && w->left->color == BLACK)
{
w->color = RED;
relDeleteFixup(x->p);
}
else
{
if (w->left->color == BLACK)
{
w->right->color = BLACK;
w->color = RED;
relLeftRotate(w);
w = x->p->left;
}
w->color = x->p->color;
x->p->color = BLACK;
w->left->color = BLACK;
relRightRotate(x->p);
}
}
}
void relDelete(struct givingRelNode* z, struct entRelItem* entRelItem)
{
struct receivingRelItem* receivingRelItem;
struct givingRelNode* y;
struct givingRelNode* x;
globalRelRoot=entRelItem->givingRelRoot;
if (z->left == globalRelNil || z->right == globalRelNil)
y = z;
else
y = relTreeSuccessor(z);
if (y->left != globalRelNil)
x = y->left;
else
x = y->right;
x->p = y->p;
if (y->p == globalRelNil)
globalRelRoot = x;
else if (y == y->p->left)
y->p->left = x;
else
y->p->right = x;
if (y != z)
{
z->entRelItem = y->entRelItem;
z->receivingRelItem=y->receivingRelItem;
if(z->receivingRelItem!=NULL)
{
z->receivingRelItem->next->givingRelNode=z;
z->receivingRelItem->next->entRelItem=entRelItem;
}
else
{
z->entRelItem->firstReceivingRelItem->givingRelNode=z;
z->entRelItem->firstReceivingRelItem->entRelItem=entRelItem;
}
}
if (y->color == BLACK)
relDeleteFixup(x);
free(y);
entRelItem->givingRelRoot=globalRelRoot;
}
struct entRelItem* deleteEntRelItem(struct entRelItem* toDelete, struct entNode* entNode);
void deleteGivingRelTree(struct givingRelNode* toDelete, struct outputRelItem* outputRelItem)
{
struct outputEntItem* outputEntItem;
if(toDelete->right!=globalRelNil)
deleteGivingRelTree(toDelete->right,outputRelItem);
if(toDelete->left!=globalRelNil)
deleteGivingRelTree(toDelete->left,outputRelItem);
deleteReceivingRelItem(toDelete->receivingRelItem,toDelete->entRelItem);
outputEntItem=toDelete->entRelItem->outputEntItem;
outputEntItem->number--;
if(outputEntItem->number==0)
{
deleteOutputEntItem(outputEntItem,outputRelItem);
toDelete->entRelItem->outputEntItem=NULL;
if(globalRelNil==toDelete->entRelItem->givingRelRoot)
deleteEntRelItem(toDelete->entRelItem,toDelete->entRelItem->entNode);
if(NULL==outputRelItem->lastOutputEntItem)
deleteOutputRelItem(outputRelItem);
}
else
outputEntListDelrelFixup(outputEntItem,outputRelItem);
free(toDelete);
}
//ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE
//ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE
//ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE
//ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE
//ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE ENT TREE
struct entNode* searchEntNode()
{
struct entNode* node;
int comparison;
node=globalEntRoot;
while (node != globalEntNil)
{
comparison=strcmp(globalBuffer,node->entID);
if (comparison < 0)
node = node->left;
else if (comparison > 0)
node = node->right;
else
return node;
}
return NULL;
}
void entLeftRotate(struct entNode* x)
{
struct entNode* y = x->right;
x->right = y->left;
if (y->left != globalEntNil)
y->left->p = x;
y->p = x->p;
if (x->p == globalEntNil)
globalEntRoot = y;
else if (x == x->p->left)
x->p->left = y;
else
x->p->right = y;
y->left = x;
x->p = y;
}
void entRightRotate(struct entNode* x)
{
struct entNode* y = x->left;
x->left = y->right;
if (y->right != globalEntNil)
y->right->p = x;
y->p = x->p;
if (x->p == globalEntNil)
globalEntRoot = y;
else if (x == x->p->right)
x->p->right = y;
else
x->p->left = y;
y->right = x;
x->p = y;
}
struct entNode* entTreeMinimum(struct entNode* x)
{
while (x->left != globalEntNil)
x = x->left;
return x;
}
struct entNode* entTreeSuccessor(struct entNode* x)
{
struct entNode* y;
if (x->right != globalEntNil)
return entTreeMinimum(x->right);
y = x->p;
while (y != globalEntNil && x == y->right)
{
x = y;
y = y->p;
}
return y;
}
void entInsertFixup(struct entNode* z)
{
struct entNode* x;
struct entNode* y;
if (z == globalEntRoot)
globalEntRoot->color = BLACK;
else
{
x = z->p;
if (x->color == RED)
{
if (x == x->p->left)
{
y = x->p->right;
if (y->color == RED)
{
x->color = BLACK;
y->color = BLACK;
x->p->color = RED;
entInsertFixup(x->p);
}
else
{
if (z == x->right)
{
z = x;
entLeftRotate(z);
x = z->p;
}
x->color = BLACK;
x->p->color = RED;
entRightRotate(x->p);
}
}
else
{
y = x->p->left;
if (y->color == RED)
{
x->color = BLACK;
y->color = BLACK;
x->p->color = RED;
entInsertFixup(x->p);
}
else
{
if (z == x->left)
{
z = x;
entRightRotate(z);
x = z->p;
}
x->color = BLACK;
x->p->color = RED;
entLeftRotate(x->p);
}
}
}
}
}
void entInsert()
{
int comparison;
struct entNode* z;
struct entNode* y;
struct entNode* x;
y = globalEntNil;
x = globalEntRoot;
while (x != globalEntNil)
{
y = x;
comparison=strcmp(globalBuffer,x->entID);
if (comparison < 0)
x = x->left;
else if (comparison > 0)
x = x->right;
else
return;
}
z=(struct entNode*)malloc(sizeof(struct entNode));
z->entID=(char*)malloc(globalBufferLenght*sizeof(char));
strcpy(z->entID,globalBuffer);
z->p = y;
z->left=globalEntNil;
z->right=globalEntNil;
z->entRelList=NULL;
if (y == globalEntNil)
globalEntRoot = z;
else if (comparison < 0)
y->left = z;
else
y->right = z;
z->color = RED;
entInsertFixup(z);
}
void entDeleteFixup(struct entNode* x)
{
struct entNode* w;
if (x->color == RED || x->p == globalEntNil)
x->color = BLACK;
else if (x == x->p->left)
{
w = x->p->right;
if (w->color == RED)
{
w->color = BLACK;
x->p->color = RED;
entLeftRotate(x->p);
w = x->p->right;
}
if (w->left->color == BLACK && w->right->color == BLACK)
{
w->color = RED;
entDeleteFixup(x->p);
}
else
{
if (w->right->color == BLACK)
{
w->left->color = BLACK;
w->color = RED;
entRightRotate(w);
w = x->p->right;
}
w->color = x->p->color;
x->p->color = BLACK;
w->right->color = BLACK;
entLeftRotate(x->p);
}
}
else
{
w = x->p->left;
if (w->color == RED)
{
w->color = BLACK;
x->p->color = RED;
entRightRotate(x->p);
w = x->p->left;
}
if (w->right->color == BLACK && w->left->color == BLACK)
{
w->color = RED;
entDeleteFixup(x->p);
}
else
{
if (w->left->color == BLACK)
{
w->right->color = BLACK;
w->color = RED;
entLeftRotate(w);
w = x->p->left;
}
w->color = x->p->color;
x->p->color = BLACK;
w->left->color = BLACK;
entRightRotate(x->p);
}
}
}
void entDelete(struct entNode* z)
{
struct entRelItem* fuck;
struct entNode* y;
struct entNode* x;
if (z->left == globalEntNil || z->right == globalEntNil)
y = z;
else
y = entTreeSuccessor(z);
if (y->left != globalEntNil)
x = y->left;
else
x = y->right;
x->p = y->p;
if (y->p == globalEntNil)
globalEntRoot = x;
else if (y == y->p->left)
y->p->left = x;
else
y->p->right = x;
free(z->entID);
if (y != z)
{
z->entID = y->entID;
z->entRelList=y->entRelList;
fuck=y->entRelList;
while(fuck!=NULL)
{
fuck->entNode=z;
fuck=fuck->next;
}
}
if (y->color == BLACK)
entDeleteFixup(x);
free(y);
}
//ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM
//ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM
//ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM
//ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM
//ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM ENT REL ITEM
struct entRelItem* createEntRelItem(struct outputRelItem* outputRelItem, struct entNode* entNode)
{
struct entRelItem* currentItem;
struct entRelItem* prevItem;
struct entRelItem* newItem;
currentItem=entNode->entRelList;
prevItem=NULL;
while(currentItem!=NULL)
{
prevItem=currentItem;
currentItem=currentItem->next;
}
newItem=(struct entRelItem*)malloc(sizeof(struct entRelItem));
newItem->givingRelRoot=globalRelNil;
newItem->firstReceivingRelItem=NULL;
newItem->lastReceivingRelItem=NULL;
newItem->outputRelItem=outputRelItem;
newItem->outputEntItem=NULL;
newItem->entNode=entNode;
newItem->next=NULL;
newItem->prev=prevItem;
if(prevItem==NULL)
entNode->entRelList=newItem;
else
prevItem->next=newItem;
return newItem;
}
struct entRelItem* searchEntRelItem(struct outputRelItem* outputRelItem, struct entNode* entNode)
{
struct entRelItem* currentItem;
int isFound;
int comparison;
currentItem=entNode->entRelList;
isFound=0;
while(currentItem!=NULL&&!isFound)
{
comparison=outputRelItem-currentItem->outputRelItem;
if(comparison==0)
isFound=1;
else
currentItem=currentItem->next;
}
if(!isFound)
return createEntRelItem(outputRelItem,entNode);
else
return currentItem;
}
struct entRelItem* deleteEntRelItem(struct entRelItem* toDelete, struct entNode* entNode)
{
struct entRelItem* prev;
struct entRelItem* next;
prev=toDelete->prev;
next=toDelete->next;
if(NULL!=next)
next->prev=prev;
if(NULL==prev)
entNode->entRelList=next;
else
prev->next=next;
free(toDelete);
}
//EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA
//EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA
//EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA
//EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA
//EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA EXTRA
void readID()
{
getchar();
if(getchar()=='\"')
{
char c;
int IDLenght;
globalBufferLenght=0;
c=getchar();
while(c!='\"')
{
globalBuffer[globalBufferLenght]=c;
globalBufferLenght++;
c=getchar();
}
globalBuffer[globalBufferLenght]='\0';
globalBufferLenght++;
}
}
//ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT
//ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT
//ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT
//ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT
//ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT ADDENT
void addent()
{
readID();
entInsert();
}
//ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL
//ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL
//ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL
//ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL
//ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL ADDREL ADRREL ADDREL
void addrel()
{
struct entNode* entNode1;
struct entNode* entNode2;
struct outputRelItem* outputRelItem;
struct entRelItem* entRelItem1;
struct entRelItem* entRelItem2;
struct givingRelNode* insertedGivingRelNode;
struct receivingRelItem* receivingRelItem;
struct outputEntItem* outputEntItem;
char* ID;
readID();
entNode1=searchEntNode();
readID();
entNode2=searchEntNode();
readID();
if(entNode1!=NULL&&entNode2!=NULL)
{
outputRelItem=searchOutputRelItem();
if(NULL==outputRelItem)
outputRelItem=createOutputRelItem();
entRelItem1=searchEntRelItem(outputRelItem,entNode1);
entRelItem2=searchEntRelItem(outputRelItem,entNode2);
globalRelRoot=entRelItem1->givingRelRoot;
insertedGivingRelNode=relInsert(entRelItem2);
entRelItem1->givingRelRoot=globalRelRoot;
if(NULL!=insertedGivingRelNode)
{
receivingRelItem=createReceivingRelItem(insertedGivingRelNode,entRelItem2,entRelItem1);
insertedGivingRelNode->receivingRelItem=receivingRelItem;
insertedGivingRelNode->entRelItem=entRelItem2;
outputEntItem=entRelItem2->outputEntItem;
if(NULL==outputEntItem)
{
outputEntItem=createOutputEntItem(outputRelItem,entNode2->entID);
entRelItem2->outputEntItem=outputEntItem;
}
else
outputEntItem->number++;
outputEntListAddrelFixup(outputEntItem,outputRelItem);
}
}
}
//DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL
//DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL
//DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL
//DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL
//DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL DELREL
void delrel()
{
struct entNode* entNode1;
struct entNode* entNode2;
struct outputRelItem* outputRelItem;
struct entRelItem* entRelItem1;
struct entRelItem* entRelItem2;
struct givingRelNode* givingRelNodeToDelete;
struct receivingRelItem* receivingRelItemToDelete;
struct outputEntItem* outputEntItem;
char* ID;
readID();
entNode1=searchEntNode();
readID();
entNode2=searchEntNode();
readID();
if(entNode1!=NULL&&entNode2!=NULL)
{
outputRelItem=searchOutputRelItem();
if(NULL!=outputRelItem)
{
entRelItem1=searchEntRelItem(outputRelItem,entNode1);
entRelItem2=searchEntRelItem(outputRelItem,entNode2);
if(NULL!=entRelItem1&&NULL!=entRelItem2)
{
givingRelNodeToDelete=searchRelNode(entRelItem2,entRelItem1->givingRelRoot);
if(NULL!=givingRelNodeToDelete)
{
receivingRelItemToDelete=givingRelNodeToDelete->receivingRelItem;
deleteReceivingRelItem(receivingRelItemToDelete,entRelItem2);
relDelete(givingRelNodeToDelete,entRelItem1);
outputEntItem=entRelItem2->outputEntItem;
outputEntItem->number--;
if(outputEntItem->number==0)
{
deleteOutputEntItem(outputEntItem,outputRelItem);
entRelItem2->outputEntItem=NULL;
if(entRelItem1!=entRelItem2&&globalRelNil==entRelItem2->givingRelRoot)
deleteEntRelItem(entRelItem2,entNode2);
if(NULL==outputRelItem->lastOutputEntItem)
deleteOutputRelItem(outputRelItem);
}
else
outputEntListDelrelFixup(outputEntItem,outputRelItem);
if(globalRelNil==entRelItem1->givingRelRoot&&NULL==entRelItem1->firstReceivingRelItem)
deleteEntRelItem(entRelItem1,entNode1);
}
}
}
}
}
//DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT
//DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT
//DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT
//DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT
//DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT DELENT
void delent()
{
struct entNode* entNode;
struct entRelItem* entRelItem;
struct entRelItem* toDelete;
char* ID;
readID();
entNode=searchEntNode();
if(NULL!=entNode)
{
entRelItem=entNode->entRelList;
while(NULL!=entRelItem)
{
deleteReceivingRelList(entRelItem->firstReceivingRelItem);
if(globalRelNil!=entRelItem->givingRelRoot)
deleteGivingRelTree(entRelItem->givingRelRoot,entRelItem->outputRelItem); //outputRelItem to add variable
toDelete=entRelItem;
entRelItem=entRelItem->next;
if(NULL!=toDelete->outputEntItem)
{
deleteOutputEntItem(toDelete->outputEntItem,toDelete->outputRelItem);
if(NULL==toDelete->outputRelItem->lastOutputEntItem)
deleteOutputRelItem(toDelete->outputRelItem);
}
free(toDelete);
}
entDelete(entNode);
}
}
//REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT
//REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT
//REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT
//REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT
//REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT REPORT
void report()
{
struct outputEntItem* currentItem;
struct outputEntItem* prevItem;
struct outputRelItem* relItem;
int number;
relItem=globalOutputRelList;
if(relItem==NULL)
{
printf("none\n");
}
else
{
while(relItem!=NULL)
{
fputs("\"",stdout);
fputs(relItem->relID,stdout);
fputs("\"",stdout);
currentItem=relItem->firstOutputEntItem;
fputs(" \"",stdout);
fputs(currentItem->entID,stdout);
fputs("\"",stdout);
number=currentItem->number;
currentItem=currentItem->next;
while(currentItem!=NULL&&number==currentItem->number)
{
fputs(" \"",stdout);
fputs(currentItem->entID,stdout);
fputs("\"",stdout);
currentItem=currentItem->next;
}
printf(" %d; ",number);
relItem=relItem->next;
}
printf("\n");
}
}
//MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN
//MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN
//MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN
//MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN
//MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN
int main()
{
globalOutputRelList=NULL;
globalEntNil=(struct entNode*)malloc(sizeof(struct entNode));
globalEntNil->entID="NIL";
globalEntNil->color=BLACK;
globalEntNil->left=globalEntNil;
globalEntNil->right=globalEntNil;
globalEntRoot=globalEntNil;
globalRelNil=(struct givingRelNode*)malloc(sizeof(struct givingRelNode));
globalRelNil->color=BLACK;
globalRelNil->left=globalRelNil;
globalRelNil->right=globalRelNil;
char commandID[4];
do
{
fgets(commandID,4,stdin);
if(strcmp(commandID,"add")==0)
{
fgets(commandID,4,stdin);
if(strcmp(commandID,"ent")==0)
addent();
else if(strcmp(commandID,"rel")==0)
addrel();
}
else if(strcmp(commandID,"del")==0)
{
fgets(commandID,4,stdin);
if(strcmp(commandID,"ent")==0)
delent();
else if(strcmp(commandID,"rel")==0)
delrel();
}
else if(strcmp(commandID,"rep")==0)
{
fgets(commandID,4,stdin);
if(strcmp(commandID,"ort")==0)
report();
}
else if(strcmp(commandID,"end")==0)
return 0;
}
while(getchar()!=EOF);
}
|
the_stack_data/961257.c
|
#include <stdio.h>
void main(void)
{
printf("quack!");
}
|
the_stack_data/52009.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_is_prime.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akharrou <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/26 23:59:35 by akharrou #+# #+# */
/* Updated: 2018/10/29 08:47:42 by akharrou ### ########.fr */
/* */
/* ************************************************************************** */
int ft_is_prime(int nb)
{
long i;
long result;
if (nb < 2)
return (0);
if (nb == 2 || nb == 3 || nb == 5 || nb == 7)
return (1);
if (nb % 2 == 0 || nb % 3 == 0 || nb % 5 == 0 || nb % 7 == 0)
return (0);
i = 11;
while ((result = i * i) < nb)
{
if (nb % i == 0 || result > 2147483647)
return (0);
i += 2;
}
return (1);
}
|
the_stack_data/43887720.c
|
/* PR40052 */
/* { dg-do compile } */
/* { dg-options "-O -ftree-vrp -fno-tree-ccp -fdump-tree-optimized" } */
int foo(_Bool b)
{
return b | 1;
}
int bar(_Bool b)
{
return b & -2;
}
/* { dg-final { scan-tree-dump "return 0;" "optimized" } } */
/* { dg-final { scan-tree-dump "return 1;" "optimized" } } */
|
the_stack_data/734884.c
|
/*
* autostatic.c
*
* Description:
* This translation unit implements static auto-init and auto-exit logic.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: [email protected]
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* 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 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 in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#if defined(PTW32_STATIC_LIB)
#if defined(__MINGW64__) || defined(__MINGW32__) || defined(_MSC_VER)
#include "pthread.h"
#include "implement.h"
static void on_process_init(void)
{
pthread_win32_process_attach_np ();
}
static void on_process_exit(void)
{
pthread_win32_thread_detach_np ();
pthread_win32_process_detach_np ();
}
#if defined(__MINGW64__) || defined(__MINGW32__)
# define attribute_section(a) __attribute__((section(a)))
#elif defined(_MSC_VER)
# define attribute_section(a) __pragma(section(a,long,read)); __declspec(allocate(a))
#endif
attribute_section(".ctors") void *gcc_ctor = on_process_init;
attribute_section(".dtors") void *gcc_dtor = on_process_exit;
attribute_section(".CRT$XCU") void *msc_ctor = on_process_init;
attribute_section(".CRT$XPU") void *msc_dtor = on_process_exit;
#endif /* defined(__MINGW64__) || defined(__MINGW32__) || defined(_MSC_VER) */
#endif /* PTW32_STATIC_LIB */
|
the_stack_data/1063890.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* TEST.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lpaulo-m <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/23 20:12:40 by lpaulo-m #+# #+# */
/* Updated: 2021/01/23 20:18:20 by lpaulo-m ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
/*
** https://www.codechef.com/problems/TEST
*/
int main(void)
{
int answer;
while (1)
{
scanf("%d", &answer);
if (answer == 42)
break ;
printf("%d\n", answer);
}
return (0);
}
|
the_stack_data/156392003.c
|
#include<stdio.h>
#include<stdlib.h>
int nextMax(int array[],int n){
int size=2*n;
int temp=array[1];
array[1]=0;
int i=1;
for( i=1;i<=size/2;){
if(array[i*2]==temp){
array[i*2]=0;
i=i*2;
}
else{
array[i*2+1]=0;
i=i*2+1;
}
}
while(1){
if(i==0)
break;
if(i%2==0){
if(array[i]>array[i+1])
array[i/2]=array[i];
else
array[i/2]=array[i+1];
i=i/2;
}
else{
if(array[i]>array[i-1])
array[i/2]=array[i];
else
array[i/2]=array[i-1];
i=i/2;
}
}
return array[1];
}
void build(int array[],int n){
int size=2*n;
for(int i=size-1;i>=n;i-=2){
if(array[i]>array[i-1])
array[i/2]=array[i];
else
array[i/2]=array[i-1];
}
if(n/2!=0)
build(array,n/2);
}
int main(){
int n;
scanf("%d",&n);
int size=2*n;
int *array=(int *)malloc(size * sizeof(int) );
for(int i=n;i<size;i++)
scanf("%d",&array[i]);
build(array,n);
for(int i=1;i<size;i++)
printf("%d ",array[i]);
printf("nextmax %d \n",nextMax(array,n));
}
|
the_stack_data/53381.c
|
#define NDEBUG // Comment this out if you want assertion checking.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <assert.h>
#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <alloca.h>
#elif defined(_MSC_VER)
#include <malloc.h>
#define restrict __restrict
#endif
#ifdef __GNUC__
#define ATTRIBUTE(a) __attribute__(a)
#else
#define ATTRIBUTE(a)
#endif
#define LOW INT32_MIN // the lowest possible value of an Element
#define SCN_ELEM SCNd32 // to scan an Element
#define PRI_ELEM PRId32 // to print an Element
#define PRI_BIGGER PRIdFAST64 // to print a Bigger
typedef int32_t Element;
typedef int_fast64_t Bigger; // big enough to add or subtract any two Elements
enum { k_nice_debugging = 0 };
enum { k_nmax = 100000 };
enum { k_no_value = 0 }; // "doesn't mean to hold a value yet"
// MEMORY ALLOCATORS:
ATTRIBUTE (( malloc, returns_nonnull, warn_unused_result ))
static void *xcalloc(const size_t num, const size_t size)
{
void *const p = calloc(num, size);
if (p == NULL) abort();
return p;
}
ATTRIBUTE (( malloc, returns_nonnull, warn_unused_result))
static void *xmalloc(const size_t size)
{
void *const p = malloc(size);
if (p == NULL) abort();
return p;
}
ATTRIBUTE (( returns_nonnull, warn_unused_result))
static void *xrealloc(void *const p, const size_t size)
{
void *const q = realloc(p, size);
if (q == NULL) abort();
return q;
}
// VEC DATA STRUCTURE:
enum { k_vec_initial_capacity = 1 };
static_assert(k_vec_initial_capacity > 0, "initial capacity must be positive");
struct vec {
int length, capacity;
Element *elems;
};
ATTRIBUTE (( nonnull ))
static void vec_append(struct vec *const vp, const Element e)
{
assert(0 <= vp->length && vp->length <= vp->capacity);
if (vp->length == vp->capacity) {
if (vp->capacity == 0) {
assert(vp->elems == NULL);
vp->capacity = k_vec_initial_capacity;
vp->elems = xmalloc(k_vec_initial_capacity * sizeof *vp->elems);
} else {
assert(vp->elems != NULL);
vp->capacity *= 2;
vp->elems = xrealloc(vp->elems,
(size_t)vp->capacity * sizeof *vp->elems);
}
}
vp->elems[vp->length++] = e;
}
#ifdef NDEBUG
ATTRIBUTE (( pure ))
#endif
ATTRIBUTE (( nonnull, warn_unused_result ))
static int vec_index_of(const struct vec *const vp, const Element e)
{
assert(0 <= vp->length && vp->length <= vp->capacity);
assert((vp->capacity == 0) == (vp->elems == NULL));
for (int i = 0; i != vp->length; ++i)
if (vp->elems[i] == e) return i;
return -1;
}
ATTRIBUTE (( nonnull ))
static void vec_erase_at(struct vec *const vp, int i)
{
assert(0 <= i && i < vp->length && vp->length <= vp->capacity);
assert(vp->elems != NULL);
for (--vp->length; i != vp->length; ++i) vp->elems[i] = vp->elems[i + 1];
}
// AD-HOC SET DATA STRUCTURE (the caller must manually do some operations):
#ifdef NDEBUG
ATTRIBUTE (( const ))
#endif
ATTRIBUTE (( warn_unused_result ))
static inline int set_guess_best_bucket_count(const int n)
{
assert(0 < n);
return (int)lroundf((float)n / logf(2.0f));
}
ATTRIBUTE (( malloc, returns_nonnull, warn_unused_result ))
static inline struct vec *set_create(const int slen) // pass bucket count
{
assert(0 < slen);
return xcalloc((size_t)slen, sizeof *set_create(slen));
}
ATTRIBUTE (( nonnull ))
static void set_destroy(const int slen, struct vec *restrict *const sp)
{
assert(0 < slen);
assert(*sp != NULL);
for (int i = 0; i != slen; ++i) {
if ((*sp)[i].capacity != 0) { // no need to check, but it may be sparse
assert((*sp)[i].elems != NULL);
assert(0 <= (*sp)[i].length
&& (*sp)[i].length <= (*sp)[i].capacity);
free((*sp)[i].elems);
(*sp)[i].elems = NULL;
(*sp)[i].capacity = (*sp)[i].length = 0;
}
}
free(*sp);
*sp = NULL;
}
#ifdef NDEBUG
ATTRIBUTE (( const ))
#endif
ATTRIBUTE (( nonnull, warn_unused_result ))
static inline struct vec *set_get_bucket(const int slen, struct vec *const s,
const Element e)
{
// Use http://mathworld.wolfram.com/CommonResidue.html to index the bucket.
const int i = (slen + e % slen) % slen;
assert(0 <= i && i < slen);
return s + i;
}
ATTRIBUTE (( nonnull ))
static inline void set_insert(const int slen, struct vec *const s,
const Element e)
{
struct vec *const bp = set_get_bucket(slen, s, e);
if (vec_index_of(bp, e) == -1) vec_append(bp, e);
}
// COMPUTING RUNNING MEDIANS WITH BOTH INSERTIONS AND REMOVALS:
ATTRIBUTE (( nonnull ))
static inline void print_median(const Element *restrict const a,
const int i) // i indexes the last element in a
{
assert(0 < i);
const int idx_quot = i / 2, idx_rem = i % 2;
if (idx_rem != 0) {
printf("%" PRI_ELEM "\n", a[idx_quot + 1]);
return;
}
const Bigger m = (Bigger)a[idx_quot] + (Bigger)a[idx_quot + 1];
if (m == -1) {
puts("-0.5");
return;
}
const Bigger val_quot = m / 2, val_rem = m % 2;
#ifdef __MINGW32__
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-non-iso"
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat"
#endif // ! __MINGW32__
#endif
if (val_rem == 0) printf("%" PRI_BIGGER "\n", val_quot);
else printf("%" PRI_BIGGER ".5\n", val_quot);
#ifdef __MINGW32__
#ifdef __clang__
#pragma clang diagnostic pop
#else
#pragma GCC diagnostic pop
#endif
#endif // ! __MINGW32__
}
ATTRIBUTE (( nonnull ))
static inline void run(int n, Element *restrict const a,
const int slen, struct vec *restrict const s)
{
char q = k_no_value;
Element e = k_no_value;
for (int i = 0; n-- != 0; ) { // i indexes that last element in a
(void)scanf(" %c %" SCN_ELEM, &q, &e);
if (q == 'a') {
// This query performs INSERTION, so insert an e into a.
int j = i, k = ++i; // shift items from j to k (k == j + 1, always)
while (e < a[j]) a[k--] = a[j--];
a[k] = e; // insert at k, then we can check for a duplicate at j
// If a might not have had e before this, add e to s.
if (a[j] != e || e == LOW) set_insert(slen, s, e);
} else {
// This query performs REMOVAL, so check s to see if a has an e.
struct vec *const bp = set_get_bucket(slen, s, e);
const int bi = vec_index_of(bp, e);
if (bi == -1) {
no_update:
puts("Wrong!");
continue;
}
assert(0 <= bi && bi < bp->length && bp->length <= bp->capacity);
assert(bp->elems != NULL && bp->elems[bi] == e);
// Since s contains e, a has at least one e, so remove an e from a.
int j = i - 1; // j will index just before the removed element in a
for (Element t0 = a[i], t1 = k_no_value; t0 != e; ) {
t1 = a[j];
a[j--] = t0;
if (t1 == e) break;
t0 = a[j];
a[j--] = t1;
}
// If we removed the only occurrence of e in a, remove e from s.
if (a[j] != e || j == 0) {
vec_erase_at(bp, bi);
assert(vec_index_of(bp, e) == -1);
}
// Update the size of a, and emit the appropriate type of output.
if (--i == 0) goto no_update;
}
print_median(a, i);
}
}
int main(void)
{
int n;
(void)scanf("%d", &n);
if (n <= 0 || n > k_nmax) abort();
const int slen = set_guess_best_bucket_count(n);
struct vec *restrict s = set_create(slen);
Element *restrict const a = alloca((size_t)(n + 1) * sizeof a[0]);
a[0] = LOW; // sentinel element
if (k_nice_debugging != (0)) memset(a + 1, 0xCC, (size_t)n * sizeof a[1]);
run(n, a, slen, s);
if (k_nice_debugging != (0)) set_destroy(slen, &s);
}
|
the_stack_data/220455428.c
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int choice;
char ch1, ch2, ch3, ch4, chPass1, chPass2, chPass3, chPass4;
chPass1 = chPass2 = chPass3 = chPass4 = '0';
srand(time(0));
while(1){
system("cls");
printf("1. Login\n2. Reset Password\n3. Exit\n\nEnter your choice: ");
fflush(stdin);
scanf("%d", &choice);
switch(choice){
case 1:
system("cls");
printf("Enter password: ");
fflush(stdin);
scanf("%c%c%c%c", &ch1, &ch2, &ch3, &ch4);
if(ch1 == chPass1 && ch2 == chPass2 && ch3 == chPass3 && ch4 == chPass4){
system("cls");
printf("Welcome!\n");
getch();
}else{
system("cls");
printf("Wrong password entered\n");
Sleep(1000);
}
break;
case 2:
system("cls");
do{
chPass1 = (rand() % 128) + 1;
}while(chPass1 < 'a' || chPass1 > 'z');
do{
chPass2 = (rand() % 128) + 1;
}while(chPass2 < 'A' || chPass2 > 'Z');
do{
chPass3 = (rand() % 128) + 1;
}while(chPass3 < '0' || chPass3 > '9');
do{
chPass4 = (rand() % 128) + 1;
}while(chPass4 < 'a' || chPass4 > 'z');
printf("Your new password: %c%c%c%c", chPass1, chPass2, chPass3, chPass4);
getch();
break;
case 3:
system("cls");
printf("Good Bye!");
Sleep(500);
exit(0);
break;
default:
system("cls");
printf("Wrong input");
Sleep(200);
break;
}
}
return 0;
}
|
the_stack_data/179830582.c
|
//
// main.c
// Lyrics demo
//
// Created by apple on 2019/10/23.
// Copyright © 2019 apple. All rights reserved.
//
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 2048
#define MAX_PATH 1024
#define MAX_NAME 512
#define true 1
void textProcessor(FILE *lrcx,FILE *lrc);
int isLineRight(char* buffer);
void deleteString(char *buffer,int position);
void getFileName(char* lrcxPath, char* fileName);
void editPath(char* lrcxPath);
int main(int argc, const char * argv[]) {
//input the path of .lrcx file
char lrcxPath[MAX_PATH];
char fileName[MAX_NAME];
char outPath[MAX_PATH]="/Users/apple/Desktop/" ;
while(1){
printf("Drag the .lrcx File:");
scanf("%[^\n]",lrcxPath); //[^\n] means end only with enter(not space)
setbuf(stdin, NULL);
//edit the path(ep. space,"")
editPath(lrcxPath);
getFileName(lrcxPath, fileName);
strcat(outPath, fileName);
//open the .lrcx file by the path above
FILE *lrcx;
lrcx=fopen(lrcxPath, "r");
//create a new .lrc file as the output
FILE *lrc;
lrc=fopen(outPath,"w");
/*lyrics text processor*/
textProcessor(lrcx, lrc);
//close the files
fclose(lrcx);
fclose(lrc);
memset(lrcxPath, '\0', sizeof(lrcxPath));
memset(fileName, '\0', sizeof(fileName));
for(int i=0;i<MAX_PATH;i++){
if(i>20){
outPath[i]='\0';
}
}
}
}
void textProcessor(FILE *lrcx,FILE *lrc){
char buffer[MAX_LENGTH];
while(fgets(buffer, MAX_LENGTH, lrcx)!=NULL)
{
if(isLineRight(buffer)==1){
//edit the time format
buffer[6]=':';
deleteString(buffer, 9);
fputs(buffer, lrc);
}
}
}
int isLineRight(char* buffer){
int point=0;
while(buffer[point]!='\n'){
if(buffer[point]=='['){
if(buffer[point+1]>='0'&&buffer[point+1]<='9'){
;
}
else return 0;
}
point++;
}
return 1;
}
void deleteString(char *buffer,int position){
int point=position;
while(buffer[point]!='\0'){
buffer[point]=buffer[point+1];
point++;
}
buffer[point]=buffer[point+1];
}
void editPath(char* lrcxPath){
int point;
for(point=0;lrcxPath[point]!='\0';point++){
if(lrcxPath[point]=='\\'){
deleteString(lrcxPath, point);
}
}
if(lrcxPath[point-1]==' '){
lrcxPath[point-1]='\0';
}
}
void getFileName(char* lrcxPath, char* fileName){
//find endPoint and the last '/'
int endPoint;
for(endPoint=0;lrcxPath[endPoint]!='\0';endPoint++){;}
int lastSection;
for(lastSection=endPoint;lrcxPath[lastSection]!='/';lastSection--){;}
lastSection++;
int i;
//get the file name to the string
//endPoint-1 to delete the 'x' out of 'lrcx'
for(i=0;lastSection!=endPoint-1;lastSection++,i++){
fileName[i]=lrcxPath[lastSection];
}
}
|
the_stack_data/95209.c
|
#include <unistd.h>
#include <string.h>
#include <stdio.h>
// Este codigo escribe todos los bytes que lee de la entrada std en la salida stda
main(){
char c;
char *buf="fin ejecución\n";
char buffer[1024];
int ret;
// USO
sprintf(buffer,"................................................\n");
write(2,buffer,strlen(buffer));
sprintf(buffer,"Este programa escribe por la salida std todo lo que lee de la entrada std. Si no has redirigido la salida, lo que escribas en el teclado saldra por la pantalla\n");
write(2,buffer,strlen(buffer));
sprintf(buffer,"Para acabar CtrlD\n");
write(2,buffer,strlen(buffer));
sprintf(buffer,"................................................\n");
write(2,buffer,strlen(buffer));
// Leemos del canal 0 (entrada std), 1 bye
ret=read(0,&c,sizeof(c));
// Cuando el read devuelve 0 significa que se ha acabado la
// entrada de datos --> acabamos el bucle de lectura
while(ret>0){
// Escribimos en el canal 1 (salida std) 1 byte
write(1,&c,sizeof(c));
ret=read(0,&c,sizeof(c));
}
write(1,buf,strlen(buf));
}
|
the_stack_data/57951590.c
|
/* Copyright (c) 2016, Dennis Wölfing
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* libc/src/string/memmove.c
* Move memory.
*/
#include <string.h>
void* memmove(void* dest, const void* src, size_t size) {
unsigned char* d = dest;
const unsigned char* s = src;
if (src > dest) {
for (size_t i = 0; i < size; i++) {
d[i] = s[i];
}
} else {
for (size_t i = size; i > 0; i--) {
d[i - 1] = s[i - 1];
}
}
return dest;
}
|
the_stack_data/54825368.c
|
#include <stdio.h>
#include <string.h>
#define HASH_START_VALUE 42
long hash(char *);
int main()
{
char input_word[200];
long word_hash;
scanf("%s",input_word);
word_hash = hash(input_word);
printf("%ld\n", word_hash);
return 0;
}
long hash(char *word)
{
long word_hash = HASH_START_VALUE;
int word_lenght = strlen(word);
int i = 0;
for(;i < word_lenght; i++)
{
word_hash += word[i] * (i+1);
}
return word_hash;
}
|
the_stack_data/34513809.c
|
#include <stdio.h>
void main()
{
printf("\nMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0OkkkkOKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKOxlcclllccld0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXdcccd0XXK0xlco0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXdcclOWWWNNXklcoKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXdcclOWWWWNNXxccdXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNdcclOWWWWNNNKdcckNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNxcccOWWWWWNNNOlcoKMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXdccckWWWWWNNNKdcckWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWOlccoKWWWWNNNNXxccxNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOlcco0WWWWNNNNNKdcckWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNklcox0WWWWNNNNNNOlcl0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXxccdKNWWWWNNNNNNXkccdXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKdccxXWWWWWNNNNNNNKdcckNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMW0oclkNWWWWNNNNNNNNNOlclOXNNNNNNNNNNNNNNNNNNNWWMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNklcoONWWWWWNNNNNNNNXxccclooooooooooooooooooooodk0XWMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKdccdKWWWWWWWWNNNNNNNXOxxxxxxxxxxxxxxxddddddddddoccoONMMMMMMM\n");
printf("MMMMMMMWXKKKKKKKKKKKKKKKKKKKKKKKKKKKXKklclkXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNXKOoclOWMMMMMM\n");
printf("MMMMMMXklcccccccccccccccccccccccccccllcld0WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNNXxccxNMMMMMM\n");
printf("MMMMMM0lcclllllllllllllllllllllllccclokKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNNXOlclOWMMMMMM\n");
printf("MMMMMMKoccodddddddddddddddddddddlcclOXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNKOdlclkXWMMMMMM\n");
printf("MMMMMMXoccodooooooooooooooooooddlccdKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNXOoccoONWMMMMMMM\n");
printf("MMMMMMXdccldooooooooooooooooooodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNNOl:oKMMMMMMMMM\n");
printf("MMMMMMNxccldooooooooooooooooooodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNNOlcoKMMMMMMMMM\n");
printf("MMMMMMWkccloooooooooooooooooooodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNXOoccxNMMMMMMMMM\n");
printf("MMMMMMWOlclodoooooooooooooooooodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNXkocclkXWMMMMMMMMM\n");
printf("MMMMMMM0lccodoooooooooooooooooodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNXklccxNWMMMMMMMMMM\n");
printf("MMMMMMMKoccodoooooooooooooooooodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNXxccxNMMMMMMMMMMM\n");
printf("MMMMMMMXdccodoooooooooooooooooodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNN0oclkNMMMMMMMMMMM\n");
printf("MMMMMMMNxccldoooooooooooooooooodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNX0klclxXWMMMMMMMMMMM\n");
printf("MMMMMMMWkcclooooooooooooooooooodlccdKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNN0occlkXWMMMMMMMMMMMM\n");
printf("MMMMMMMWOlclooooooooooooooooooodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNXOlco0WMMMMMMMMMMMMM\n");
printf("MMMMMMMM0lclodooooooooooxO00koodlccoKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNN0ocl0WMMMMMMMMMMMMM\n");
printf("MMMMMMMMKoccodooooooooooONNNKxodlcclxO0KNWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNX0dccxXMMMMMMMMMMMMMM\n");
printf("MMMMMMMMXdccodooooooooooxO00koodlcccccclok0KXXXXXXXXXXXXXXXXXXXXXXXXXKKKKKKK00kdlclxKWMMMMMMMMMMMMMM\n");
printf("MMMMMMMMNxccldooooooooooooooooodlcccccodoccllllllllllllllllllllllllllllllllllcclox0NWMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMWkccclllllllllllllllllllccccclONXKOkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkOKXWWMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMN0xddddddddddddddddddddddddxONWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMWWWWWWWWWWWWWWWWWWWWWWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n");
printf("fb{YOU GOT THE LAST FLAG!!! NICE WORK!!!}\n");
}
|
the_stack_data/153009.c
|
// RUN: %clang_cc1 -triple x86_64-apple-darwin12 -S -o - -emit-llvm %s | FileCheck %s -check-prefix=CHECK-NOERRNO
// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -o - -emit-llvm -fmath-errno %s | FileCheck %s -check-prefix=CHECK-ERRNO
// RUN: %clang_cc1 -triple x86_64-apple-darwin12 -S -o - -emit-llvm -x c++ %s | FileCheck %s -check-prefix=CHECK-NOERRNO
// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -o - -emit-llvm -x c++ -fmath-errno %s | FileCheck %s -check-prefix=CHECK-ERRNO
// Prototypes.
#ifdef __cplusplus
extern "C" {
#endif
double atan2(double, double);
float atan2f(float, float);
long double atan2l(long double, long double);
int abs(int);
long int labs(long int);
long long int llabs(long long int);
double copysign(double, double);
float copysignf(float, float);
long double copysignl(long double, long double);
double fabs(double);
float fabsf(float);
long double fabsl(long double);
double fmod(double, double);
float fmodf(float, float);
long double fmodl(long double, long double);
double frexp(double, int *);
float frexpf(float, int *);
long double frexpl(long double, int *);
double ldexp(double, int);
float ldexpf(float, int);
long double ldexpl(long double, int);
double modf(double, double *);
float modff(float, float *);
long double modfl(long double, long double *);
double nan(const char *);
float nanf(const char *);
long double nanl(const char *);
double pow(double, double);
float powf(float, float);
long double powl(long double, long double);
double acos(double);
float acosf(float);
long double acosl(long double);
double acosh(double);
float acoshf(float);
long double acoshl(long double);
double asin(double);
float asinf(float);
long double asinl(long double);
double asinh(double);
float asinhf(float);
long double asinhl(long double);
double atan(double);
float atanf(float);
long double atanl( long double);
double atanh(double);
float atanhf(float);
long double atanhl(long double);
double cbrt(double);
float cbrtf(float);
long double cbrtl(long double);
double ceil(double);
float ceilf(float);
long double ceill(long double);
double cos(double);
float cosf(float);
long double cosl(long double);
double cosh(double);
float coshf(float);
long double coshl(long double);
double erf(double);
float erff(float);
long double erfl(long double);
double erfc(double);
float erfcf(float);
long double erfcl(long double);
double exp(double);
float expf(float);
long double expl(long double);
double exp2(double);
float exp2f(float);
long double exp2l(long double);
double expm1(double);
float expm1f(float);
long double expm1l(long double);
double fdim(double, double);
float fdimf(float, float);
long double fdiml(long double, long double);
double floor(double);
float floorf(float);
long double floorl(long double);
double fma(double, double, double);
float fmaf(float, float, float);
long double fmal(long double, long double, long double);
double fmax(double, double);
float fmaxf(float, float);
long double fmaxl(long double, long double);
double fmin(double, double);
float fminf(float, float);
long double fminl(long double, long double);
double hypot(double, double);
float hypotf(float, float);
long double hypotl(long double, long double);
int ilogb(double);
int ilogbf(float);
int ilogbl(long double);
double lgamma(double);
float lgammaf(float);
long double lgammal(long double);
long long int llrint(double);
long long int llrintf(float);
long long int llrintl(long double);
long long int llround(double);
long long int llroundf(float);
long long int llroundl(long double);
double log(double);
float logf(float);
long double logl(long double);
double log10(double);
float log10f(float);
long double log10l(long double);
double log1p(double);
float log1pf(float);
long double log1pl(long double);
double log2(double);
float log2f(float);
long double log2l(long double);
double logb(double);
float logbf(float);
long double logbl(long double);
long int lrint(double);
long int lrintf(float);
long int lrintl(long double);
long int lround(double);
long int lroundf(float);
long int lroundl(long double);
double nearbyint(double);
float nearbyintf(float);
long double nearbyintl(long double);
double nextafter(double, double);
float nextafterf(float, float);
long double nextafterl(long double, long double);
double nexttoward(double, long double);
float nexttowardf(float, long double);
long double nexttowardl(long double, long double);
double remainder(double, double);
float remainderf(float, float);
long double remainderl(long double, long double);
double rint(double);
float rintf(float);
long double rintl(long double);
double round(double);
float roundf(float);
long double roundl(long double);
double scalbln(double, long int exp);
float scalblnf(float, long int exp);
long double scalblnl(long double, long int exp);
double scalbn(double, int exp);
float scalbnf(float, int exp);
long double scalbnl(long double, int exp);
double sin(double);
float sinf(float);
long double sinl(long double);
double sinh(double);
float sinhf(float);
long double sinhl(long double);
double sqrt(double);
float sqrtf(float);
long double sqrtl(long double);
double tan(double);
float tanf(float);
long double tanl(long double);
double tanh(double);
float tanhf(float);
long double tanhl(long double);
double tgamma(double);
float tgammaf(float);
long double tgammal(long double);
double trunc(double);
float truncf(float);
long double truncl(long double);
double cabs(double _Complex);
float cabsf(float _Complex);
long double cabsl(long double _Complex);
double _Complex cacos(double _Complex);
float _Complex cacosf(float _Complex);
long double _Complex cacosl(long double _Complex);
double _Complex cacosh(double _Complex);
float _Complex cacoshf(float _Complex);
long double _Complex cacoshl(long double _Complex);
double carg(double _Complex);
float cargf(float _Complex);
long double cargl(long double _Complex);
double _Complex casin(double _Complex);
float _Complex casinf(float _Complex);
long double _Complex casinl(long double _Complex);
double _Complex casinh(double _Complex);
float _Complex casinhf(float _Complex);
long double _Complex casinhl(long double _Complex);
double _Complex catan(double _Complex);
float _Complex catanf(float _Complex);
long double _Complex catanl(long double _Complex);
double _Complex catanh(double _Complex);
float _Complex catanhf(float _Complex);
long double _Complex catanhl(long double _Complex);
double _Complex ccos(double _Complex);
float _Complex ccosf(float _Complex);
long double _Complex ccosl(long double _Complex);
double _Complex ccosh(double _Complex);
float _Complex ccoshf(float _Complex);
long double _Complex ccoshl(long double _Complex);
double _Complex cexp(double _Complex);
float _Complex cexpf(float _Complex);
long double _Complex cexpl(long double _Complex);
double cimag(double _Complex);
float cimagf(float _Complex);
long double cimagl(long double _Complex);
double _Complex conj(double _Complex);
float _Complex conjf(float _Complex);
long double _Complex conjl(long double _Complex);
double _Complex clog(double _Complex);
float _Complex clogf(float _Complex);
long double _Complex clogl(long double _Complex);
double _Complex cproj(double _Complex);
float _Complex cprojf(float _Complex);
long double _Complex cprojl(long double _Complex);
double _Complex cpow(double _Complex, _Complex double);
float _Complex cpowf(float _Complex, _Complex float);
long double _Complex cpowl(long double _Complex, _Complex long double);
double creal(double _Complex);
float crealf(float _Complex);
long double creall(long double _Complex);
double _Complex csin(double _Complex);
float _Complex csinf(float _Complex);
long double _Complex csinl(long double _Complex);
double _Complex csinh(double _Complex);
float _Complex csinhf(float _Complex);
long double _Complex csinhl(long double _Complex);
double _Complex csqrt(double _Complex);
float _Complex csqrtf(float _Complex);
long double _Complex csqrtl(long double _Complex);
double _Complex ctan(double _Complex);
float _Complex ctanf(float _Complex);
long double _Complex ctanl(long double _Complex);
double _Complex ctanh(double _Complex);
float _Complex ctanhf(float _Complex);
long double _Complex ctanhl(long double _Complex);
double __sinpi(double);
float __sinpif(float);
double __cospi(double);
float __cospif(float);
double __tanpi(double);
float __tanpif(float);
double __exp10(double);
float __exp10f(float);
#ifdef __cplusplus
}
#endif
// Force emission of the declare statements.
#define F(x) ((void*)x)
void *use[] = {
F(atan2), F(atan2f), F(atan2l), F(abs), F(labs),
F(llabs), F(copysign), F(copysignf), F(copysignl), F(fabs),
F(fabsf), F(fabsl), F(fmod), F(fmodf), F(fmodl),
F(frexp), F(frexpf), F(frexpl), F(ldexp), F(ldexpf),
F(ldexpl), F(modf), F(modff), F(modfl), F(nan),
F(nanf), F(nanl), F(pow), F(powf), F(powl),
F(acos), F(acosf), F(acosl), F(acosh), F(acoshf),
F(acoshl), F(asin), F(asinf), F(asinl), F(asinh),
F(asinhf), F(asinhl), F(atan), F(atanf), F(atanl),
F(atanh), F(atanhf), F(atanhl), F(cbrt), F(cbrtf),
F(cbrtl), F(ceil), F(ceilf), F(ceill), F(cos),
F(cosf), F(cosl), F(cosh), F(coshf), F(coshl),
F(erf), F(erff), F(erfl), F(erfc), F(erfcf),
F(erfcl), F(exp), F(expf), F(expl), F(exp2),
F(exp2f), F(exp2l), F(expm1), F(expm1f), F(expm1l),
F(fdim), F(fdimf), F(fdiml), F(floor), F(floorf),
F(floorl), F(fma), F(fmaf), F(fmal), F(fmax),
F(fmaxf), F(fmaxl), F(fmin), F(fminf), F(fminl),
F(hypot), F(hypotf), F(hypotl), F(ilogb), F(ilogbf),
F(ilogbl), F(lgamma), F(lgammaf), F(lgammal), F(llrint),
F(llrintf), F(llrintl), F(llround), F(llroundf), F(llroundl),
F(log), F(logf), F(logl), F(log10), F(log10f),
F(log10l), F(log1p), F(log1pf), F(log1pl), F(log2),
F(log2f), F(log2l), F(logb), F(logbf), F(logbl),
F(lrint), F(lrintf), F(lrintl), F(lround), F(lroundf),
F(lroundl), F(nearbyint), F(nearbyintf), F(nearbyintl), F(nextafter),
F(nextafterf), F(nextafterl), F(nexttoward), F(nexttowardf), F(nexttowardl),
F(remainder), F(remainderf), F(remainderl), F(rint), F(rintf),
F(rintl), F(round), F(roundf), F(roundl), F(scalbln),
F(scalblnf), F(scalblnl), F(scalbn), F(scalbnf), F(scalbnl),
F(sin), F(sinf), F(sinl), F(sinh), F(sinhf),
F(sinhl), F(sqrt), F(sqrtf), F(sqrtl), F(tan),
F(tanf), F(tanl), F(tanh), F(tanhf), F(tanhl),
F(tgamma), F(tgammaf), F(tgammal), F(trunc), F(truncf),
F(truncl), F(cabs), F(cabsf), F(cabsl), F(cacos),
F(cacosf), F(cacosl), F(cacosh), F(cacoshf), F(cacoshl),
F(carg), F(cargf), F(cargl), F(casin), F(casinf),
F(casinl), F(casinh), F(casinhf), F(casinhl), F(catan),
F(catanf), F(catanl), F(catanh), F(catanhf), F(catanhl),
F(ccos), F(ccosf), F(ccosl), F(ccosh), F(ccoshf),
F(ccoshl), F(cexp), F(cexpf), F(cexpl), F(cimag),
F(cimagf), F(cimagl), F(conj), F(conjf), F(conjl),
F(clog), F(clogf), F(clogl), F(cproj), F(cprojf),
F(cprojl), F(cpow), F(cpowf), F(cpowl), F(creal),
F(crealf), F(creall), F(csin), F(csinf), F(csinl),
F(csinh), F(csinhf), F(csinhl), F(csqrt), F(csqrtf),
F(csqrtl), F(ctan), F(ctanf), F(ctanl), F(ctanh),
F(ctanhf), F(ctanhl), F(__sinpi), F(__sinpif), F(__cospi),
F(__cospif), F(__tanpi), F(__tanpif), F(__exp10), F(__exp10f)
};
// CHECK-NOERRNO: declare double @atan2(double, double) [[NUW:#[0-9]+]]
// CHECK-NOERRNO: declare float @atan2f(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @atan2l(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare i32 @abs(i32) [[NUW]]
// CHECK-NOERRNO: declare i64 @labs(i64) [[NUW]]
// CHECK-NOERRNO: declare i64 @llabs(i64) [[NUW]]
// CHECK-NOERRNO: declare double @copysign(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @copysignf(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @copysignl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @fabs(double) [[NUW]]
// CHECK-NOERRNO: declare float @fabsf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @fabsl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @fmod(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @fmodf(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @fmodl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @ldexp(double, i32) [[NUW]]
// CHECK-NOERRNO: declare float @ldexpf(float, i32) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @ldexpl(x86_fp80, i32) [[NUW]]
// CHECK-NOERRNO: declare double @nan(i8*) [[NUW]]
// CHECK-NOERRNO: declare float @nanf(i8*) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @nanl(i8*) [[NUW]]
// CHECK-NOERRNO: declare double @pow(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @powf(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @powl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @acos(double) [[NUW]]
// CHECK-NOERRNO: declare float @acosf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @acosl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @acosh(double) [[NUW]]
// CHECK-NOERRNO: declare float @acoshf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @acoshl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @asin(double) [[NUW]]
// CHECK-NOERRNO: declare float @asinf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @asinl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @asinh(double) [[NUW]]
// CHECK-NOERRNO: declare float @asinhf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @asinhl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @atan(double) [[NUW]]
// CHECK-NOERRNO: declare float @atanf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @atanl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @atanh(double) [[NUW]]
// CHECK-NOERRNO: declare float @atanhf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @atanhl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @cbrt(double) [[NUW]]
// CHECK-NOERRNO: declare float @cbrtf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @cbrtl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @ceil(double) [[NUW]]
// CHECK-NOERRNO: declare float @ceilf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @ceill(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @cos(double) [[NUW]]
// CHECK-NOERRNO: declare float @cosf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @cosl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @cosh(double) [[NUW]]
// CHECK-NOERRNO: declare float @coshf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @coshl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @erf(double) [[NUW]]
// CHECK-NOERRNO: declare float @erff(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @erfl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @erfc(double) [[NUW]]
// CHECK-NOERRNO: declare float @erfcf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @erfcl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @exp(double) [[NUW]]
// CHECK-NOERRNO: declare float @expf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @expl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @exp2(double) [[NUW]]
// CHECK-NOERRNO: declare float @exp2f(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @exp2l(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @expm1(double) [[NUW]]
// CHECK-NOERRNO: declare float @expm1f(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @expm1l(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @fdim(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @fdimf(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @fdiml(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @floor(double) [[NUW]]
// CHECK-NOERRNO: declare float @floorf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @floorl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @fma(double, double, double) [[NUW]]
// CHECK-NOERRNO: declare float @fmaf(float, float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @fmal(x86_fp80, x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @fmax(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @fmaxf(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @fmaxl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @fmin(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @fminf(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @fminl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @hypot(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @hypotf(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @hypotl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare i32 @ilogb(double) [[NUW]]
// CHECK-NOERRNO: declare i32 @ilogbf(float) [[NUW]]
// CHECK-NOERRNO: declare i32 @ilogbl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @lgamma(double) [[NONCONST:#[0-9]+]]
// CHECK-NOERRNO: declare float @lgammaf(float) [[NONCONST]]
// CHECK-NOERRNO: declare x86_fp80 @lgammal(x86_fp80) [[NONCONST]]
// CHECK-NOERRNO: declare i64 @llrint(double) [[NUW]]
// CHECK-NOERRNO: declare i64 @llrintf(float) [[NUW]]
// CHECK-NOERRNO: declare i64 @llrintl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare i64 @llround(double) [[NUW]]
// CHECK-NOERRNO: declare i64 @llroundf(float) [[NUW]]
// CHECK-NOERRNO: declare i64 @llroundl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @log(double) [[NUW]]
// CHECK-NOERRNO: declare float @logf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @logl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @log10(double) [[NUW]]
// CHECK-NOERRNO: declare float @log10f(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @log10l(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @log1p(double) [[NUW]]
// CHECK-NOERRNO: declare float @log1pf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @log1pl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @log2(double) [[NUW]]
// CHECK-NOERRNO: declare float @log2f(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @log2l(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @logb(double) [[NUW]]
// CHECK-NOERRNO: declare float @logbf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @logbl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare i64 @lrint(double) [[NUW]]
// CHECK-NOERRNO: declare i64 @lrintf(float) [[NUW]]
// CHECK-NOERRNO: declare i64 @lrintl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare i64 @lround(double) [[NUW]]
// CHECK-NOERRNO: declare i64 @lroundf(float) [[NUW]]
// CHECK-NOERRNO: declare i64 @lroundl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @nearbyint(double) [[NUW]]
// CHECK-NOERRNO: declare float @nearbyintf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @nearbyintl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @nextafter(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @nextafterf(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @nextafterl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @nexttoward(double, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare float @nexttowardf(float, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @nexttowardl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @remainder(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @remainderf(float, float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @remainderl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @rint(double) [[NUW]]
// CHECK-NOERRNO: declare float @rintf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @rintl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @round(double) [[NUW]]
// CHECK-NOERRNO: declare float @roundf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @roundl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @scalbln(double, i64) [[NUW]]
// CHECK-NOERRNO: declare float @scalblnf(float, i64) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @scalblnl(x86_fp80, i64) [[NUW]]
// CHECK-NOERRNO: declare double @scalbn(double, i32) [[NUW]]
// CHECK-NOERRNO: declare float @scalbnf(float, i32) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @scalbnl(x86_fp80, i32) [[NUW]]
// CHECK-NOERRNO: declare double @sin(double) [[NUW]]
// CHECK-NOERRNO: declare float @sinf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @sinl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @sinh(double) [[NUW]]
// CHECK-NOERRNO: declare float @sinhf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @sinhl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @sqrt(double) [[NUW]]
// CHECK-NOERRNO: declare float @sqrtf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @sqrtl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @tan(double) [[NUW]]
// CHECK-NOERRNO: declare float @tanf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @tanl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @tanh(double) [[NUW]]
// CHECK-NOERRNO: declare float @tanhf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @tanhl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @tgamma(double) [[NUW]]
// CHECK-NOERRNO: declare float @tgammaf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @tgammal(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @trunc(double) [[NUW]]
// CHECK-NOERRNO: declare float @truncf(float) [[NUW]]
// CHECK-NOERRNO: declare x86_fp80 @truncl(x86_fp80) [[NUW]]
// CHECK-NOERRNO: declare double @cabs(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @cabsf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @cacos(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @cacosf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @cacosh(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @cacoshf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare double @carg(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @cargf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @casin(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @casinf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @casinh(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @casinhf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @catan(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @catanf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @catanh(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @catanhf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @ccos(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @ccosf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @ccosh(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @ccoshf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @cexp(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @cexpf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare double @cimag(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @cimagf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @conj(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @conjf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @clog(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @clogf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @cproj(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @cprojf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @cpow(double, double, double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @cpowf(<2 x float>, <2 x float>) [[NUW]]
// CHECK-NOERRNO: declare double @creal(double, double) [[NUW]]
// CHECK-NOERRNO: declare float @crealf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @csin(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @csinf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @csinh(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @csinhf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @csqrt(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @csqrtf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @ctan(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @ctanf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare { double, double } @ctanh(double, double) [[NUW]]
// CHECK-NOERRNO: declare <2 x float> @ctanhf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: declare double @__sinpi(double) [[NUW]]
// CHECK-NOERRNO: declare float @__sinpif(float) [[NUW]]
// CHECK-NOERRNO: declare double @__cospi(double) [[NUW]]
// CHECK-NOERRNO: declare float @__cospif(float) [[NUW]]
// CHECK-NOERRNO: declare double @__tanpi(double) [[NUW]]
// CHECK-NOERRNO: declare float @__tanpif(float) [[NUW]]
// CHECK-NOERRNO: declare double @__exp10(double) [[NUW]]
// CHECK-NOERRNO: declare float @__exp10f(float) [[NUW]]
// CHECK-ERRNO: declare i32 @abs(i32) [[NUW:#[0-9]+]]
// CHECK-ERRNO: declare i64 @labs(i64) [[NUW]]
// CHECK-ERRNO: declare i64 @llabs(i64) [[NUW]]
// CHECK-ERRNO: declare double @copysign(double, double) [[NUW]]
// CHECK-ERRNO: declare float @copysignf(float, float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @copysignl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @fabs(double) [[NUW]]
// CHECK-ERRNO: declare float @fabsf(float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @fabsl(x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @nan(i8*) [[NUW]]
// CHECK-ERRNO: declare float @nanf(i8*) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @nanl(i8*) [[NUW]]
// CHECK-ERRNO: declare double @ceil(double) [[NUW]]
// CHECK-ERRNO: declare float @ceilf(float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @ceill(x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @floor(double) [[NUW]]
// CHECK-ERRNO: declare float @floorf(float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @floorl(x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @fmax(double, double) [[NUW]]
// CHECK-ERRNO: declare float @fmaxf(float, float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @fmaxl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @fmin(double, double) [[NUW]]
// CHECK-ERRNO: declare float @fminf(float, float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @fminl(x86_fp80, x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @lgamma(double) [[NONCONST:#[0-9]+]]
// CHECK-ERRNO: declare float @lgammaf(float) [[NONCONST]]
// CHECK-ERRNO: declare x86_fp80 @lgammal(x86_fp80) [[NONCONST]]
// CHECK-ERRNO: declare double @nearbyint(double) [[NUW]]
// CHECK-ERRNO: declare float @nearbyintf(float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @nearbyintl(x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @rint(double) [[NUW]]
// CHECK-ERRNO: declare float @rintf(float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @rintl(x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @round(double) [[NUW]]
// CHECK-ERRNO: declare float @roundf(float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @roundl(x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @trunc(double) [[NUW]]
// CHECK-ERRNO: declare float @truncf(float) [[NUW]]
// CHECK-ERRNO: declare x86_fp80 @truncl(x86_fp80) [[NUW]]
// CHECK-ERRNO: declare double @cabs(double, double) [[NUW]]
// CHECK-ERRNO: declare float @cabsf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @cacos(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @cacosf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @cacosh(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @cacoshf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare double @carg(double, double) [[NUW]]
// CHECK-ERRNO: declare float @cargf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @casin(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @casinf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @casinh(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @casinhf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @catan(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @catanf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @catanh(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @catanhf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @ccos(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @ccosf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @ccosh(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @ccoshf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @cexp(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @cexpf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare double @cimag(double, double) [[NUW]]
// CHECK-ERRNO: declare float @cimagf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @conj(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @conjf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @clog(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @clogf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @cproj(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @cprojf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @cpow(double, double, double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @cpowf(<2 x float>, <2 x float>) [[NUW]]
// CHECK-ERRNO: declare double @creal(double, double) [[NUW]]
// CHECK-ERRNO: declare float @crealf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @csin(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @csinf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @csinh(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @csinhf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @csqrt(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @csqrtf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @ctan(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @ctanf(<2 x float>) [[NUW]]
// CHECK-ERRNO: declare { double, double } @ctanh(double, double) [[NUW]]
// CHECK-ERRNO: declare <2 x float> @ctanhf(<2 x float>) [[NUW]]
// CHECK-NOERRNO: attributes [[NUW]] = { nounwind readnone{{.*}} }
// CHECK-NOERRNO: attributes [[NONCONST]] = {
// CHECK-NOERRNO-NOT: readnone
// CHECK-NOERRNO-SAME: nounwind{{.*}} }
// CHECK-ERRNO: attributes [[NONCONST]] = {
// CHECK-ERRNO-NOT: readnone
// CHECK-ERRNO-SAME: nounwind{{.*}} }
// CHECK-ERRNO: attributes [[NUW]] = { nounwind readnone{{.*}} }
|
the_stack_data/12638100.c
|
int check_hardware(void) {
return 1;
}
|
the_stack_data/70451097.c
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
typedef unsigned long u64;
static u64 get_cr0(void)
{
__asm__ __volatile__("movq %cr0, %rax");
}
int main(void)
{
printf("Hello, inline assembly:\n [CR0] = 0x%lx\n", get_cr0());
exit(0);
}
|
the_stack_data/29825262.c
|
#include<stdio.h>
int main(){
int a, b;
scanf("%d%d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("%d %d\n", a, b);
return 0;
}
|
the_stack_data/57950618.c
|
/*
* sleeptest.c
*
* Andrew H. Fagg 11/12/92 Original
*
* Test the time-based scheduling capability.
* Creates two processes : one that wakes up every 5 seconds,
* increments its time value, reports it to the user,
* and then goes back to sleep again.
* The other process waits for input from stdin. When a
* 'q' is entered, it exits, causing the clockproc() to
* exit as well.
*
*/
#include <stdio.h>
#define SLEEP 5
/*
* clockproc()
*
* Infinite loop of wake up, increment time, report time, and then
* go back to sleep again. Because set_schedule_interval() and
* next_interval() are used, this process is assured that it will
* be scheduled on the specified intervals, with no drift due to
* various delays.
*/
clockproc()
{
int time;
time = 0;
set_schedule_interval(5000); /* Specify how often the process */
/* is to wake up in msecs. */
while(1)
{
puts("The time is ");
puti(time);
puts("\n");
next_interval(); /* Wait for next time interval */
time += SLEEP;
}
}
/*
* interactive()
*
* Waits for input from the user (stdin). When a
* 'q' is entered, the process exits.
*
*/
interactive()
{
char buf[100];
while(1)
{
qprintf("val = ");
gets(buf, 100);
qprintf("entered %s\n\r", buf);
if(buf[0] == 'q')
return;
}
}
/*
* main()
*
* Start the clockproc() and interactive() processes. When
* the interactive process exits, then kill the clockproc.
*
*/
main()
{
int clock;
int other;
puts("Clock is"); /* Create and start the clockproc() */
clock = create(clockproc, 9, 0); /* priority = 9, stack size = default */
puti(clock);
puts("\n");
start(clock);
/* Create and start the interactive process */
other = create(interactive, 2, 0); /* priority = 2, stack size = default */
qprintf("Other is %d\n\r", other);
start(other);
/* Wait for interactive() to exit. */
wait(other);
kill(clock); /* Halt the clockproc() process. */
}
|
the_stack_data/152381.c
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
/*
A ciascun nuovo processo e' assegnato un intero di 16 bit con segno e
progressivo che lo identifica univocamente rispetto agli altri processi, il
"Process ID" (PID); essendo peraltro un intero a 16 bit puo' raggiungere al
massimo il valore di 32768, dopodiche' eventualmente, dopo la terminazione di un
processo puo' anche essere riutilizzato, ma solo dopo uno specifico lasso di
tempo.
Nota: Il primo bit e' riservato al segno, ecco perche' il valore e' 32768, ossia
2^15.
PID 0, solitamente e' assegnato allo schedulatore dei processi, detto "swapper";
PID 1, e' assegnao ad "init", invocato dal kernel alla fine della procedura di
"bootstrap", per cui e' il primo processo ad essere eseguito, e si occupa di
far partire tutti gli altri processi.
Il processo "init" non muore mai e sebbene venga eseguito con privilegi da
"superuser" e' un normale processo utente e non un processo kernel.
Vi sono diverse funzioni che consentono l'identificazione dei processi:
HEADER : <unistd.h>
PROTOTYPE : pid_t getpid(void);
pid_t getppid(void);
uid_t getuid(void);
uid_t geteuid(void);
gid_g getgid(void);
gid_t getegid(void);
SEMANTICS : getpid() ritorna il PID del processo chiamante;
getppid() ritorna il parent PID del processo chiamante;
getuid() ritorna il real user ID del processo chiamante;
geteuid() ritorna l'effective user ID del processo chiamante;
getgid() ritorna il real group ID del processo chiamante;
getegid() ritorno l'effective real group ID del processo chiamante.
RETURNS : L'identificativo richiesto in caso di successo, nessun errore.
--------------------------------------------------------------------------------
Nota: Le due funzioni getpid() e getppid() servono per acquisire il PID del
current process e il PID del parent process, ossia il PPID, questo perche' tutti
i processi conservano, oltre al proprio PID anche il PID del genitore.
Controllo d'accesso:
Un sistema unix-like e' basato su fondamenti di sicurezza imprescindibili,
anzitutto vi e' una netta differenziazione tra il superuser (root o
amministratore) che gode del pieno controllo del sistema e gli utenti che
inevitabilmente hanno diverse restrizioni, vi e' inoltre il concetto di "utente"
e di "gruppo".
Il sistema associa un identificatore univoco ad ogni utente e gruppo,
lo user-ID (UID) e il group-ID (GID) rispettivamente, essi servono al kernel per
identificare uno specifico utente o un gruppo di utenti, e grazie ad essi
verificare se godono delle autorizzazioni necessarie per eseguire i compiti
richiesti.
Poiche' tutte le operazioni del sistema sono eseguite da uno o piu' processi,
risulta ovvio che per poter fornire un controllo su tali operazioni e'
necessario essere a conoscenza dell'utente che ha lanciato il programma, ragion
per cui anche un processo deve avere i propri UID e GID.
I sistemi unix-like forniscono i seguenti gruppi di identificatori:
- Real , real user-ID (RUID) / real group-ID (RGID)
Sono impostati al login al valore dell'utente e del gruppo con cui
si accede al sistema. Solitamente non vengono cambiati, potrebbe
farlo tuttavia solo un processo che gode dei privilegi di
superuser.
Identificano l'utente e il gruppo dei proprietari del processo.
- Effective , effective user-ID (EUID) / effective group-ID (EGID)
Ai due si aggiunge anche l'effective GID di altri eventuali gruppi
di appartenenza.
Sono utilizzati nelle verifiche dei permessi del processo e per il
controllo d'accesso ai file, in pratica identificano l'utente e
il gruppo usati per decidere se un processo possa o meno accedere
ad una risorsa.
Nota: solitamente real ed effective sono identici, tranne nel caso
in cui il programma in esecuzione avesse i bit 'suid' o 'sgid'
impostati, in tal caso gli effective saranno impostati al nome
dell'utente e del gruppo proprietari del file. Questo e' il caso
in cui un programma puo' essere eseguito da un utente con
privilegi di superuser (o altri). Puo' rappresentare un serio
problema di sicurezza.
- Saved , saved user-ID / saved group-ID
Solo se _POSIX_SAVED_IDS e' impostato.
Sono copie dell'effective User-ID ed effettive group-ID del
processo padre - impostati da una delle funzioni exec all'avvio
del processo - cosi che sia possibile ripristinarli.
I sistemi con kernel Linux dispongono anche dell'identificatore filesystem, una
estensione di sicurezza NFS.
*/
int main(int argc, char* argv[])
{
printf("Processo chiamante:\n");
printf(" Process-ID (PID): %d\n", getpid());
printf(" Parent Process-ID (PPID): %d - la shell\n", getppid());
printf(" Real User-ID (real-UID): %d\n", getuid());
printf("Effective User-ID (effective-UID): %d\n", geteuid());
printf(" Real Group-ID (real-GID): %d\n", getgid());
printf("Effective Group-ID (effective-GID): %d\n", getegid());
return (EXIT_SUCCESS);
}
/* L'effettiva valenza e utilita' di ciascuna funzione sara' estremamente chiara
negli esempi successivi a questo, andando avanti nello studio dei processi */
|
the_stack_data/2737.c
|
/* 3) Gerar um vetor com cinco números aleatórios no intervalo entre 10 e 20, inclusive.
Para cada número exibir a sequência dos pares de 2 até o número gerado e a soma desses pares.
Utilizar função uma para mostrar pares e outra função que retorna a quantidade de pares.
Mostrar como na figura ao lado. */
#include <stdio.h>
int main(void)
{
int i;
int vetorA[5];
GVACL(vetorA, 5, 20, 10);
for (i = 0; i < 5; i++)
{
printf("%d ===> ", vetorA[i]);
PDP(vetorA, 5, i);
CSP(vetorA, 5);
printf("\n");
}
return 0;
}
//Funcao para gerar vetor aleatorio
void GVACL(int vetor[], int tam, int limS, int limI)
{
int i;
srand(time(NULL));
for (i = 0; i < tam; i++)
{
vetor[i] = rand() % (limS - limI + 1) + limI;
}
}
//Funcao para pegar divisores pares
void PDP(int vet[], int tam, int i)
{
int j;
for (j = 2; j <= vet[i]; j = j + 2)
{
if (vet[i] % 2 == 0)
{
if (vet[i] == j)
{
printf("%d.", j);
}
else
{
printf("%d, ", j);
}
}
}
}
// Funcao para calcular a soma dos pares
void CSP(int vet[], int tam)
{
int i, j;
int qtde = 0;
for (i = 0; i < tam; i++)
{
for (j = 2; j < vet[i]; j = j + 2)
{
if (vet[i] % 2 == 0)
{
qtde = qtde + j;
}
}
}
return (qtde);
}
|
the_stack_data/222424.c
|
/*
Resolucao:
Somar duas matrizes e imprimir o resultado
*/
#include <stdio.h>
int mat[101][101];
int main()
{
int i, j, k, n, x;
scanf("%d", &n);
for (k = 0; k < 2; ++k)
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j) {
scanf("%d", &x);
mat[i][j] += x;
}
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j)
printf("%d ", mat[i][j]);
printf("\n");
}
return 0;
}
|
the_stack_data/107953505.c
|
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.