file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/192330656.c | /*
BSD 2-Clause License
Copyright (c) 2016, Rafael Kitover
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <wctype.h>
#include <wchar.h>
#include <locale.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#define BUF_SIZE 4096
#define WBUF_SIZE BUF_SIZE * sizeof(wchar_t)
#define MSG_SIZE 256
const char* version = "0.3";
const char* msg_prefix = "bin2c: ";
void format_perror(const char* fmt, va_list args) {
static char error_str[MSG_SIZE];
static char fmt_str[MSG_SIZE];
strcpy(fmt_str, msg_prefix);
strncat(fmt_str, fmt, MSG_SIZE - sizeof(msg_prefix));
vsnprintf(error_str, sizeof(error_str), fmt_str, args);
perror(error_str);
}
void die(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
format_perror(fmt, args);
va_end(args);
exit(1);
}
void* safe_malloc(size_t size) {
void* allocated;
if (!(allocated = malloc(size)))
die("out of memory");
return allocated;
}
char* file_name_to_identifier(const char* file_name_cstr) {
wchar_t* file_name = safe_malloc(WBUF_SIZE);
wchar_t* identifier = safe_malloc(WBUF_SIZE);
char* identifier_cstr = safe_malloc(WBUF_SIZE);
wchar_t* file_name_ptr = file_name;
wchar_t* identifier_ptr = identifier;
wchar_t* file_name_end = NULL;
size_t file_name_len = 0;
int between_tokens = 0;
if ((file_name_len = mbstowcs(file_name, file_name_cstr, BUF_SIZE - 1)) == -1)
die("cannot convert '%s' to locale representation", file_name_cstr);
*identifier = 0;
file_name_end = file_name + file_name_len + 1;
while (file_name_ptr < file_name_end) {
if (iswalnum(*file_name_ptr)) {
*identifier_ptr = *file_name_ptr;
identifier_ptr++;
between_tokens = 0;
}
else if (!between_tokens) {
mbstowcs(identifier_ptr, "_", 1);
identifier_ptr++;
between_tokens = 1;
}
file_name_ptr++;
}
/* terminate identifier, on _ or on next position */
if (between_tokens) identifier_ptr--;
*identifier_ptr = 0;
if (wcstombs(identifier_cstr, identifier, WBUF_SIZE - 1) == -1)
die("failed to convert wide character string to bytes");
free(file_name);
free(identifier);
return identifier_cstr;
}
void usage(int err) {
FILE* stream = err ? stderr : stdout;
fputs(
"Usage: [32mbin2c [1;34m[[1;35mIN_FILE [1;34m[[1;35mOUT_FILE [1;34m[[1;35mVAR_NAME[1;34m][1;34m][1;34m][0m\n"
"Write [1;35mIN_FILE[0m as a C array of bytes named [1;35mVAR_NAME[0m into [1;35mOUT_FILE[0m.\n"
"\n"
"By default, [1mSTDIN[0m is the input and [1mSTDOUT[0m is the output, either can be explicitly specified with [1;35m-[0m.\n"
"\n"
"The default [1;35mVAR_NAME[0m is the [1;35mIN_FILE[0m name converted to an identifier, or [1m\"resource_data\"[0m\n"
"if it's [1mSTDIN[0m.\n"
"\n"
" [1m-h, --help[0m Show this help screen and exit.\n"
" [1m-v, --version[0m Print version and exit.\n"
"\n"
"Examples:\n"
" # write data from file [1;35m./compiled-resources.xrs[0m into header file [1;35m./resources.h[0m using variable name [1;35mresource_data[0m\n"
" [32mbin2c [1;35m./compiled-resources.xrs[0m [1;35m./resources.h[0m [1;35mresource_data[0m\n"
" # write data from [1mSTDIN[0m to [1mSTDOUT[0m with [1m\"resource_data\"[0m as the [1;35mVAR_NAME[0m\n"
" [32mbin2c[0m\n"
" # write data from [1;35m./compiled-resources.xrs[0m to [1mSTDOUT[0m with [1m\"compiled_resources_xrs\"[0m as the [1;35mVAR_NAME[0m\n"
" [32mbin2c [1;35m./compiled-resources.xrs[0m\n"
" # write data from [1;35m./compiled-resources.xrs[0m to [1;35m./resources.h[0m with [1m\"compiled_resources_xrs\"[0m as the [1;35mVAR_NAME[0m\n"
" [32mbin2c [1;35m./compiled-resources.xrs [1;35m./resources.h[0m\n"
"\n"
"Project homepage and documentation: <[1;34mhttp://github.com/rkitover/bin2c[0m>\n"
, stream);
}
void die_usage(const char* fmt, ...) {
static char fmt_str[MSG_SIZE];
va_list args;
va_start(args, fmt);
strcpy(fmt_str, msg_prefix);
strncat(fmt_str, fmt, MSG_SIZE - sizeof(msg_prefix) - 1);
strcat(fmt_str, "\n");
vfprintf(stderr, fmt_str, args);
va_end(args);
usage(1);
exit(1);
}
void exit_usage(int exit_code) {
usage(exit_code);
exit(exit_code);
}
int main(int argc, const char** argv) {
const char* usage_opts[] = {"-h", "--help"};
const char* version_opts[] = {"-v", "--version"};
const char* in_file_name = argc >= 2 ? argv[1] : NULL;
const char* out_file_name = argc >= 3 ? argv[2] : NULL;
const char* var_name = argc >= 4 ? argv[3] : NULL;
char* computed_identifier = NULL;
int i = 0, file_pos = 0, in_fd = -1;
size_t bytes_read = 0;
unsigned char* buf = safe_malloc(BUF_SIZE);
FILE *in_file, *out_file;
setlocale(LC_ALL, "");
if (argc > 4)
die_usage("invalid number of arguments");
if (argc >= 2) {
for (i = 0; i < (sizeof(usage_opts)/sizeof(char*)); i++) {
if (!strcmp(argv[1], usage_opts[i])) exit_usage(0);
}
for (i = 0; i < (sizeof(version_opts)/sizeof(char*)); i++) {
if (!strcmp(argv[1], version_opts[i])) {
printf("bin2c %s\n", version);
return 0;
}
}
}
if (!(in_file = !in_file_name || !strcmp(in_file_name, "-") ? stdin : fopen(in_file_name, "rb")))
die("can't open input file '%s'", in_file_name);
if (!(out_file = !out_file_name || !strcmp(out_file_name, "-") ? stdout : fopen(out_file_name, "w")))
die("can't open '%s' for writing", out_file_name);
if (in_file_name && !var_name)
var_name = computed_identifier = file_name_to_identifier(in_file_name);
fprintf(out_file, "/* generated from %s: do not edit */\n"
"static const unsigned char %s[] = {\n",
in_file_name ? in_file_name : "resource data",
var_name ? var_name : "resource_data"
);
in_fd = fileno(in_file);
while ((bytes_read = read(in_fd, buf, BUF_SIZE))) {
for (i = 0; i < bytes_read; i++) {
char* comma = bytes_read < BUF_SIZE && i == bytes_read - 1 ? "" : ",";
fprintf(out_file, "0x%02x%s", buf[i], comma);
if (++file_pos % 16 == 0) fputc('\n', out_file);
}
}
fputs("};\n", out_file);
free(buf);
free(computed_identifier);
fclose(in_file);
fclose(out_file);
return 0;
}
|
the_stack_data/15581.c | /*
* Decremental loop iteration,
* Default loop scheduling
*/
#include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#endif
int a[20];
int main(void)
{
int i;
int j = 100;
#pragma omp parallel
{
#pragma omp single
printf ("Using %d threads.\n",omp_get_num_threads());
#pragma omp for nowait firstprivate(j) lastprivate(j)
for (i=19;i>-1;i-=3)
{
a[i]=i*2+j;
printf("Iteration %2d is carried out by thread %2d\n",\
i, omp_get_thread_num());
}
}
return 0;
}
|
the_stack_data/14609.c | #include <stdio.h>
#include <ctype.h>
int strip = 0; /* => discard special characters */
int invert = 0; /* => if any printable characters are contained, the name is not
printed */
int is_printable(FILE *fp);
/*
* if there are no file name argument, it do nothing.
*/
int main(int argc, char *argv[])
{
FILE *fp;
while (argc > 1 && argv[1][0] == '-') {
switch (argv[1][1]) {
case 's':
strip = 1;
break;
case 'v':
invert = 1;
break;
default:
fprintf(stderr, "%s: unknown arg %s\n", argv[0], argv[1]);
return 1;
}
argc--;
argv++;
}
if (argc != 1) {
for (int i = 1; i < argc; i++) {
if ((fp = fopen(argv[i], "r")) == NULL) {
fprintf(stderr, "%s: can't open %s\n", argv[0], argv[i]);
return 1;
} else {
if (is_printable(fp)) {
printf("%s\n", argv[i]);
}
fclose(fp);
}
}
}
return 0;
}
int is_printable(FILE *fp)
{
int c;
int val = 1;
while ((c = getc(fp)) != EOF) {
if (isascii(c) && (isprint(c) || c == '\n' || c == '\t' || c == ' ')) {
//
} else {
val = 0;
}
}
return invert ? !val : val;
}
|
the_stack_data/2982.c | extern void abort (void);
extern void exit (int);
union iso_directory_record {
char carr[4];
struct {
unsigned char name_len [1];
char name [0];
} u;
} entry;
void set(union iso_directory_record *);
int main (void)
{
union iso_directory_record *de;
de = &entry;
set(de);
if (de->u.name_len[0] == 1 && de->u.name[0] == 0)
exit (0);
else
abort ();
}
void set (union iso_directory_record *p)
{
p->carr[0] = 1;
p->carr[1] = 0;
return;
}
|
the_stack_data/927457.c | #include <stdint.h>
#include <stdio.h>
void main() {
int32_t a;
a = 1 & 2;
}
|
the_stack_data/89201442.c | /* Coverity Scan model
*
* This is a modelling file for Coverity Scan. Modelling helps to avoid false
* positives.
*
* - A model file can't import any header files.
* - Therefore only some built-in primitives like int, char and void are
* available but not NULL etc.
* - Modelling doesn't need full structs and typedefs. Rudimentary structs
* and similar types are sufficient.
* - An uninitialised local pointer is not an error. It signifies that the
* variable could be either NULL or have some data.
*
* Coverity Scan doesn't pick up modifications automatically. The model file
* must be uploaded by an admin in the analysis.
*
* Based on:
* http://hg.python.org/cpython/file/tip/Misc/coverity_model.c
* Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
* 2011, 2012, 2013 Python Software Foundation; All Rights Reserved
*
*/
/*
* Useful references:
* https://scan.coverity.com/models
*/
typedef unsigned int switch_status_t;
struct pthread_mutex_t {};
struct switch_mutex
{
struct pthread_mutex_t lock;
};
typedef struct switch_mutex switch_mutex_t;
switch_status_t switch_mutex_lock(switch_mutex_t *lock)
{
__coverity_recursive_lock_acquire__(&lock->lock);
}
switch_status_t switch_mutex_unlock(switch_mutex_t *lock)
{
__coverity_recursive_lock_release__(&lock->lock);
}
|
the_stack_data/34512534.c | #include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <math.h>
#include <sys/time.h>
#include <stdbool.h>
#define p(a) printf("\e[1;%dm", a)
#define normal() printf("\e[0m")
#define rd "\x1b[31m"
#define rst "\x1b[0m"
#define SHMSIZE 27 /* Size of the shared memory */
char uid;
// str title;
// shm - Store karega ki session start ho gaya yaa nahi
// shm1 - Store karega latest person ki UID
// shm2 - Store karega current status
// shm3 - Likhna chalu hoga
void *reading(char *shm)
{
char *s;
*(shm + 2) = 'i';
bool check = 0;
while (1)
{
if (*(shm + 2) == 'i')
{
check = 0;
sleep(0.001);
}
else if (*(shm + 2) == uid)
{
// printf("UID is %c", *(shm+2));
}
else
{
if (!check && *(shm + 2) != 'i')
{
check = 1;
s = shm + 3;
if (*s == '\n')
{
int x = *(shm + 2) - 97 + 31;
p(x);
printf("\n\t %c \e[0mhas joined the chat\n", *(shm + 2));
normal();
}
else
{
int x = *(shm + 2) - 97 + 31;
p(x);
printf("%c: ", *(shm + 2));
normal();
while (*s != 0)
{
putchar(*s++);
}
}
}
}
}
}
//
void *writing(char *shm)
{
char *s;
while (1)
{
sleep(1);
*(shm + 2) = 'i';
s = shm + 3;
char mess[50];
fgets(mess, sizeof(mess), stdin);
// Person B is writing:
for (int i = 0; shm[i] != '\0'; i++)
{
*s++ = mess[i];
}
*(shm + 2) = uid;
*s = 0;
}
}
int main()
{
pthread_t pt1, pt2;
char c;
int shmid;
key_t key;
char *shm, *s;
key = 4115; /* We need to get the segment named '5678' crated by the server */
printf("Please enter the key port\n");
scanf("%d", &key);
char title[50];
/* Locate the Segment */
if ((shmid = shmget(key, SHMSIZE, IPC_CREAT | 0666)) < 0)
{
perror("shmget");
exit(1);
}
/* Attach the segment to our data space */
if ((shm = shmat(shmid, NULL, 0)) == (char *)-1)
{
perror("shmat");
exit(0);
}
int array_id;
char strings[10][50];
int fd1;
char *myfifo = "/tmp/myfifo";
mkfifo(myfifo, 0666);
char str1[80], str2[80];
// Mera code yahan se chaalu hota hai
char session_status = *shm;
char latest_uid = *(shm + 1);
if (*shm == 'x')
{
system("clear");
fd1 = open(myfifo, O_RDONLY);
read(fd1, str1, 80);
p(32);
printf("\t%s\n\n", str1);
normal();
close(fd1);
fd1 = open(myfifo, O_WRONLY);
write(fd1, str1, strlen(str1) + 1);
close(fd1);
uid = (*(shm + 1)) + 1;
*(shm + 1) += 1;
int x = uid - 97 + 31;
printf("\nWelcome \e[1;%d%c\n", x, uid);
}
else
{
printf("Enter the title to the group\n");
fd1 = open(myfifo, O_WRONLY);
fgets(str2, 80, stdin);
write(fd1, str2, strlen(str2) + 1);
close(fd1);
*shm = 'x';
uid = *(shm + 1) = 'a';
}
/* Now read whatever server has put in into shared memory */
pthread_create(&pt1, NULL, reading, shm);
// sleep(1);
pthread_create(&pt2, NULL, writing, shm);
pthread_join(pt1, NULL);
exit(0);
}
|
the_stack_data/809364.c | struct a {
int b
};
struct c {
int d;
int e;
int f;
int g
};
struct h {
int aa;
struct c i;
int j
};
k, l, m, n, o, p, q, r, s, t, u, v, w, x;
y() {
struct a *a = z();
struct h *b = 0;
if (ab()) {
b->j = k;
b->i.g = o;
b->i.f = q;
b->i.e = r;
b->i.d = s;
a->b = &p;
} else {
b->j = l;
b->i.g = t;
b->i.f = v;
b->i.e = w;
b->i.d = x;
a->b = &u;
}
if (n)
ac();
else {
!b->aa;
ad(m);
}
}
|
the_stack_data/107952838.c | #include <stdio.h>
#define LIMIT 500
void func(int n) {
if(n < 0 || n > LIMIT) {
return;
}
n = 2*n;
printf("%d\n", n);
func(n);
printf("%d\n", n);
}
int main() {
func(10);
return 0;
} |
the_stack_data/90762324.c | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <string.h>
int main() {
int m_id;
//key_t key=1234;
//key_t key=0x000004d2;
//key_t key=IPC_PRIVATE;
key_t key=ftok("/home/schi/examples.desktopaaaaa", 'x');
if (key==-1) {
//if (m_id=msgget(key, IPC_CREAT)<0) {
fprintf(stderr, "%s: %d. Error in ftok #%03d: %s\n", __FILE__, __LINE__, errno, strerror(errno));
exit(EXIT_FAILURE);
}
//if (m_id=msgget(key, IPC_CREAT | IPC_EXCL)<0) {
if (m_id=msgget(key, IPC_CREAT)<0) {
fprintf(stderr, "%s: %d. Error in msgget #%03d: %s\n", __FILE__, __LINE__, errno, strerror(errno));
exit(EXIT_FAILURE);
}
printf("Created message queue identifier: %d\n",m_id);
exit(EXIT_SUCCESS);
}
|
the_stack_data/1074150.c | #include <stdio.h>
#define MAXLINE 100
int get(char line[], int maxline);
void copy(char to[], char from[]);
// print the longest input line
void main()
{
int len, max; // Current, Max length
char line[MAXLINE]; // current line
char longest[MAXLINE]; // longest line store
max = 0;
while ((len = get(line, MAXLINE)) > 0)
{
if (len > max) {
max = len;
copy(longest, line);
}
}
if (max > 0) {
printf("%s\n", longest);
}
}
int get(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
s[i] = c;
}
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0') {
++i;
}
}
|
the_stack_data/51701106.c | /* Test generation of mulchwu on 405. */
/* Origin: Joseph Myers <[email protected]> */
/* { dg-do compile } */
/* { dg-require-effective-target ilp32 } */
/* { dg-options "-O2 -mcpu=405" } */
/* { dg-final { scan-assembler "mulchwu " } } */
int
f(unsigned int b, unsigned int c)
{
unsigned int a = (unsigned short)b * (c >> 16);
return a;
}
|
the_stack_data/92327658.c | //
// Created by Administrator on 2018/11/28.
//
#include <stdio.h>
#include <malloc.h>
#include <math.h>
int* scanfmyself(int n);
int* findPri(int begin,int end);
int powInt(int, int);
int main() {
int* p = scanfmyself(1);
int n, flag = 1;
for(int i = 2; i <= p[0]; i++) {
n = powInt(2, i) - 1;
int *pp = findPri(n, n);
if(pp[0]) {
flag = 0;
printf("%d\n", n);
}
}
if(flag) printf("None");
return 0;
}
int powInt(int num, int n) {
int result = 1;
for(int i = 0; i < n; i++) {
result *= num;
}
return result;
}
//索性写一个专门接受整型的函数吧
//p是数组,n是我要输入的整型的数字
int* scanfmyself(int n) {
int *p = (int*)malloc(n * sizeof(int));
for(int i = 0; i < n; i++) {
scanf("%d", p+i);
}
return p;
}
//返回的数组0号元素为size,其他是素数
//这里的p[0],表示的是其后素数的个数,与我之后写的其他函数不同
int* findPri(int begin,int end) {
int size = 0;
int* p = NULL; //数组记录素数
int cap = 7;
p = (int*)malloc(cap * sizeof(int));
p[0] = size;
if(begin != 2) {
begin = (begin%2 == 0||(begin == 1&&end != 1))?begin+1:begin;
}
if(begin == 2){
//when == 2
size = 1;
p[0] = 1;
p[1] = 2;
begin++;
}
for(int i = begin; i <= end && i > 2; i += 2) {
int flag = 1;
//从二开始,可以排除一
for(int j = 2; j <= sqrt(i); j++) {
if(i%j==0) {
flag = 0;
break;
}
}
if(flag == 1) {
size++;
if(cap <= size) {
cap *= 2;
p = (int*)realloc(p, cap * sizeof(int));
}
p[0] = size;
p[size] = i; //记录素数
}
}
return p;
}
|
the_stack_data/83841.c | #include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
int main(){
printf("real uid: %d\n", getuid());
printf("effective uid: %d\n", geteuid());
}
//end of code
|
the_stack_data/73575492.c | #include <stdio.h>
int insertionSort(int arr[], int n);
void printArray(int arr[], int n);
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
void printArray(int arr[], int n)
{
int i;
for (i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
|
the_stack_data/145451717.c | /* Exercise 1.15. Rewrite the temperature conversion program of Section 1.2 to
use a function for conversion. */
#include <stdio.h>
float celsius(float fahr);
/* print Fahrenheit-Celsius table for fahr = 0, 20, ..., 300;
floating-point version, using a function */
int main(void)
{
float fahr;
float lower, upper, step;
lower = 0; /* lower limit of temperatuire scale */
upper = 300; /* upper limit */
step = 20; /* step size */
fahr = lower;
while (fahr <= upper) {
printf("%3.0f %6.1f\n", fahr, celsius(fahr)); /* modified */
fahr = fahr + step;
}
}
float celsius(float fahr)
{
return (5.0/9.0) * (fahr-32.0);
}
|
the_stack_data/168726.c | // RUN: not --crash %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection %s 2>&1 | FileCheck %s
// REQUIRES: crash-recovery
// FIXME: CHECKs might be incompatible to win32.
// Stack traces also require back traces.
// REQUIRES: shell, backtrace
void clang_analyzer_crash(void);
void inlined() {
clang_analyzer_crash();
}
void test() {
inlined();
}
// CHECK: 0. Program arguments: {{.*}}clang
// CHECK-NEXT: 1. <eof> parser at end of file
// CHECK-NEXT: 2. While analyzing stack:
// CHECK-NEXT: #0 void inlined()
// CHECK-NEXT: #1 void test()
// CHECK-NEXT: 3. {{.*}}crash-trace.c:{{[0-9]+}}:3: Error evaluating statement
|
the_stack_data/126702134.c | #include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char **argv) {
for (int arg = 1; arg < argc; arg++) {
if (argc > 2) {
write(1, "==> ", 4);
write(1, argv[arg], strlen(argv[arg]));
write(1, " <==\n", 5);
}
int fd = open(argv[arg], O_RDONLY);
for (int i = 0; i < 10; i++) {
char j;
read(fd, &j, sizeof(char));
write(1, &j, sizeof(char));
while (j != '\n') {
read(fd, &j, sizeof(char));
write(1, &j, sizeof(char));
}
}
if (arg != argc - 1) {
write(1, "\n", 1);
}
close(fd);
}
return 0;
}
|
the_stack_data/60297.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2015-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
extern void test (void);
int
main (void)
{
test ();
return 0;
}
|
the_stack_data/81459.c | //
// Created by shinnlove on 2019-02-20.
//
#include <stdio.h>
void Qsort(int a[], int low, int high) {
if (low >= high) {
return;
}
int first = low;
int last = high;
int key = a[first]; // 用字表的第一个记录作为枢轴
while (first < last) {
while (first < last && a[last] >= key) {
--last;
}
a[first] = a[last]; // 将比第一个小的移到低端
while (first < last && a[first] <= key) {
++first;
}
a[last] = a[first];
// 将比第一个大的移到高端
}
a[first] = key; // 枢轴记录到位
Qsort(a, low, first - 1);
Qsort(a, first + 1, high);
}
int main() {
// 参考数据结构p274(清华大学出版社,严蔚敏)
int a[] = {57, 68, 59, 52, 72, 28, 96, 33, 24};
// 这里原文第三个参数要减1否则内存越界
Qsort(a, 0, sizeof(a) / sizeof(a[0]) - 1);
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++) {
printf("%d ", a[i]);
}
return 0;
} |
the_stack_data/115766079.c | /******************************************************************************
* Copyright (c) 1998 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* Memory management utilities
*
* Routines to use "Debug Malloc Library", dmalloc
*
*****************************************************************************/
#ifdef HYPRE_MEMORY_DMALLOC
#include "memory.h"
#include <dmalloc.h>
char dmalloc_logpath_memory[256];
/*--------------------------------------------------------------------------
* hypre_InitMemoryDebugDML
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_InitMemoryDebugDML( HYPRE_Int id )
{
HYPRE_Int *iptr;
/* do this to get the Debug Malloc Library started/initialized */
iptr = hypre_TAlloc(HYPRE_Int, 1, HYPRE_MEMORY_HOST);
hypre_TFree(iptr, HYPRE_MEMORY_HOST);
dmalloc_logpath = dmalloc_logpath_memory;
hypre_sprintf(dmalloc_logpath, "dmalloc.log.%04d", id);
return 0;
}
/*--------------------------------------------------------------------------
* hypre_FinalizeMemoryDebugDML
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_FinalizeMemoryDebugDML( )
{
dmalloc_verify(NULL);
return 0;
}
/*--------------------------------------------------------------------------
* hypre_MAllocDML
*--------------------------------------------------------------------------*/
char *
hypre_MAllocDML( HYPRE_Int size,
char *file,
HYPRE_Int line )
{
char *ptr;
if (size > 0)
{
ptr = _malloc_leap(file, line, size);
}
else
{
ptr = NULL;
}
return ptr;
}
/*--------------------------------------------------------------------------
* hypre_CAllocDML
*--------------------------------------------------------------------------*/
char *
hypre_CAllocDML( HYPRE_Int count,
HYPRE_Int elt_size,
char *file,
HYPRE_Int line )
{
char *ptr;
HYPRE_Int size = count * elt_size;
if (size > 0)
{
ptr = _calloc_leap(file, line, count, elt_size);
}
else
{
ptr = NULL;
}
return ptr;
}
/*--------------------------------------------------------------------------
* hypre_ReAllocDML
*--------------------------------------------------------------------------*/
char *
hypre_ReAllocDML( char *ptr,
HYPRE_Int size,
char *file,
HYPRE_Int line )
{
ptr = _realloc_leap(file, line, ptr, size);
return ptr;
}
/*--------------------------------------------------------------------------
* hypre_FreeDML
*--------------------------------------------------------------------------*/
void
hypre_FreeDML( char *ptr,
char *file,
HYPRE_Int line )
{
if (ptr)
{
_free_leap(file, line, ptr);
}
}
#else
/* this is used only to eliminate compiler warnings */
char hypre_memory_dmalloc_empty;
#endif
|
the_stack_data/952341.c | // File: 3.3.c
// Author: TaoKY
#include <stdio.h>
#include <math.h>
int main(){
int d = 300000, p = 6000;
double r = 0.01;
printf("%.1lf\n", log10(p / (p - d * r)) / log10(1 + r));
return 0;
}
|
the_stack_data/46659.c | #include <unistd.h> // fork()
#include <sys/wait.h> // waitpid()
#include <stdio.h> // printf(), fgets()
#include <string.h> // strtok(), strcmp(), strdup()
#include <stdlib.h> // free()
#include <fcntl.h> // open(), creat(), close()
const unsigned MAX_LINE_LENGTH = 89;
const unsigned BUF_SIZE = 64;
const unsigned REDIR_SIZE = 2;
const unsigned PIPE_SIZE = 3;
const unsigned MAX_HISTORY = 30;
const unsigned MAX_COMMAND_NAME = 30;
const unsigned ANTI_CHINA_WORDLIST_SIZE = 64;
const char *ANTI_CHINA_WORDLIST[] = {"xjp","winnie","democracy","freedom","justice"};
void parse_cmd(char input[], char *argv[], int *wait)
{
for (unsigned idx = 0; idx < BUF_SIZE; idx++)
{
argv[idx] = NULL;
}
if (input[strlen(input) - 1] == '&')
{
*wait = 1;
input[strlen(input) - 1] = '\0';
}
else
{
*wait = 0;
}
const char *delim = " ";
unsigned idx = 0;
char *token = strtok(input, delim);
while (token != NULL)
{
argv[idx++] = token;
token = strtok(NULL, delim);
}
argv[idx] = NULL;
}
void parse_redir(char *argv[], char *redir_argv[])
{
unsigned idx = 0;
redir_argv[0] = NULL;
redir_argv[1] = NULL;
while (argv[idx] != NULL)
{
if (strcmp(argv[idx], "<") == 0 || strcmp(argv[idx], ">") == 0)
{
if (argv[idx + 1] != NULL)
{
redir_argv[0] = strdup(argv[idx]);
redir_argv[1] = strdup(argv[idx + 1]);
argv[idx] = NULL;
argv[idx + 1] = NULL;
}
}
idx++;
}
}
int parse_pipe(char *argv[], char *child01_argv[], char *child02_argv[])
{
unsigned idx = 0, split_idx = 0;
int contains_pipe = 0;
int cnt = 0;
while (argv[idx] != NULL)
{
if (strcmp(argv[idx], "|") == 0)
{
split_idx = idx;
contains_pipe = 1;
}
idx++;
}
if (!contains_pipe)
{
return 0;
}
for (idx = 0; idx < split_idx; idx++)
{
child01_argv[idx] = strdup(argv[idx]);
}
child01_argv[idx++] = NULL;
while (argv[idx] != NULL)
{
child02_argv[idx - split_idx - 1] = strdup(argv[idx]);
idx++;
}
child02_argv[idx - split_idx - 1] = NULL;
return 1;
}
void child(char *argv[], char *redir_argv[])
{
int fd_out, fd_in;
if (redir_argv[0] != NULL)
{
if (strcmp(redir_argv[0], ">") == 0)
{
fd_out = creat(redir_argv[1], S_IRWXU);
if (fd_out == -1)
{
perror("Redirect output failed");
exit(EXIT_FAILURE);
}
dup2(fd_out, STDOUT_FILENO);
if (close(fd_out) == -1)
{
perror("Closing output failed");
exit(EXIT_FAILURE);
}
}
else if (strcmp(redir_argv[0], "<") == 0)
{
fd_in = open(redir_argv[1], O_RDONLY);
if (fd_in == -1)
{
perror("Redirect input failed");
exit(EXIT_FAILURE);
}
dup2(fd_in, STDIN_FILENO);
if (close(fd_in) == -1)
{
perror("Closing input failed");
exit(EXIT_FAILURE);
}
}
}
if (execvp(argv[0], argv) == -1)
{
perror("Fail to execute command");
exit(EXIT_FAILURE);
}
}
void parent(pid_t child_pid, int wait)
{
int status;
printf("Parent <%d> spawned a child <%d>.\n", getpid(), child_pid);
switch (wait)
{
case 0:
{
waitpid(child_pid, &status, 0);
break;
}
default:
{
waitpid(child_pid, &status, WUNTRACED);
if (WIFEXITED(status))
{
printf("Child <%d> exited with status = %d.\n", child_pid, status);
}
break;
}
}
}
void add_history_feature(char *history[], int *history_count, char *input_line)
{
if (*history_count < MAX_HISTORY)
{
strcpy(history[(*history_count)++], input_line);
}
else
{
free(history[0]);
for (int i = 1; i < MAX_HISTORY; i++)
{
strcpy(history[i - 1], history[i]);
}
strcpy(history[MAX_HISTORY - 1], input_line);
}
}
void exec_with_pipe(char *child01_argv[], char *child02_argv[])
{
int pipefd[2];
if (pipe(pipefd) == -1)
{
perror("pipe() failed");
exit(EXIT_FAILURE);
}
if (fork() == 0)
{
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[0]);
close(pipefd[1]);
execvp(child01_argv[0], child01_argv);
perror("Fail to execute first command");
exit(EXIT_FAILURE);
}
if (fork() == 0)
{
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[1]);
close(pipefd[0]);
execvp(child02_argv[0], child02_argv);
perror("Fail to execute second command");
exit(EXIT_FAILURE);
}
close(pipefd[0]);
close(pipefd[1]);
wait(0);
wait(0);
}
int main()
{
int running = 1;
pid_t pid;
int status = 0, history_count = 0, wait;
char input_line[MAX_LINE_LENGTH];
char *argv[BUF_SIZE], *redir_argv[REDIR_SIZE];
char *child01_argv[PIPE_SIZE], *child02_argv[PIPE_SIZE];
char *history[MAX_HISTORY];
for (int i = 0; i < MAX_HISTORY; i++)
{
history[i] = (char *)malloc(MAX_COMMAND_NAME);
}
while (running)
{
printf("winniesh>");
fflush(stdout);
while (fgets(input_line, MAX_LINE_LENGTH, stdin) == NULL)
{
perror("Cannot read user input!");
fflush(stdin);
}
input_line[strcspn(input_line, "\n")] = '\0';
add_history_feature(history, &history_count, input_line);
parse_cmd(input_line, argv, &wait);
parse_redir(argv, redir_argv);
if (strcmp(input_line, "exit") == 0)
{
running = 0;
continue;
}
if (strcmp(input_line, "!!") == 0)
{
if (history_count == 0)
{
fprintf(stderr, "No commands in history\n");
continue;
}
strcpy(input_line, history[history_count - 1]);
printf("winniesh>%s\n", input_line);
}
if (strcmp(input_line, "history") == 0)
{
for (int k = 0; k < history_count; ++k)
{
printf("%s\n", history[k]);
}
continue;
}
if (strcmp(input_line, "hk") == 0)
{
printf("光復香港 時代革命\n");
// 五大诉求 缺一不可
continue;
}
for (int count = 0; count < sizeof(ANTI_CHINA_WORDLIST) / sizeof(char *); count++){
if (strcmp(input_line, ANTI_CHINA_WORDLIST[count]) == 0)
{
printf("本代码不欢迎反华分子使用\n");
exit(EXIT_FAILURE);
}
}
if (strcmp(argv[0], "cd") == 0)
{
if (argv[1] == NULL)
{
chdir("/");
continue;
}
else
{
chdir(argv[1]);
continue;
}
}
if (parse_pipe(argv, child01_argv, child02_argv))
{
exec_with_pipe(child01_argv, child02_argv);
continue;
}
pid_t pid = fork();
switch (pid)
{
case -1:
perror("fork() failed!");
exit(EXIT_FAILURE);
case 0:
child(argv, redir_argv);
exit(EXIT_SUCCESS);
default:
parent(pid, wait);
}
}
return 0;
}
|
the_stack_data/211081087.c | /* { dg-do compile } */
/* { dg-options "-O2 -fdump-tree-dom2-details" } */
void foo();
void bla();
void bar();
/* Avoid threading in the following case, to prevent creating subloops. */
void dont_thread_2 (int first)
{
int i = 0;
do
{
if (first)
foo ();
else
bar ();
first = 0;
bla ();
} while (i++ < 100);
}
/* Peeling off the first iteration would make threading through
the loop latch safe, but we don't do that currently. */
/* { dg-final { scan-tree-dump-not "IRREDUCIBLE_LOOP" "dom2" } } */
|
the_stack_data/145452887.c |
char foo(void);
char foo(void)
{
char c = 0;
char d = 1;
c = d + 3;
return c;
} |
the_stack_data/154831243.c | #include <stdlib.h>
long val = 0x5e000000;
long
f1 (void)
{
return 0x132;
}
long
f2 (void)
{
return 0x5e000000;
}
void
f3 (long b)
{
val = b;
}
void
f4 ()
{
long v = f1 ();
long o = f2 ();
v = (v & 0x00ffffff) | (o & 0xff000000);
f3 (v);
}
int main ()
{
f4 ();
if (val != 0x5e000132)
abort ();
exit (0);
}
|
the_stack_data/76701229.c | #include <stdio.h>
#include <stdlib.h>
void foo(FILE *f) {
fseek(f, 0L, SEEK_END);
printf("The size of the file is %ld bytes.\n", ftell(f));
fclose(f);
}
int main(int argc, char **argv) {
FILE *f;
f = fopen(argv[1], "r");
foo(f);
return 0;
} |
the_stack_data/1266352.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int numDecodings(char* s) {
static volatile int i;
static int cnt = 0;
int e = 0; // for function return roll back i
for (; s[i]!=0; ++i) {
if ((s[i]!='0')&&(s[i+1]!=0)){
int num_t=10*(s[i]-'0')+(s[i+1]-'0');
printf("num_t:%d\n",num_t);
if ((num_t>9)&&(num_t <= 26)){
printf("in i: %d\n",i);
++i;
numDecodings(s);
}
}
printf("out i: %d\n",i);
++e;
printf("out e: %d\n",e);
}
i=i-e;
printf("cnt:%d\n",++cnt);
printf("ret i: %d\n",i);
return cnt;
}
int main(int argc, char **argv) {
numDecodings(argv[1]);
return 0;
}
|
the_stack_data/125140545.c | int f(int x) {
// 0
if (x == 0) { // 1
return x; // 2
} else {
int a[3]; // 3
a[0] = -x;
return a[0];
}
}
int main() {
printf("%d\n", f(10));
return 0;
}
|
the_stack_data/17999.c | /* EXERCICIO 1
Faça uma função que crie um arquivo txt chamado ex1.txt e grave
o texto: “Arquivo 1” no arquivo. Após ter gravado no arquivo, leia
esse texto para uma variável e mostre o valor da variável na tela.
OBS: Utilize a função que achar melhor (fscanf, fprintf, fgets ou fputs).
*/
#include <stdio.h>
int main(){
char leitura[30];
FILE *arq;
arq = fopen("ex1.txt", "w");
fprintf(arq, "Arquivo 1");
rewind(arq);
fgets(leitura, 30, arq);
printf("%c", leitura);
return 0;
}
|
the_stack_data/1612.c |
struct Foo1 {
char a;
};
int f1(struct Foo1 v1, struct Foo1 v2)
{
return v1.a + v2.a;
}
struct Foo2 {
int a;
int b;
};
int f2(struct Foo2 v)
{
return v.a + v.b;
}
int
main()
{
struct Foo1 v1, v2;
v1.a = 1;
v2.a = 2;
if(f1(v1, v2) != 3)
return 1;
struct Foo2 v;
v.a = 1;
v.b = 2;
if(f2(v) != 3)
return 2;
return 0;
}
|
the_stack_data/59715.c | /*
* Test the insertion of multiple calls to runtime terminate functions.
* The function calls should not share the same statement.
* 7/25/2011
By C. Liao
*/
#include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#endif
int main(void)
{
int i=0, j=0;
#pragma omp parallel default(shared) private(i)
{
#ifdef _OPENMP
i=omp_get_thread_num()+j;
#endif
printf("Hello,world! I am thread %d\n",i);
}
if (i)
return 0;
else
return 0;
}
|
the_stack_data/29826347.c | /* lc482.c */
/* LeetCode 482. License Key Formatting `E` */
/* acc | 81%* | 32' */
/* A~0f15 */
char *licenseKeyFormatting(char *S, int K)
{
int charCnt = 0;
for (int i = 0; S[i]; ++i)
if (S[i] != '-')
++charCnt;
int firstLen = charCnt % K;
firstLen = firstLen == 0 ? K : firstLen;
int groupNum = charCnt / K + (firstLen != K);
int resLen = charCnt + groupNum - 1;
char *res;
if (charCnt == 0)
{
res = malloc(sizeof(char) * 1);
res[0] = 0;
return res;
}
else
res = malloc(sizeof(char) * (resLen + 1));
for (int i = 0, j = 0; i < resLen; ++i, ++j)
{
if ((i - firstLen) % (K + 1) == 0)
res[i++] = '-';
while (S[j] == '-')
++j;
res[i] = toupper(S[j]);
}
res[resLen] = 0;
return res;
}
|
the_stack_data/33004.c | /* prog0101.c */
int main()
{
} |
the_stack_data/89201509.c | #include <stdio.h>
int main()
{
int x, y;
scanf("%i\n%i", &x, &y);
if (x > y) {printf("1\n");}
else {printf("0\n");}
if (x == y) {printf("1\n");}
else {printf("0\n");}
if (x < y) {printf("1\n");}
else {printf("0\n");}
if (x != y) {printf("1\n");}
else {printf("0\n");}
if (x >= y) {printf("1\n");}
else {printf("0\n");}
if (x <= y) {printf("1\n");}
else {printf("0\n");}
return(0);
}
|
the_stack_data/192331495.c | /* Generated by CIL v. 1.3.7 */
/* print_CIL_Input is true */
#line 211 "/usr/lib/gcc/x86_64-linux-gnu/4.4.3/include/stddef.h"
typedef unsigned long size_t;
#line 31 "/usr/include/bits/types.h"
typedef unsigned char __u_char;
#line 33 "/usr/include/bits/types.h"
typedef unsigned int __u_int;
#line 34 "/usr/include/bits/types.h"
typedef unsigned long __u_long;
#line 143 "/usr/include/bits/types.h"
typedef int __pid_t;
#line 149 "/usr/include/bits/types.h"
typedef long __time_t;
#line 35 "/usr/include/sys/types.h"
typedef __u_char u_char;
#line 37 "/usr/include/sys/types.h"
typedef __u_int u_int;
#line 38 "/usr/include/sys/types.h"
typedef __u_long u_long;
#line 100 "/usr/include/sys/types.h"
typedef __pid_t pid_t;
#line 76 "/usr/include/time.h"
typedef __time_t time_t;
#line 201 "/usr/include/sys/types.h"
typedef unsigned char u_int8_t;
#line 202 "/usr/include/sys/types.h"
typedef unsigned short u_int16_t;
#line 203 "/usr/include/sys/types.h"
typedef unsigned int u_int32_t;
#line 52 "/usr/include/stdint.h"
typedef unsigned int uint32_t;
#line 141 "/usr/include/netinet/in.h"
typedef uint32_t in_addr_t;
#line 142 "/usr/include/netinet/in.h"
struct in_addr {
in_addr_t s_addr ;
};
#line 48 "/usr/include/arpa/nameser_compat.h"
struct __anonstruct_HEADER_25 {
unsigned int id : 16 ;
unsigned int rd : 1 ;
unsigned int tc : 1 ;
unsigned int aa : 1 ;
unsigned int opcode : 4 ;
unsigned int qr : 1 ;
unsigned int rcode : 4 ;
unsigned int cd : 1 ;
unsigned int ad : 1 ;
unsigned int unused : 1 ;
unsigned int ra : 1 ;
unsigned int qdcount : 16 ;
unsigned int ancount : 16 ;
unsigned int nscount : 16 ;
unsigned int arcount : 16 ;
};
#line 48 "/usr/include/arpa/nameser_compat.h"
typedef struct __anonstruct_HEADER_25 HEADER;
#line 165 "ns_defs.h"
enum severity {
ignore = 0,
warn = 1,
fail = 2,
not_set = 3
} ;
#line 173 "ns_defs.h"
struct zoneinfo {
char *z_origin ;
time_t z_time ;
time_t z_lastupdate ;
u_int32_t z_refresh ;
u_int32_t z_retry ;
u_int32_t z_expire ;
u_int32_t z_minimum ;
u_int32_t z_serial ;
char *z_source ;
time_t z_ftime ;
struct in_addr z_axfr_src ;
struct in_addr z_xaddr ;
struct in_addr z_addr[16] ;
u_char z_addrcnt ;
u_char z_type ;
u_int32_t z_flags ;
pid_t z_xferpid ;
u_int z_options ;
u_int z_optset ;
int z_class ;
int z_numxfrs ;
enum severity z_checknames ;
struct in_addr *z_also_notify ;
int z_notify_count ;
char *z_ixfr_base ;
char *z_ixfr_tmp ;
int z_maintain_ixfr_base ;
int z_log_size_ixfr ;
int z_max_log_size_ixfr ;
};
#line 303
enum transport {
primary_trans = 0,
secondary_trans = 1,
response_trans = 2,
update_trans = 3,
num_trans = 4
} ;
#line 312
enum context {
domain_ctx = 0,
owner_ctx = 1,
mailname_ctx = 2,
hostname_ctx = 3
} ;
#line 339 "/usr/include/stdio.h"
extern int printf(char const * __restrict __format , ...) ;
#line 43 "/usr/include/string.h"
extern __attribute__((__nothrow__)) void *memcpy(void * __restrict __dest , void const * __restrict __src ,
size_t __n ) __attribute__((__nonnull__(1,2))) ;
#line 127
extern __attribute__((__nothrow__)) char *strcpy(char * __restrict __dest , char const * __restrict __src ) __attribute__((__nonnull__(1,2))) ;
#line 397
extern __attribute__((__nothrow__)) size_t strlen(char const *__s ) __attribute__((__pure__,
__nonnull__(1))) ;
#line 411
extern __attribute__((__nothrow__)) char *strerror(int __errnum ) ;
#line 43 "/usr/include/bits/errno.h"
extern __attribute__((__nothrow__)) int *__errno_location(void) __attribute__((__const__)) ;
#line 271 "/usr/include/resolv.h"
extern __attribute__((__nothrow__)) int __res_init(void) ;
#line 326
__attribute__((__nothrow__)) int __res_hnok(char const *dn ) ;
#line 329
__attribute__((__nothrow__)) int __res_dnok(char const *dn ) ;
#line 351
extern __attribute__((__nothrow__)) char *__p_secstodate(u_long ) ;
#line 353
extern __attribute__((__nothrow__)) int __dn_comp(char const * , u_char * , int ,
u_char ** , u_char ** ) ;
#line 355
extern __attribute__((__nothrow__)) int __dn_expand(u_char const * , u_char const * ,
u_char const * , char * , int ) ;
#line 471 "/usr/include/stdlib.h"
extern __attribute__((__nothrow__)) void *malloc(size_t __size ) __attribute__((__malloc__)) ;
#line 186 "/usr/include/time.h"
extern __attribute__((__nothrow__)) time_t time(time_t *__timer ) ;
#line 71 "/usr/include/assert.h"
extern __attribute__((__nothrow__, __noreturn__)) void __assert_fail(char const *__assertion ,
char const *__file ,
unsigned int __line ,
char const *__function ) ;
#line 104 "sig-bad.c"
char const *transport_strings[4] = { "primary", "secondary", "response", (char const *)((void *)0)};
#line 140
__attribute__((__nothrow__)) int __res_dnok(char const *dn ) ;
#line 140 "sig-bad.c"
int __res_dnok(char const *dn )
{ int ch ;
char const *tmp ;
char __cil_tmp4 ;
{
{
#line 144
while (1) {
while_continue: /* CIL Label */ ;
#line 144
tmp = dn;
#line 144
dn = dn + 1;
#line 144
__cil_tmp4 = *tmp;
#line 144
ch = (int )__cil_tmp4;
#line 144
if (ch != 0) {
} else {
#line 144
goto while_break;
}
#line 145
if (ch > 32) {
#line 145
if (ch < 127) {
} else {
#line 146
return (0);
}
} else {
#line 146
return (0);
}
}
while_break: /* CIL Label */ ;
}
#line 147
return (1);
}
}
#line 150
__attribute__((__nothrow__)) int __res_hnok(char const *dn ) ;
#line 150 "sig-bad.c"
int __res_hnok(char const *dn )
{ int ppch ;
int pch ;
int ch ;
char const *tmp ;
int nch ;
char const *tmp___0 ;
char __cil_tmp8 ;
char __cil_tmp9 ;
{
#line 152
ppch = '\000';
#line 152
pch = 46;
#line 152
tmp = dn;
#line 152
dn = dn + 1;
#line 152
__cil_tmp8 = *tmp;
#line 152
ch = (int )__cil_tmp8;
{
#line 154
while (1) {
while_continue: /* CIL Label */ ;
#line 154
if (ch != 0) {
} else {
#line 154
goto while_break;
}
#line 155
tmp___0 = dn;
#line 155
dn = dn + 1;
#line 155
__cil_tmp9 = *tmp___0;
#line 155
nch = (int )__cil_tmp9;
#line 157
if (ch == 46) {
} else
#line 159
if (pch == 46) {
#line 160
if (ch >= 65) {
#line 160
if (ch <= 90) {
} else {
#line 160
goto _L___0;
}
} else
_L___0: /* CIL Label */
#line 160
if (ch >= 97) {
#line 160
if (ch <= 122) {
} else {
#line 160
goto _L;
}
} else
_L: /* CIL Label */
#line 160
if (ch >= 48) {
#line 160
if (ch <= 57) {
} else {
#line 161
return (0);
}
} else {
#line 161
return (0);
}
} else
#line 162
if (nch == 46) {
#line 162
goto _L___6;
} else
#line 162
if (nch == 0) {
_L___6: /* CIL Label */
#line 163
if (ch >= 65) {
#line 163
if (ch <= 90) {
} else {
#line 163
goto _L___2;
}
} else
_L___2: /* CIL Label */
#line 163
if (ch >= 97) {
#line 163
if (ch <= 122) {
} else {
#line 163
goto _L___1;
}
} else
_L___1: /* CIL Label */
#line 163
if (ch >= 48) {
#line 163
if (ch <= 57) {
} else {
#line 164
return (0);
}
} else {
#line 164
return (0);
}
} else
#line 166
if (ch >= 65) {
#line 166
if (ch <= 90) {
} else {
#line 166
goto _L___5;
}
} else
_L___5: /* CIL Label */
#line 166
if (ch >= 97) {
#line 166
if (ch <= 122) {
} else {
#line 166
goto _L___4;
}
} else
_L___4: /* CIL Label */
#line 166
if (ch >= 48) {
#line 166
if (ch <= 57) {
} else {
#line 166
goto _L___3;
}
} else
_L___3: /* CIL Label */
#line 166
if (ch == 45) {
} else {
#line 167
return (0);
}
#line 169
ppch = pch;
#line 169
pch = ch;
#line 169
ch = nch;
}
while_break: /* CIL Label */ ;
}
#line 171
return (1);
}
}
#line 175 "sig-bad.c"
enum context ns_ownercontext(int type , enum transport transport )
{ enum context context ;
char const * __restrict __cil_tmp4 ;
{
#line 180
context = (enum context )0;
{
#line 183
if (type == 1) {
#line 183
goto case_1;
} else {
}
#line 184
if (type == 11) {
#line 184
goto case_1;
} else {
}
#line 185
if (type == 15) {
#line 185
goto case_1;
} else {
}
#line 200
if (type == 7) {
#line 200
goto case_7;
} else {
}
#line 201
if (type == 8) {
#line 201
goto case_7;
} else {
}
#line 204
goto switch_default___0;
case_1: /* CIL Label */
case_11: /* CIL Label */
case_15: /* CIL Label */
{
#line 187
if ((int )transport == 3) {
#line 187
goto case_3;
} else {
}
#line 188
if ((int )transport == 0) {
#line 188
goto case_3;
} else {
}
#line 189
if ((int )transport == 1) {
#line 189
goto case_3;
} else {
}
#line 192
if ((int )transport == 2) {
#line 192
goto case_2;
} else {
}
#line 195
goto switch_default;
case_3: /* CIL Label */
case_0: /* CIL Label */
case_1___0: /* CIL Label */
#line 190
context = (enum context )1;
#line 191
goto switch_break___0;
case_2: /* CIL Label */
#line 193
context = (enum context )3;
#line 194
goto switch_break___0;
switch_default: /* CIL Label */
{
#line 196
__cil_tmp4 = (char const * __restrict )"impossible condition in ns_ownercontext()";
#line 196
printf(__cil_tmp4);
}
switch_break___0: /* CIL Label */ ;
}
#line 199
goto switch_break;
case_7: /* CIL Label */
case_8: /* CIL Label */
#line 202
context = (enum context )2;
#line 203
goto switch_break;
switch_default___0: /* CIL Label */
#line 206
goto switch_break;
switch_break: /* CIL Label */ ;
}
#line 208
return (context);
}
}
#line 219 "sig-bad.c"
char *newstr(size_t len , int needpanic )
{ u_char *buf ;
u_char *bp ;
void *tmp ;
int *tmp___0 ;
char *tmp___1 ;
register u_int16_t t_s ;
register u_char *t_cp ;
u_char *tmp___2 ;
size_t __cil_tmp11 ;
size_t __cil_tmp12 ;
void *__cil_tmp13 ;
unsigned long __cil_tmp14 ;
unsigned long __cil_tmp15 ;
int __cil_tmp16 ;
char const * __restrict __cil_tmp17 ;
void *__cil_tmp18 ;
int __cil_tmp19 ;
int __cil_tmp20 ;
{
#line 223
if (len <= 65536UL) {
} else {
{
#line 223
__assert_fail("len <= 65536", "sig-bad.c", 223U, "newstr");
}
}
{
#line 225
__cil_tmp11 = 2UL + len;
#line 225
__cil_tmp12 = __cil_tmp11 + 1UL;
#line 225
tmp = malloc(__cil_tmp12);
#line 225
buf = (u_char *)tmp;
}
{
#line 226
__cil_tmp13 = (void *)0;
#line 226
__cil_tmp14 = (unsigned long )__cil_tmp13;
#line 226
__cil_tmp15 = (unsigned long )buf;
#line 226
if (__cil_tmp15 == __cil_tmp14) {
#line 227
if (needpanic) {
{
#line 228
tmp___0 = __errno_location();
#line 228
__cil_tmp16 = *tmp___0;
#line 228
tmp___1 = strerror(__cil_tmp16);
#line 228
__cil_tmp17 = (char const * __restrict )"savestr: malloc failed (%s)";
#line 228
printf(__cil_tmp17, tmp___1);
}
} else {
{
#line 230
__cil_tmp18 = (void *)0;
#line 230
return ((char *)__cil_tmp18);
}
}
} else {
}
}
#line 232
bp = buf;
{
#line 233
while (1) {
while_continue: /* CIL Label */ ;
#line 233
t_s = (u_int16_t )len;
#line 233
t_cp = bp;
#line 233
tmp___2 = t_cp;
#line 233
t_cp = t_cp + 1;
#line 233
__cil_tmp19 = (int )t_s;
#line 233
__cil_tmp20 = __cil_tmp19 >> 8;
#line 233
*tmp___2 = (u_char )__cil_tmp20;
#line 233
*t_cp = (u_char )t_s;
#line 233
bp = bp + 2;
#line 233
goto while_break;
}
while_break: /* CIL Label */ ;
}
#line 234
return ((char *)bp);
}
}
#line 240 "sig-bad.c"
int ns_nameok(char const *name , int class , struct zoneinfo *zp , enum transport transport ,
enum context context , char const *owner )
{ enum severity severity ;
int ok ;
int tmp ;
int tmp___0 ;
void *__cil_tmp11 ;
unsigned long __cil_tmp12 ;
unsigned long __cil_tmp13 ;
unsigned long __cil_tmp14 ;
unsigned long __cil_tmp15 ;
unsigned int __cil_tmp16 ;
char const * __restrict __cil_tmp17 ;
int __cil_tmp18 ;
{
#line 247
severity = (enum severity )3;
#line 248
ok = 1;
{
#line 250
__cil_tmp11 = (void *)0;
#line 250
__cil_tmp12 = (unsigned long )__cil_tmp11;
#line 250
__cil_tmp13 = (unsigned long )zp;
#line 250
if (__cil_tmp13 != __cil_tmp12) {
#line 251
__cil_tmp14 = (unsigned long )zp;
#line 251
__cil_tmp15 = __cil_tmp14 + 164;
#line 251
severity = *((enum severity *)__cil_tmp15);
} else {
}
}
{
#line 261
__cil_tmp16 = (unsigned int )severity;
#line 261
if (__cil_tmp16 == 0U) {
#line 262
return (1);
} else {
}
}
{
#line 264
if ((int )context == 0) {
#line 264
goto case_0;
} else {
}
#line 267
if ((int )context == 3) {
#line 267
goto case_3;
} else {
}
#line 270
goto switch_default;
case_0: /* CIL Label */
#line 265
if (class != 1) {
#line 265
tmp___0 = 1;
} else {
{
#line 265
tmp = __res_dnok(name);
}
#line 265
if (tmp) {
#line 265
tmp___0 = 1;
} else {
#line 265
tmp___0 = 0;
}
}
#line 265
ok = tmp___0;
#line 266
goto switch_break;
case_3: /* CIL Label */
{
#line 268
ok = __res_hnok(name);
}
#line 269
goto switch_break;
switch_default: /* CIL Label */
{
#line 272
__cil_tmp17 = (char const * __restrict )"unexpected context %d in ns_nameok";
#line 272
__cil_tmp18 = (int )context;
#line 272
printf(__cil_tmp17, __cil_tmp18);
}
#line 273
return (0);
#line 276
return (ok);
switch_break: /* CIL Label */ ;
}
#line 279
return (ok);
}
}
#line 283 "sig-bad.c"
static int rrextract(u_char *msg , int msglen , u_char *rrp , u_char *dname , int namelen )
{ u_char *eom ;
u_char *cp ;
u_char *cp1 ;
u_char *rdatap ;
u_int class ;
u_int type ;
u_int dlen ;
int n ;
int len ;
u_int32_t ttl ;
u_char data[4140] ;
HEADER *hp ;
register u_char const *t_cp ;
register u_char const *t_cp___0 ;
register u_char const *t_cp___1 ;
register u_char const *t_cp___2 ;
enum context tmp ;
int tmp___0 ;
u_long origTTL ;
u_long exptime ;
u_long signtime ;
u_long timetilexp ;
u_long now ;
u_int8_t alg ;
u_int temp ;
register u_char const *t_cp___3 ;
register u_char const *t_cp___4 ;
register u_char const *t_cp___5 ;
register u_char const *t_cp___6 ;
register u_char const *t_cp___7 ;
register u_char const *t_cp___8 ;
time_t tmp___1 ;
char *tmp___2 ;
char *tmp___3 ;
size_t tmp___4 ;
char const * __restrict __cil_tmp41 ;
char const * __restrict __cil_tmp42 ;
char *__cil_tmp43 ;
char *__cil_tmp44 ;
u_char const *__cil_tmp45 ;
u_char const *__cil_tmp46 ;
u_char const *__cil_tmp47 ;
char *__cil_tmp48 ;
char const * __restrict __cil_tmp49 ;
unsigned long __cil_tmp50 ;
unsigned long __cil_tmp51 ;
char const * __restrict __cil_tmp52 ;
unsigned long __cil_tmp53 ;
unsigned long __cil_tmp54 ;
unsigned long __cil_tmp55 ;
u_char *__cil_tmp56 ;
unsigned long __cil_tmp57 ;
unsigned long __cil_tmp58 ;
unsigned long __cil_tmp59 ;
u_char const *__cil_tmp60 ;
u_char __cil_tmp61 ;
u_int16_t __cil_tmp62 ;
int __cil_tmp63 ;
u_char const *__cil_tmp64 ;
u_char __cil_tmp65 ;
u_int16_t __cil_tmp66 ;
int __cil_tmp67 ;
int __cil_tmp68 ;
int __cil_tmp69 ;
char const * __restrict __cil_tmp70 ;
u_char const *__cil_tmp71 ;
u_char __cil_tmp72 ;
u_int16_t __cil_tmp73 ;
int __cil_tmp74 ;
u_char const *__cil_tmp75 ;
u_char __cil_tmp76 ;
u_int16_t __cil_tmp77 ;
int __cil_tmp78 ;
int __cil_tmp79 ;
int __cil_tmp80 ;
int __cil_tmp81 ;
int __cil_tmp82 ;
u_int __cil_tmp83 ;
char const * __restrict __cil_tmp84 ;
unsigned long __cil_tmp85 ;
unsigned long __cil_tmp86 ;
u_char const *__cil_tmp87 ;
u_char __cil_tmp88 ;
u_int32_t __cil_tmp89 ;
u_char const *__cil_tmp90 ;
u_char __cil_tmp91 ;
u_int32_t __cil_tmp92 ;
u_int32_t __cil_tmp93 ;
u_char const *__cil_tmp94 ;
u_char __cil_tmp95 ;
u_int32_t __cil_tmp96 ;
u_int32_t __cil_tmp97 ;
u_char const *__cil_tmp98 ;
u_char __cil_tmp99 ;
u_int32_t __cil_tmp100 ;
u_int32_t __cil_tmp101 ;
unsigned int __cil_tmp102 ;
unsigned int __cil_tmp103 ;
char const * __restrict __cil_tmp104 ;
char const * __restrict __cil_tmp105 ;
u_char const *__cil_tmp106 ;
u_char __cil_tmp107 ;
u_int16_t __cil_tmp108 ;
int __cil_tmp109 ;
u_char const *__cil_tmp110 ;
u_char __cil_tmp111 ;
u_int16_t __cil_tmp112 ;
int __cil_tmp113 ;
int __cil_tmp114 ;
int __cil_tmp115 ;
char const * __restrict __cil_tmp116 ;
unsigned long __cil_tmp117 ;
u_char *__cil_tmp118 ;
unsigned long __cil_tmp119 ;
unsigned long __cil_tmp120 ;
unsigned long __cil_tmp121 ;
char const * __restrict __cil_tmp122 ;
int __cil_tmp123 ;
enum transport __cil_tmp124 ;
char *__cil_tmp125 ;
char const *__cil_tmp126 ;
int __cil_tmp127 ;
void *__cil_tmp128 ;
struct zoneinfo *__cil_tmp129 ;
enum transport __cil_tmp130 ;
char *__cil_tmp131 ;
char const *__cil_tmp132 ;
unsigned long __cil_tmp133 ;
unsigned long __cil_tmp134 ;
char const * __restrict __cil_tmp135 ;
unsigned long __cil_tmp136 ;
unsigned long __cil_tmp137 ;
char const * __restrict __cil_tmp138 ;
char const * __restrict __cil_tmp139 ;
char const * __restrict __cil_tmp140 ;
unsigned long __cil_tmp141 ;
u_char *__cil_tmp142 ;
unsigned long __cil_tmp143 ;
unsigned long __cil_tmp144 ;
unsigned long __cil_tmp145 ;
u_char const *__cil_tmp146 ;
u_char __cil_tmp147 ;
u_int16_t __cil_tmp148 ;
int __cil_tmp149 ;
u_char const *__cil_tmp150 ;
u_char __cil_tmp151 ;
u_int16_t __cil_tmp152 ;
int __cil_tmp153 ;
int __cil_tmp154 ;
int __cil_tmp155 ;
char const * __restrict __cil_tmp156 ;
u_char const *__cil_tmp157 ;
u_char __cil_tmp158 ;
u_int16_t __cil_tmp159 ;
int __cil_tmp160 ;
u_char const *__cil_tmp161 ;
u_char __cil_tmp162 ;
u_int16_t __cil_tmp163 ;
int __cil_tmp164 ;
int __cil_tmp165 ;
int __cil_tmp166 ;
char const * __restrict __cil_tmp167 ;
u_int __cil_tmp168 ;
char const * __restrict __cil_tmp169 ;
int __cil_tmp170 ;
u_char const *__cil_tmp171 ;
u_char __cil_tmp172 ;
u_int32_t __cil_tmp173 ;
u_char const *__cil_tmp174 ;
u_char __cil_tmp175 ;
u_int32_t __cil_tmp176 ;
u_int32_t __cil_tmp177 ;
u_char const *__cil_tmp178 ;
u_char __cil_tmp179 ;
u_int32_t __cil_tmp180 ;
u_int32_t __cil_tmp181 ;
u_char const *__cil_tmp182 ;
u_char __cil_tmp183 ;
u_int32_t __cil_tmp184 ;
u_int32_t __cil_tmp185 ;
unsigned int __cil_tmp186 ;
unsigned int __cil_tmp187 ;
unsigned int __cil_tmp188 ;
char const * __restrict __cil_tmp189 ;
int __cil_tmp190 ;
u_char const *__cil_tmp191 ;
u_char __cil_tmp192 ;
u_int32_t __cil_tmp193 ;
u_char const *__cil_tmp194 ;
u_char __cil_tmp195 ;
u_int32_t __cil_tmp196 ;
u_int32_t __cil_tmp197 ;
u_char const *__cil_tmp198 ;
u_char __cil_tmp199 ;
u_int32_t __cil_tmp200 ;
u_int32_t __cil_tmp201 ;
u_char const *__cil_tmp202 ;
u_char __cil_tmp203 ;
u_int32_t __cil_tmp204 ;
u_int32_t __cil_tmp205 ;
unsigned int __cil_tmp206 ;
unsigned int __cil_tmp207 ;
unsigned int __cil_tmp208 ;
char const * __restrict __cil_tmp209 ;
int __cil_tmp210 ;
u_char const *__cil_tmp211 ;
u_char __cil_tmp212 ;
u_int32_t __cil_tmp213 ;
u_char const *__cil_tmp214 ;
u_char __cil_tmp215 ;
u_int32_t __cil_tmp216 ;
u_int32_t __cil_tmp217 ;
u_char const *__cil_tmp218 ;
u_char __cil_tmp219 ;
u_int32_t __cil_tmp220 ;
u_int32_t __cil_tmp221 ;
u_char const *__cil_tmp222 ;
u_char __cil_tmp223 ;
u_int32_t __cil_tmp224 ;
u_int32_t __cil_tmp225 ;
unsigned int __cil_tmp226 ;
unsigned int __cil_tmp227 ;
unsigned int __cil_tmp228 ;
char const * __restrict __cil_tmp229 ;
int __cil_tmp230 ;
u_char const *__cil_tmp231 ;
u_char __cil_tmp232 ;
u_int16_t __cil_tmp233 ;
int __cil_tmp234 ;
u_char const *__cil_tmp235 ;
u_char __cil_tmp236 ;
u_int16_t __cil_tmp237 ;
int __cil_tmp238 ;
int __cil_tmp239 ;
int __cil_tmp240 ;
char const * __restrict __cil_tmp241 ;
void *__cil_tmp242 ;
time_t *__cil_tmp243 ;
char const * __restrict __cil_tmp244 ;
int __cil_tmp245 ;
u_long __cil_tmp246 ;
char const * __restrict __cil_tmp247 ;
char const * __restrict __cil_tmp248 ;
int __cil_tmp249 ;
u_int __cil_tmp250 ;
u_int __cil_tmp251 ;
char const * __restrict __cil_tmp252 ;
int __cil_tmp253 ;
u_int __cil_tmp254 ;
u_int __cil_tmp255 ;
u_long __cil_tmp256 ;
char const * __restrict __cil_tmp257 ;
unsigned long __cil_tmp258 ;
unsigned long __cil_tmp259 ;
unsigned long __cil_tmp260 ;
u_char *__cil_tmp261 ;
unsigned long __cil_tmp262 ;
unsigned long __cil_tmp263 ;
unsigned long __cil_tmp264 ;
void * __restrict __cil_tmp265 ;
void const * __restrict __cil_tmp266 ;
size_t __cil_tmp267 ;
char const * __restrict __cil_tmp268 ;
char const * __restrict __cil_tmp269 ;
char *__cil_tmp270 ;
char *__cil_tmp271 ;
u_char const *__cil_tmp272 ;
u_char const *__cil_tmp273 ;
u_char *__cil_tmp274 ;
u_char const *__cil_tmp275 ;
char *__cil_tmp276 ;
unsigned long __cil_tmp277 ;
int __cil_tmp278 ;
char const * __restrict __cil_tmp279 ;
char *__cil_tmp280 ;
char const * __restrict __cil_tmp281 ;
char const * __restrict __cil_tmp282 ;
unsigned long __cil_tmp283 ;
unsigned long __cil_tmp284 ;
char *__cil_tmp285 ;
char const *__cil_tmp286 ;
size_t __cil_tmp287 ;
int __cil_tmp288 ;
u_int __cil_tmp289 ;
u_int __cil_tmp290 ;
char const * __restrict __cil_tmp291 ;
char const * __restrict __cil_tmp292 ;
char const * __restrict __cil_tmp293 ;
unsigned long __cil_tmp294 ;
unsigned long __cil_tmp295 ;
u_char *__cil_tmp296 ;
int __cil_tmp297 ;
unsigned long __cil_tmp298 ;
unsigned long __cil_tmp299 ;
char const * __restrict __cil_tmp300 ;
unsigned long __cil_tmp301 ;
unsigned long __cil_tmp302 ;
u_char *__cil_tmp303 ;
int __cil_tmp304 ;
int __cil_tmp305 ;
int __cil_tmp306 ;
int __cil_tmp307 ;
unsigned long __cil_tmp308 ;
unsigned long __cil_tmp309 ;
u_char *__cil_tmp310 ;
int __cil_tmp311 ;
int __cil_tmp312 ;
int __cil_tmp313 ;
char const * __restrict __cil_tmp314 ;
unsigned long __cil_tmp315 ;
unsigned long __cil_tmp316 ;
unsigned long __cil_tmp317 ;
unsigned long __cil_tmp318 ;
unsigned long __cil_tmp319 ;
unsigned long __cil_tmp320 ;
unsigned long __cil_tmp321 ;
unsigned long __cil_tmp322 ;
char const * __restrict __cil_tmp323 ;
unsigned long __cil_tmp324 ;
unsigned long __cil_tmp325 ;
unsigned int __cil_tmp326 ;
char const * __restrict __cil_tmp327 ;
unsigned int __cil_tmp328 ;
void * __restrict __cil_tmp329 ;
void const * __restrict __cil_tmp330 ;
size_t __cil_tmp331 ;
unsigned long __cil_tmp332 ;
unsigned long __cil_tmp333 ;
u_char *__cil_tmp334 ;
unsigned long __cil_tmp335 ;
unsigned long __cil_tmp336 ;
char const * __restrict __cil_tmp337 ;
int __cil_tmp338 ;
u_int __cil_tmp339 ;
u_int __cil_tmp340 ;
unsigned long __cil_tmp341 ;
unsigned long __cil_tmp342 ;
unsigned long __cil_tmp343 ;
unsigned long __cil_tmp344 ;
int __cil_tmp345 ;
u_int __cil_tmp346 ;
char const * __restrict __cil_tmp347 ;
int __cil_tmp348 ;
u_int __cil_tmp349 ;
unsigned long __cil_tmp350 ;
unsigned long __cil_tmp351 ;
char const * __restrict __cil_tmp352 ;
unsigned long __cil_tmp353 ;
unsigned long __cil_tmp354 ;
{
{
#line 288
len = 0;
#line 291
hp = (HEADER *)msg;
#line 293
cp = rrp;
#line 294
eom = msg + msglen;
#line 296
__cil_tmp41 = (char const * __restrict )"Trying to do dn_expand..\n";
#line 296
printf(__cil_tmp41);
#line 297
__cil_tmp42 = (char const * __restrict )"msg = %s, msglen = %d, rrp = %s, namelen = %d\n";
#line 297
__cil_tmp43 = (char *)msg;
#line 297
__cil_tmp44 = (char *)rrp;
#line 297
printf(__cil_tmp42, __cil_tmp43, msglen, __cil_tmp44, namelen);
#line 299
__cil_tmp45 = (u_char const *)msg;
#line 299
__cil_tmp46 = (u_char const *)eom;
#line 299
__cil_tmp47 = (u_char const *)cp;
#line 299
__cil_tmp48 = (char *)dname;
#line 299
n = __dn_expand(__cil_tmp45, __cil_tmp46, __cil_tmp47, __cil_tmp48, namelen);
}
#line 299
if (n < 0) {
{
#line 300
__cil_tmp49 = (char const * __restrict )"dn_expand returned %d\n";
#line 300
printf(__cil_tmp49, n);
#line 301
__cil_tmp50 = (unsigned long )hp;
#line 301
__cil_tmp51 = __cil_tmp50 + 3;
#line 301
*((unsigned int *)__cil_tmp51) = 1U;
}
#line 302
return (-1);
} else {
}
{
#line 305
__cil_tmp52 = (char const * __restrict )"First dn_expand returned n = %d\n";
#line 305
printf(__cil_tmp52, n);
#line 307
cp = cp + n;
#line 308
len = len + n;
#line 309
__cil_tmp53 = (unsigned long )len;
#line 309
__cil_tmp54 = __cil_tmp53 + 12UL;
#line 309
len = (int )__cil_tmp54;
}
{
#line 311
while (1) {
while_continue: /* CIL Label */ ;
{
#line 311
__cil_tmp55 = (unsigned long )eom;
#line 311
__cil_tmp56 = cp + 10;
#line 311
__cil_tmp57 = (unsigned long )__cil_tmp56;
#line 311
if (__cil_tmp57 > __cil_tmp55) {
#line 311
__cil_tmp58 = (unsigned long )hp;
#line 311
__cil_tmp59 = __cil_tmp58 + 3;
#line 311
*((unsigned int *)__cil_tmp59) = 1U;
#line 311
return (-1);
} else {
}
}
#line 311
goto while_break;
}
while_break: /* CIL Label */ ;
}
{
#line 312
while (1) {
while_continue___0: /* CIL Label */ ;
#line 312
t_cp = (u_char const *)cp;
#line 312
__cil_tmp60 = t_cp + 1;
#line 312
__cil_tmp61 = *__cil_tmp60;
#line 312
__cil_tmp62 = (u_int16_t )__cil_tmp61;
#line 312
__cil_tmp63 = (int )__cil_tmp62;
#line 312
__cil_tmp64 = t_cp + 0;
#line 312
__cil_tmp65 = *__cil_tmp64;
#line 312
__cil_tmp66 = (u_int16_t )__cil_tmp65;
#line 312
__cil_tmp67 = (int )__cil_tmp66;
#line 312
__cil_tmp68 = __cil_tmp67 << 8;
#line 312
__cil_tmp69 = __cil_tmp68 | __cil_tmp63;
#line 312
type = (u_int )__cil_tmp69;
#line 312
cp = cp + 2;
#line 312
goto while_break___0;
}
while_break___0: /* CIL Label */ ;
}
{
#line 313
cp = cp + 2;
#line 314
len = len + 2;
#line 315
__cil_tmp70 = (char const * __restrict )"type = %d\n";
#line 315
printf(__cil_tmp70, type);
}
{
#line 316
while (1) {
while_continue___1: /* CIL Label */ ;
#line 316
t_cp___0 = (u_char const *)cp;
#line 316
__cil_tmp71 = t_cp___0 + 1;
#line 316
__cil_tmp72 = *__cil_tmp71;
#line 316
__cil_tmp73 = (u_int16_t )__cil_tmp72;
#line 316
__cil_tmp74 = (int )__cil_tmp73;
#line 316
__cil_tmp75 = t_cp___0 + 0;
#line 316
__cil_tmp76 = *__cil_tmp75;
#line 316
__cil_tmp77 = (u_int16_t )__cil_tmp76;
#line 316
__cil_tmp78 = (int )__cil_tmp77;
#line 316
__cil_tmp79 = __cil_tmp78 << 8;
#line 316
__cil_tmp80 = __cil_tmp79 | __cil_tmp74;
#line 316
class = (u_int )__cil_tmp80;
#line 316
cp = cp + 2;
#line 316
goto while_break___1;
}
while_break___1: /* CIL Label */ ;
}
#line 317
cp = cp + 2;
#line 318
len = len + 2;
{
#line 320
__cil_tmp81 = 1 << 8;
#line 320
__cil_tmp82 = __cil_tmp81 - 1;
#line 320
__cil_tmp83 = (u_int )__cil_tmp82;
#line 320
if (class > __cil_tmp83) {
{
#line 321
__cil_tmp84 = (char const * __restrict )"bad class in rrextract";
#line 321
printf(__cil_tmp84);
#line 322
__cil_tmp85 = (unsigned long )hp;
#line 322
__cil_tmp86 = __cil_tmp85 + 3;
#line 322
*((unsigned int *)__cil_tmp86) = 1U;
}
#line 323
return (-1);
} else {
}
}
{
#line 325
while (1) {
while_continue___2: /* CIL Label */ ;
#line 325
t_cp___1 = (u_char const *)cp;
#line 325
__cil_tmp87 = t_cp___1 + 3;
#line 325
__cil_tmp88 = *__cil_tmp87;
#line 325
__cil_tmp89 = (u_int32_t )__cil_tmp88;
#line 325
__cil_tmp90 = t_cp___1 + 2;
#line 325
__cil_tmp91 = *__cil_tmp90;
#line 325
__cil_tmp92 = (u_int32_t )__cil_tmp91;
#line 325
__cil_tmp93 = __cil_tmp92 << 8;
#line 325
__cil_tmp94 = t_cp___1 + 1;
#line 325
__cil_tmp95 = *__cil_tmp94;
#line 325
__cil_tmp96 = (u_int32_t )__cil_tmp95;
#line 325
__cil_tmp97 = __cil_tmp96 << 16;
#line 325
__cil_tmp98 = t_cp___1 + 0;
#line 325
__cil_tmp99 = *__cil_tmp98;
#line 325
__cil_tmp100 = (u_int32_t )__cil_tmp99;
#line 325
__cil_tmp101 = __cil_tmp100 << 24;
#line 325
__cil_tmp102 = __cil_tmp101 | __cil_tmp97;
#line 325
__cil_tmp103 = __cil_tmp102 | __cil_tmp93;
#line 325
ttl = __cil_tmp103 | __cil_tmp89;
#line 325
cp = cp + 4;
#line 325
goto while_break___2;
}
while_break___2: /* CIL Label */ ;
}
{
#line 326
__cil_tmp104 = (char const * __restrict )"ttl = %d\n";
#line 326
printf(__cil_tmp104, ttl);
#line 327
cp = cp + 4;
#line 328
len = len + 4;
}
#line 330
if (ttl > 2147483647U) {
{
#line 331
__cil_tmp105 = (char const * __restrict )"%s: converted TTL > %u to 0";
#line 331
printf(__cil_tmp105, dname, 2147483647);
#line 334
ttl = (u_int32_t )0;
}
} else {
}
{
#line 336
while (1) {
while_continue___3: /* CIL Label */ ;
#line 336
t_cp___2 = (u_char const *)cp;
#line 336
__cil_tmp106 = t_cp___2 + 1;
#line 336
__cil_tmp107 = *__cil_tmp106;
#line 336
__cil_tmp108 = (u_int16_t )__cil_tmp107;
#line 336
__cil_tmp109 = (int )__cil_tmp108;
#line 336
__cil_tmp110 = t_cp___2 + 0;
#line 336
__cil_tmp111 = *__cil_tmp110;
#line 336
__cil_tmp112 = (u_int16_t )__cil_tmp111;
#line 336
__cil_tmp113 = (int )__cil_tmp112;
#line 336
__cil_tmp114 = __cil_tmp113 << 8;
#line 336
__cil_tmp115 = __cil_tmp114 | __cil_tmp109;
#line 336
dlen = (u_int )__cil_tmp115;
#line 336
cp = cp + 2;
#line 336
goto while_break___3;
}
while_break___3: /* CIL Label */ ;
}
{
#line 337
cp = cp + 2;
#line 338
len = len + 2;
#line 340
__cil_tmp116 = (char const * __restrict )"dlen = %d\n";
#line 340
printf(__cil_tmp116, dlen);
}
{
#line 341
while (1) {
while_continue___4: /* CIL Label */ ;
{
#line 341
__cil_tmp117 = (unsigned long )eom;
#line 341
__cil_tmp118 = cp + dlen;
#line 341
__cil_tmp119 = (unsigned long )__cil_tmp118;
#line 341
if (__cil_tmp119 > __cil_tmp117) {
#line 341
__cil_tmp120 = (unsigned long )hp;
#line 341
__cil_tmp121 = __cil_tmp120 + 3;
#line 341
*((unsigned int *)__cil_tmp121) = 1U;
#line 341
return (-1);
} else {
}
}
#line 341
goto while_break___4;
}
while_break___4: /* CIL Label */ ;
}
{
#line 342
__cil_tmp122 = (char const * __restrict )"bounds check succeeded\n";
#line 342
printf(__cil_tmp122);
#line 343
rdatap = cp;
#line 345
__cil_tmp123 = (int )type;
#line 345
__cil_tmp124 = (enum transport )2;
#line 345
tmp = ns_ownercontext(__cil_tmp123, __cil_tmp124);
#line 345
__cil_tmp125 = (char *)dname;
#line 345
__cil_tmp126 = (char const *)__cil_tmp125;
#line 345
__cil_tmp127 = (int )class;
#line 345
__cil_tmp128 = (void *)0;
#line 345
__cil_tmp129 = (struct zoneinfo *)__cil_tmp128;
#line 345
__cil_tmp130 = (enum transport )2;
#line 345
__cil_tmp131 = (char *)dname;
#line 345
__cil_tmp132 = (char const *)__cil_tmp131;
#line 345
tmp___0 = ns_nameok(__cil_tmp126, __cil_tmp127, __cil_tmp129, __cil_tmp130, tmp,
__cil_tmp132);
}
#line 345
if (tmp___0) {
} else {
#line 348
__cil_tmp133 = (unsigned long )hp;
#line 348
__cil_tmp134 = __cil_tmp133 + 3;
#line 348
*((unsigned int *)__cil_tmp134) = 5U;
#line 349
return (-1);
}
{
#line 351
__cil_tmp135 = (char const * __restrict )"rrextract: dname %s type %d class %d ttl %d\n";
#line 351
printf(__cil_tmp135, dname, type, class, ttl);
}
{
#line 371
if ((int )type == 1) {
#line 371
goto case_1;
} else {
}
#line 380
if ((int )type == 35) {
#line 380
goto case_35;
} else {
}
#line 388
if ((int )type == 15) {
#line 388
goto case_15;
} else {
}
#line 389
if ((int )type == 18) {
#line 389
goto case_15;
} else {
}
#line 390
if ((int )type == 21) {
#line 390
goto case_15;
} else {
}
#line 391
if ((int )type == 33) {
#line 391
goto case_15;
} else {
}
#line 395
if ((int )type == 26) {
#line 395
goto case_26;
} else {
}
#line 399
if ((int )type == 24) {
#line 399
goto case_24;
} else {
}
#line 572
goto switch_default___0;
case_1: /* CIL Label */
#line 372
if (dlen != 4U) {
#line 373
__cil_tmp136 = (unsigned long )hp;
#line 373
__cil_tmp137 = __cil_tmp136 + 3;
#line 373
*((unsigned int *)__cil_tmp137) = 1U;
#line 374
return (-1);
} else {
}
#line 377
goto switch_break;
case_35: /* CIL Label */
{
#line 381
__cil_tmp138 = (char const * __restrict )"NOT HANDLING T_NAPTR RECORDS\n";
#line 381
printf(__cil_tmp138);
}
#line 382
goto switch_break;
case_15: /* CIL Label */
case_18: /* CIL Label */
case_21: /* CIL Label */
case_33: /* CIL Label */
{
#line 392
__cil_tmp139 = (char const * __restrict )"NOT HANDLING T_SRV RECORDS\n";
#line 392
printf(__cil_tmp139);
}
#line 393
goto switch_break;
case_26: /* CIL Label */
{
#line 396
__cil_tmp140 = (char const * __restrict )"NOT HANDLING T_PX RECORDS\n";
#line 396
printf(__cil_tmp140);
}
#line 397
goto switch_break;
case_24: /* CIL Label */
{
#line 408
while (1) {
while_continue___5: /* CIL Label */ ;
{
#line 408
__cil_tmp141 = (unsigned long )eom;
#line 408
__cil_tmp142 = cp + 16;
#line 408
__cil_tmp143 = (unsigned long )__cil_tmp142;
#line 408
if (__cil_tmp143 > __cil_tmp141) {
#line 408
__cil_tmp144 = (unsigned long )hp;
#line 408
__cil_tmp145 = __cil_tmp144 + 3;
#line 408
*((unsigned int *)__cil_tmp145) = 1U;
#line 408
return (-1);
} else {
}
}
#line 408
goto while_break___5;
}
while_break___5: /* CIL Label */ ;
}
#line 410
cp1 = cp;
{
#line 412
while (1) {
while_continue___6: /* CIL Label */ ;
#line 412
t_cp___3 = (u_char const *)cp1;
#line 412
__cil_tmp146 = t_cp___3 + 1;
#line 412
__cil_tmp147 = *__cil_tmp146;
#line 412
__cil_tmp148 = (u_int16_t )__cil_tmp147;
#line 412
__cil_tmp149 = (int )__cil_tmp148;
#line 412
__cil_tmp150 = t_cp___3 + 0;
#line 412
__cil_tmp151 = *__cil_tmp150;
#line 412
__cil_tmp152 = (u_int16_t )__cil_tmp151;
#line 412
__cil_tmp153 = (int )__cil_tmp152;
#line 412
__cil_tmp154 = __cil_tmp153 << 8;
#line 412
__cil_tmp155 = __cil_tmp154 | __cil_tmp149;
#line 412
temp = (u_int )__cil_tmp155;
#line 412
cp1 = cp1 + 2;
#line 412
goto while_break___6;
}
while_break___6: /* CIL Label */ ;
}
{
#line 413
__cil_tmp156 = (char const * __restrict )"covered type = %d\n";
#line 413
printf(__cil_tmp156, temp);
#line 414
cp1 = cp1 + 2;
#line 415
len = len + 2;
}
{
#line 417
while (1) {
while_continue___7: /* CIL Label */ ;
#line 417
t_cp___4 = (u_char const *)cp1;
#line 417
__cil_tmp157 = t_cp___4 + 1;
#line 417
__cil_tmp158 = *__cil_tmp157;
#line 417
__cil_tmp159 = (u_int16_t )__cil_tmp158;
#line 417
__cil_tmp160 = (int )__cil_tmp159;
#line 417
__cil_tmp161 = t_cp___4 + 0;
#line 417
__cil_tmp162 = *__cil_tmp161;
#line 417
__cil_tmp163 = (u_int16_t )__cil_tmp162;
#line 417
__cil_tmp164 = (int )__cil_tmp163;
#line 417
__cil_tmp165 = __cil_tmp164 << 8;
#line 417
__cil_tmp166 = __cil_tmp165 | __cil_tmp160;
#line 417
temp = (u_int )__cil_tmp166;
#line 417
cp1 = cp1 + 2;
#line 417
goto while_break___7;
}
while_break___7: /* CIL Label */ ;
}
{
#line 418
__cil_tmp167 = (char const * __restrict )" alg label = %d\n";
#line 418
printf(__cil_tmp167, temp);
#line 419
__cil_tmp168 = temp / 256U;
#line 419
alg = (u_int8_t )__cil_tmp168;
#line 420
cp1 = cp1 + 2;
#line 421
len = len + 2;
#line 423
__cil_tmp169 = (char const * __restrict )"alg = %d\n";
#line 423
__cil_tmp170 = (int )alg;
#line 423
printf(__cil_tmp169, __cil_tmp170);
}
{
#line 425
while (1) {
while_continue___8: /* CIL Label */ ;
#line 425
t_cp___5 = (u_char const *)cp1;
#line 425
__cil_tmp171 = t_cp___5 + 3;
#line 425
__cil_tmp172 = *__cil_tmp171;
#line 425
__cil_tmp173 = (u_int32_t )__cil_tmp172;
#line 425
__cil_tmp174 = t_cp___5 + 2;
#line 425
__cil_tmp175 = *__cil_tmp174;
#line 425
__cil_tmp176 = (u_int32_t )__cil_tmp175;
#line 425
__cil_tmp177 = __cil_tmp176 << 8;
#line 425
__cil_tmp178 = t_cp___5 + 1;
#line 425
__cil_tmp179 = *__cil_tmp178;
#line 425
__cil_tmp180 = (u_int32_t )__cil_tmp179;
#line 425
__cil_tmp181 = __cil_tmp180 << 16;
#line 425
__cil_tmp182 = t_cp___5 + 0;
#line 425
__cil_tmp183 = *__cil_tmp182;
#line 425
__cil_tmp184 = (u_int32_t )__cil_tmp183;
#line 425
__cil_tmp185 = __cil_tmp184 << 24;
#line 425
__cil_tmp186 = __cil_tmp185 | __cil_tmp181;
#line 425
__cil_tmp187 = __cil_tmp186 | __cil_tmp177;
#line 425
__cil_tmp188 = __cil_tmp187 | __cil_tmp173;
#line 425
origTTL = (u_long )__cil_tmp188;
#line 425
cp1 = cp1 + 4;
#line 425
goto while_break___8;
}
while_break___8: /* CIL Label */ ;
}
{
#line 426
cp1 = cp1 + 4;
#line 427
len = len + 4;
#line 429
__cil_tmp189 = (char const * __restrict )"origttl = %d\n";
#line 429
__cil_tmp190 = (int )origTTL;
#line 429
printf(__cil_tmp189, __cil_tmp190);
}
{
#line 430
while (1) {
while_continue___9: /* CIL Label */ ;
#line 430
t_cp___6 = (u_char const *)cp1;
#line 430
__cil_tmp191 = t_cp___6 + 3;
#line 430
__cil_tmp192 = *__cil_tmp191;
#line 430
__cil_tmp193 = (u_int32_t )__cil_tmp192;
#line 430
__cil_tmp194 = t_cp___6 + 2;
#line 430
__cil_tmp195 = *__cil_tmp194;
#line 430
__cil_tmp196 = (u_int32_t )__cil_tmp195;
#line 430
__cil_tmp197 = __cil_tmp196 << 8;
#line 430
__cil_tmp198 = t_cp___6 + 1;
#line 430
__cil_tmp199 = *__cil_tmp198;
#line 430
__cil_tmp200 = (u_int32_t )__cil_tmp199;
#line 430
__cil_tmp201 = __cil_tmp200 << 16;
#line 430
__cil_tmp202 = t_cp___6 + 0;
#line 430
__cil_tmp203 = *__cil_tmp202;
#line 430
__cil_tmp204 = (u_int32_t )__cil_tmp203;
#line 430
__cil_tmp205 = __cil_tmp204 << 24;
#line 430
__cil_tmp206 = __cil_tmp205 | __cil_tmp201;
#line 430
__cil_tmp207 = __cil_tmp206 | __cil_tmp197;
#line 430
__cil_tmp208 = __cil_tmp207 | __cil_tmp193;
#line 430
exptime = (u_long )__cil_tmp208;
#line 430
cp1 = cp1 + 4;
#line 430
goto while_break___9;
}
while_break___9: /* CIL Label */ ;
}
{
#line 431
__cil_tmp209 = (char const * __restrict )"Exptime = %d\n";
#line 431
__cil_tmp210 = (int )exptime;
#line 431
printf(__cil_tmp209, __cil_tmp210);
#line 432
cp1 = cp1 + 4;
#line 433
len = len + 4;
}
{
#line 435
while (1) {
while_continue___10: /* CIL Label */ ;
#line 435
t_cp___7 = (u_char const *)cp1;
#line 435
__cil_tmp211 = t_cp___7 + 3;
#line 435
__cil_tmp212 = *__cil_tmp211;
#line 435
__cil_tmp213 = (u_int32_t )__cil_tmp212;
#line 435
__cil_tmp214 = t_cp___7 + 2;
#line 435
__cil_tmp215 = *__cil_tmp214;
#line 435
__cil_tmp216 = (u_int32_t )__cil_tmp215;
#line 435
__cil_tmp217 = __cil_tmp216 << 8;
#line 435
__cil_tmp218 = t_cp___7 + 1;
#line 435
__cil_tmp219 = *__cil_tmp218;
#line 435
__cil_tmp220 = (u_int32_t )__cil_tmp219;
#line 435
__cil_tmp221 = __cil_tmp220 << 16;
#line 435
__cil_tmp222 = t_cp___7 + 0;
#line 435
__cil_tmp223 = *__cil_tmp222;
#line 435
__cil_tmp224 = (u_int32_t )__cil_tmp223;
#line 435
__cil_tmp225 = __cil_tmp224 << 24;
#line 435
__cil_tmp226 = __cil_tmp225 | __cil_tmp221;
#line 435
__cil_tmp227 = __cil_tmp226 | __cil_tmp217;
#line 435
__cil_tmp228 = __cil_tmp227 | __cil_tmp213;
#line 435
signtime = (u_long )__cil_tmp228;
#line 435
cp1 = cp1 + 4;
#line 435
goto while_break___10;
}
while_break___10: /* CIL Label */ ;
}
{
#line 436
__cil_tmp229 = (char const * __restrict )"Sign time = %d\n";
#line 436
__cil_tmp230 = (int )signtime;
#line 436
printf(__cil_tmp229, __cil_tmp230);
#line 437
cp1 = cp1 + 4;
#line 438
len = len + 4;
}
{
#line 440
while (1) {
while_continue___11: /* CIL Label */ ;
#line 440
t_cp___8 = (u_char const *)cp1;
#line 440
__cil_tmp231 = t_cp___8 + 1;
#line 440
__cil_tmp232 = *__cil_tmp231;
#line 440
__cil_tmp233 = (u_int16_t )__cil_tmp232;
#line 440
__cil_tmp234 = (int )__cil_tmp233;
#line 440
__cil_tmp235 = t_cp___8 + 0;
#line 440
__cil_tmp236 = *__cil_tmp235;
#line 440
__cil_tmp237 = (u_int16_t )__cil_tmp236;
#line 440
__cil_tmp238 = (int )__cil_tmp237;
#line 440
__cil_tmp239 = __cil_tmp238 << 8;
#line 440
__cil_tmp240 = __cil_tmp239 | __cil_tmp234;
#line 440
temp = (u_int )__cil_tmp240;
#line 440
cp1 = cp1 + 2;
#line 440
goto while_break___11;
}
while_break___11: /* CIL Label */ ;
}
{
#line 441
__cil_tmp241 = (char const * __restrict )"random footprint = %d\n";
#line 441
printf(__cil_tmp241, temp);
#line 442
cp1 = cp1 + 2;
#line 443
len = len + 2;
#line 445
__cil_tmp242 = (void *)0;
#line 445
__cil_tmp243 = (time_t *)__cil_tmp242;
#line 445
tmp___1 = time(__cil_tmp243);
#line 445
now = (u_long )tmp___1;
#line 447
__cil_tmp244 = (char const * __restrict )"now = %d\n";
#line 447
__cil_tmp245 = (int )now;
#line 447
printf(__cil_tmp244, __cil_tmp245);
}
{
#line 449
__cil_tmp246 = (u_long )ttl;
#line 449
if (__cil_tmp246 > origTTL) {
{
#line 450
__cil_tmp247 = (char const * __restrict )"shrinking SIG TTL";
#line 450
printf(__cil_tmp247);
#line 452
ttl = (u_int32_t )origTTL;
}
} else {
}
}
#line 456
if (signtime > now) {
{
#line 457
tmp___2 = __p_secstodate(signtime);
#line 457
__cil_tmp248 = (char const * __restrict )"ignoring SIG: signature date %s is in the future";
#line 457
printf(__cil_tmp248, tmp___2);
}
{
#line 458
__cil_tmp249 = cp - rrp;
#line 458
__cil_tmp250 = (u_int )__cil_tmp249;
#line 458
__cil_tmp251 = __cil_tmp250 + dlen;
#line 458
return ((int )__cil_tmp251);
}
} else {
}
#line 462
if (exptime <= now) {
{
#line 463
tmp___3 = __p_secstodate(exptime);
#line 463
__cil_tmp252 = (char const * __restrict )"ignoring SIG: expiration %s is in the past";
#line 463
printf(__cil_tmp252, tmp___3);
}
{
#line 465
__cil_tmp253 = cp - rrp;
#line 465
__cil_tmp254 = (u_int )__cil_tmp253;
#line 465
__cil_tmp255 = __cil_tmp254 + dlen;
#line 465
return ((int )__cil_tmp255);
}
} else {
}
#line 469
timetilexp = exptime - now;
{
#line 470
__cil_tmp256 = (u_long )ttl;
#line 470
if (timetilexp < __cil_tmp256) {
{
#line 471
__cil_tmp257 = (char const * __restrict )"shrinking expiring SIG TTL";
#line 471
printf(__cil_tmp257);
#line 473
ttl = (u_int32_t )timetilexp;
}
} else {
}
}
#line 476
cp = cp1 - 18;
#line 479
__cil_tmp258 = 0 * 1UL;
#line 479
__cil_tmp259 = (unsigned long )(data) + __cil_tmp258;
#line 479
cp1 = (u_char *)__cil_tmp259;
{
#line 483
while (1) {
while_continue___12: /* CIL Label */ ;
{
#line 483
__cil_tmp260 = (unsigned long )eom;
#line 483
__cil_tmp261 = cp + 18;
#line 483
__cil_tmp262 = (unsigned long )__cil_tmp261;
#line 483
if (__cil_tmp262 > __cil_tmp260) {
#line 483
__cil_tmp263 = (unsigned long )hp;
#line 483
__cil_tmp264 = __cil_tmp263 + 3;
#line 483
*((unsigned int *)__cil_tmp264) = 1U;
#line 483
return (-1);
} else {
}
}
#line 483
goto while_break___12;
}
while_break___12: /* CIL Label */ ;
}
{
#line 484
__cil_tmp265 = (void * __restrict )cp1;
#line 484
__cil_tmp266 = (void const * __restrict )cp;
#line 484
__cil_tmp267 = (size_t )18;
#line 484
memcpy(__cil_tmp265, __cil_tmp266, __cil_tmp267);
#line 486
cp1 = cp1 + 18;
#line 489
__cil_tmp268 = (char const * __restrict )"sizeof data = %d\n";
#line 489
printf(__cil_tmp268, 4140UL);
#line 490
__cil_tmp269 = (char const * __restrict )"comp name = %s\n";
#line 490
__cil_tmp270 = (char *)cp;
#line 490
__cil_tmp271 = __cil_tmp270 + 18;
#line 490
printf(__cil_tmp269, __cil_tmp271);
#line 492
__cil_tmp272 = (u_char const *)msg;
#line 492
__cil_tmp273 = (u_char const *)eom;
#line 492
__cil_tmp274 = cp + 18;
#line 492
__cil_tmp275 = (u_char const *)__cil_tmp274;
#line 492
__cil_tmp276 = (char *)cp1;
#line 492
__cil_tmp277 = 4140UL - 18UL;
#line 492
__cil_tmp278 = (int )__cil_tmp277;
#line 492
n = __dn_expand(__cil_tmp272, __cil_tmp273, __cil_tmp275, __cil_tmp276, __cil_tmp278);
#line 496
__cil_tmp279 = (char const * __restrict )"dn_expand returned: %d, expanded name = %s\n";
#line 496
__cil_tmp280 = (char *)cp1;
#line 496
printf(__cil_tmp279, n, __cil_tmp280);
}
#line 498
if (n < 0) {
{
#line 499
__cil_tmp281 = (char const * __restrict )"ERROR: n = %d < 0!\n";
#line 499
printf(__cil_tmp281, n);
#line 500
__cil_tmp282 = (char const * __restrict )"EXITING RREXTRACT!\n";
#line 500
printf(__cil_tmp282);
#line 501
__cil_tmp283 = (unsigned long )hp;
#line 501
__cil_tmp284 = __cil_tmp283 + 3;
#line 501
*((unsigned int *)__cil_tmp284) = 1U;
}
#line 502
return (-1);
} else {
}
{
#line 504
cp = cp + n;
#line 505
__cil_tmp285 = (char *)cp1;
#line 505
__cil_tmp286 = (char const *)__cil_tmp285;
#line 505
tmp___4 = strlen(__cil_tmp286);
#line 505
__cil_tmp287 = tmp___4 + 1UL;
#line 505
cp1 = cp1 + __cil_tmp287;
#line 509
__cil_tmp288 = 18 + n;
#line 509
__cil_tmp289 = (u_int )__cil_tmp288;
#line 509
__cil_tmp290 = dlen - __cil_tmp289;
#line 509
n = (int )__cil_tmp290;
#line 511
__cil_tmp291 = (char const * __restrict )"dlen - NS_SIG_SIGNER - n = %d\n";
#line 511
printf(__cil_tmp291, n);
#line 526
__cil_tmp292 = (char const * __restrict )"n=%d\n";
#line 526
printf(__cil_tmp292, n);
#line 527
__cil_tmp293 = (char const * __restrict )"(sizeof data) - (cp1 - (u_char *)data) = %d\n";
#line 527
__cil_tmp294 = 0 * 1UL;
#line 527
__cil_tmp295 = (unsigned long )(data) + __cil_tmp294;
#line 527
__cil_tmp296 = (u_char *)__cil_tmp295;
#line 527
__cil_tmp297 = cp1 - __cil_tmp296;
#line 527
__cil_tmp298 = (unsigned long )__cil_tmp297;
#line 527
__cil_tmp299 = 4140UL - __cil_tmp298;
#line 527
printf(__cil_tmp293, __cil_tmp299);
#line 528
__cil_tmp300 = (char const * __restrict )"(n > (int) (sizeof data) - (cp1 - (u_char *)data)) = %d\n";
#line 528
__cil_tmp301 = 0 * 1UL;
#line 528
__cil_tmp302 = (unsigned long )(data) + __cil_tmp301;
#line 528
__cil_tmp303 = (u_char *)__cil_tmp302;
#line 528
__cil_tmp304 = cp1 - __cil_tmp303;
#line 528
__cil_tmp305 = (int )4140UL;
#line 528
__cil_tmp306 = __cil_tmp305 - __cil_tmp304;
#line 528
__cil_tmp307 = n > __cil_tmp306;
#line 528
printf(__cil_tmp300, __cil_tmp307);
}
{
#line 532
__cil_tmp308 = 0 * 1UL;
#line 532
__cil_tmp309 = (unsigned long )(data) + __cil_tmp308;
#line 532
__cil_tmp310 = (u_char *)__cil_tmp309;
#line 532
__cil_tmp311 = cp1 - __cil_tmp310;
#line 532
__cil_tmp312 = (int )4140UL;
#line 532
__cil_tmp313 = __cil_tmp312 - __cil_tmp311;
#line 532
if (n > __cil_tmp313) {
{
#line 533
__cil_tmp314 = (char const * __restrict )"NO ROOM\n";
#line 533
printf(__cil_tmp314);
#line 534
__cil_tmp315 = (unsigned long )hp;
#line 534
__cil_tmp316 = __cil_tmp315 + 3;
#line 534
*((unsigned int *)__cil_tmp316) = 1U;
}
#line 535
return (-1);
} else {
}
}
{
#line 539
if ((int )alg == 1) {
#line 539
goto case_1___0;
} else {
}
#line 545
if ((int )alg == 3) {
#line 545
goto case_3;
} else {
}
#line 550
goto switch_default;
case_1___0: /* CIL Label */
#line 541
if (n < 64) {
#line 542
__cil_tmp317 = (unsigned long )hp;
#line 542
__cil_tmp318 = __cil_tmp317 + 3;
#line 542
*((unsigned int *)__cil_tmp318) = 1U;
} else
#line 541
if (n > 512) {
#line 542
__cil_tmp319 = (unsigned long )hp;
#line 542
__cil_tmp320 = __cil_tmp319 + 3;
#line 542
*((unsigned int *)__cil_tmp320) = 1U;
} else {
}
#line 543
goto switch_break___0;
case_3: /* CIL Label */
#line 546
if (n != 41) {
#line 547
__cil_tmp321 = (unsigned long )hp;
#line 547
__cil_tmp322 = __cil_tmp321 + 3;
#line 547
*((unsigned int *)__cil_tmp322) = 1U;
} else {
}
#line 548
goto switch_break___0;
switch_default: /* CIL Label */
{
#line 551
__cil_tmp323 = (char const * __restrict )"DEFAULT ALG!\n";
#line 551
printf(__cil_tmp323);
}
#line 552
goto switch_break___0;
switch_break___0: /* CIL Label */ ;
}
{
#line 555
__cil_tmp324 = (unsigned long )hp;
#line 555
__cil_tmp325 = __cil_tmp324 + 3;
#line 555
__cil_tmp326 = *((unsigned int *)__cil_tmp325);
#line 555
if (__cil_tmp326 == 1U) {
#line 556
return (-1);
} else {
}
}
{
#line 558
__cil_tmp327 = (char const * __restrict )"memcpying n=%u bytes \n";
#line 558
__cil_tmp328 = (unsigned int )n;
#line 558
printf(__cil_tmp327, __cil_tmp328);
}
{
#line 562
__cil_tmp329 = (void * __restrict )cp1;
#line 562
__cil_tmp330 = (void const * __restrict )cp;
#line 562
__cil_tmp331 = (size_t )n;
#line 562
memcpy(__cil_tmp329, __cil_tmp330, __cil_tmp331);
#line 563
cp = cp + n;
#line 564
cp1 = cp1 + n;
#line 567
__cil_tmp332 = 0 * 1UL;
#line 567
__cil_tmp333 = (unsigned long )(data) + __cil_tmp332;
#line 567
__cil_tmp334 = (u_char *)__cil_tmp333;
#line 567
n = cp1 - __cil_tmp334;
#line 568
__cil_tmp335 = 0 * 1UL;
#line 568
__cil_tmp336 = (unsigned long )(data) + __cil_tmp335;
#line 568
cp1 = (u_char *)__cil_tmp336;
}
#line 569
goto switch_break;
switch_default___0: /* CIL Label */
{
#line 573
__cil_tmp337 = (char const * __restrict )"unknown type %d";
#line 573
printf(__cil_tmp337, type);
}
{
#line 574
__cil_tmp338 = cp - rrp;
#line 574
__cil_tmp339 = (u_int )__cil_tmp338;
#line 574
__cil_tmp340 = __cil_tmp339 + dlen;
#line 574
return ((int )__cil_tmp340);
}
switch_break: /* CIL Label */ ;
}
{
#line 577
__cil_tmp341 = (unsigned long )eom;
#line 577
__cil_tmp342 = (unsigned long )cp;
#line 577
if (__cil_tmp342 > __cil_tmp341) {
#line 578
__cil_tmp343 = (unsigned long )hp;
#line 578
__cil_tmp344 = __cil_tmp343 + 3;
#line 578
*((unsigned int *)__cil_tmp344) = 1U;
#line 579
return (-1);
} else {
}
}
{
#line 581
__cil_tmp345 = cp - rdatap;
#line 581
__cil_tmp346 = (u_int )__cil_tmp345;
#line 581
if (__cil_tmp346 != dlen) {
{
#line 583
__cil_tmp347 = (char const * __restrict )"encoded rdata length is %u, but actual length was %u";
#line 583
__cil_tmp348 = cp - rdatap;
#line 583
__cil_tmp349 = (u_int )__cil_tmp348;
#line 583
printf(__cil_tmp347, dlen, __cil_tmp349);
#line 585
__cil_tmp350 = (unsigned long )hp;
#line 585
__cil_tmp351 = __cil_tmp350 + 3;
#line 585
*((unsigned int *)__cil_tmp351) = 1U;
}
#line 587
return (-1);
} else {
}
}
#line 589
if (n > 2070) {
{
#line 590
__cil_tmp352 = (char const * __restrict )"update type %d: %d bytes is too much data";
#line 590
printf(__cil_tmp352, type, n);
#line 593
__cil_tmp353 = (unsigned long )hp;
#line 593
__cil_tmp354 = __cil_tmp353 + 3;
#line 593
*((unsigned int *)__cil_tmp354) = 1U;
}
#line 594
return (-1);
} else {
}
#line 600
return (cp - rrp);
}
}
#line 608 "sig-bad.c"
int createSig(u_char *buf )
{ u_char *p ;
char *temp ;
char *temp1 ;
u_char *comp_dn ;
u_char *comp_dn2 ;
char exp_dn[200] ;
char exp_dn2[200] ;
u_char **dnptrs ;
u_char **lastdnptr ;
u_char **dnptrs2 ;
int i ;
int len ;
int comp_size ;
u_long now ;
void *tmp ;
void *tmp___0 ;
void *tmp___1 ;
void *tmp___2 ;
void *tmp___3 ;
size_t tmp___4 ;
u_char *tmp___5 ;
char *tmp___6 ;
u_char **tmp___7 ;
u_char **tmp___8 ;
size_t tmp___9 ;
u_char *tmp___10 ;
u_char *tmp___11 ;
register u_int16_t t_s ;
register u_char *t_cp ;
u_char *tmp___12 ;
register u_int16_t t_s___0 ;
register u_char *t_cp___0 ;
u_char *tmp___13 ;
register u_int32_t t_l ;
register u_char *t_cp___1 ;
u_char *tmp___14 ;
u_char *tmp___15 ;
u_char *tmp___16 ;
register u_int16_t t_s___1 ;
register u_char *t_cp___2 ;
u_char *tmp___17 ;
register u_int16_t t_s___2 ;
register u_char *t_cp___3 ;
u_char *tmp___18 ;
register u_int16_t t_s___3 ;
register u_char *t_cp___4 ;
u_char *tmp___19 ;
register u_int32_t t_l___0 ;
register u_char *t_cp___5 ;
u_char *tmp___20 ;
u_char *tmp___21 ;
u_char *tmp___22 ;
time_t tmp___23 ;
register u_int32_t t_l___1 ;
register u_char *t_cp___6 ;
u_char *tmp___24 ;
u_char *tmp___25 ;
u_char *tmp___26 ;
register u_int32_t t_l___2 ;
register u_char *t_cp___7 ;
u_char *tmp___27 ;
u_char *tmp___28 ;
u_char *tmp___29 ;
register u_int16_t t_s___4 ;
register u_char *t_cp___8 ;
u_char *tmp___30 ;
u_char **tmp___31 ;
u_char **tmp___32 ;
size_t tmp___33 ;
u_char *tmp___34 ;
u_char *tmp___35 ;
register u_int32_t t_l___3 ;
register u_char *t_cp___9 ;
u_char *tmp___36 ;
u_char *tmp___37 ;
u_char *tmp___38 ;
unsigned long __cil_tmp78 ;
unsigned long __cil_tmp79 ;
unsigned long __cil_tmp80 ;
unsigned long __cil_tmp81 ;
unsigned long __cil_tmp82 ;
char * __restrict __cil_tmp83 ;
char const * __restrict __cil_tmp84 ;
char const *__cil_tmp85 ;
size_t __cil_tmp86 ;
size_t __cil_tmp87 ;
char __cil_tmp88 ;
int __cil_tmp89 ;
char __cil_tmp90 ;
unsigned long __cil_tmp91 ;
unsigned long __cil_tmp92 ;
char *__cil_tmp93 ;
char * __restrict __cil_tmp94 ;
char const * __restrict __cil_tmp95 ;
unsigned long __cil_tmp96 ;
unsigned long __cil_tmp97 ;
char *__cil_tmp98 ;
void *__cil_tmp99 ;
void *__cil_tmp100 ;
char const * __restrict __cil_tmp101 ;
unsigned long __cil_tmp102 ;
unsigned long __cil_tmp103 ;
char *__cil_tmp104 ;
char const *__cil_tmp105 ;
unsigned long __cil_tmp106 ;
unsigned long __cil_tmp107 ;
char *__cil_tmp108 ;
char const *__cil_tmp109 ;
char const * __restrict __cil_tmp110 ;
char const * __restrict __cil_tmp111 ;
char const * __restrict __cil_tmp112 ;
unsigned long __cil_tmp113 ;
unsigned long __cil_tmp114 ;
char *__cil_tmp115 ;
char *__cil_tmp116 ;
int __cil_tmp117 ;
int __cil_tmp118 ;
int __cil_tmp119 ;
int __cil_tmp120 ;
u_int32_t __cil_tmp121 ;
u_int32_t __cil_tmp122 ;
u_int32_t __cil_tmp123 ;
int __cil_tmp124 ;
int __cil_tmp125 ;
int __cil_tmp126 ;
int __cil_tmp127 ;
int __cil_tmp128 ;
int __cil_tmp129 ;
u_int32_t __cil_tmp130 ;
u_int32_t __cil_tmp131 ;
u_int32_t __cil_tmp132 ;
void *__cil_tmp133 ;
time_t *__cil_tmp134 ;
char const * __restrict __cil_tmp135 ;
u_long __cil_tmp136 ;
u_int32_t __cil_tmp137 ;
u_int32_t __cil_tmp138 ;
u_int32_t __cil_tmp139 ;
u_int32_t __cil_tmp140 ;
u_int32_t __cil_tmp141 ;
u_int32_t __cil_tmp142 ;
int __cil_tmp143 ;
int __cil_tmp144 ;
unsigned long __cil_tmp145 ;
unsigned long __cil_tmp146 ;
char *__cil_tmp147 ;
char * __restrict __cil_tmp148 ;
char const * __restrict __cil_tmp149 ;
unsigned long __cil_tmp150 ;
unsigned long __cil_tmp151 ;
char *__cil_tmp152 ;
void *__cil_tmp153 ;
void *__cil_tmp154 ;
char const * __restrict __cil_tmp155 ;
unsigned long __cil_tmp156 ;
unsigned long __cil_tmp157 ;
char *__cil_tmp158 ;
char const *__cil_tmp159 ;
unsigned long __cil_tmp160 ;
unsigned long __cil_tmp161 ;
char *__cil_tmp162 ;
char const *__cil_tmp163 ;
char const * __restrict __cil_tmp164 ;
char const * __restrict __cil_tmp165 ;
char const * __restrict __cil_tmp166 ;
unsigned long __cil_tmp167 ;
unsigned long __cil_tmp168 ;
char *__cil_tmp169 ;
char *__cil_tmp170 ;
u_int32_t __cil_tmp171 ;
u_int32_t __cil_tmp172 ;
u_int32_t __cil_tmp173 ;
{
{
#line 614
len = 0;
#line 618
__cil_tmp78 = 2UL * 8UL;
#line 618
tmp = malloc(__cil_tmp78);
#line 618
dnptrs = (unsigned char **)tmp;
#line 619
__cil_tmp79 = 2UL * 8UL;
#line 619
tmp___0 = malloc(__cil_tmp79);
#line 619
dnptrs2 = (unsigned char **)tmp___0;
#line 621
__cil_tmp80 = 200UL * 1UL;
#line 621
tmp___1 = malloc(__cil_tmp80);
#line 621
comp_dn = (unsigned char *)tmp___1;
#line 622
__cil_tmp81 = 200UL * 1UL;
#line 622
tmp___2 = malloc(__cil_tmp81);
#line 622
comp_dn2 = (unsigned char *)tmp___2;
#line 624
__cil_tmp82 = 400UL * 1UL;
#line 624
tmp___3 = malloc(__cil_tmp82);
#line 624
temp1 = (char *)tmp___3;
#line 626
temp = temp1;
#line 628
p = buf;
#line 630
__cil_tmp83 = (char * __restrict )temp;
#line 630
__cil_tmp84 = (char const * __restrict )"HEADER JUNK:";
#line 630
strcpy(__cil_tmp83, __cil_tmp84);
#line 632
__cil_tmp85 = (char const *)temp;
#line 632
tmp___4 = strlen(__cil_tmp85);
#line 632
__cil_tmp86 = (size_t )len;
#line 632
__cil_tmp87 = __cil_tmp86 + tmp___4;
#line 632
len = (int )__cil_tmp87;
}
{
#line 634
while (1) {
while_continue: /* CIL Label */ ;
{
#line 634
__cil_tmp88 = *temp;
#line 634
__cil_tmp89 = (int )__cil_tmp88;
#line 634
if (__cil_tmp89 != 0) {
} else {
#line 634
goto while_break;
}
}
#line 635
tmp___5 = p;
#line 635
p = p + 1;
#line 635
tmp___6 = temp;
#line 635
temp = temp + 1;
#line 635
__cil_tmp90 = *tmp___6;
#line 635
*tmp___5 = (u_char )__cil_tmp90;
}
while_break: /* CIL Label */ ;
}
{
#line 637
__cil_tmp91 = 0 * 1UL;
#line 637
__cil_tmp92 = (unsigned long )(exp_dn) + __cil_tmp91;
#line 637
__cil_tmp93 = (char *)__cil_tmp92;
#line 637
__cil_tmp94 = (char * __restrict )__cil_tmp93;
#line 637
__cil_tmp95 = (char const * __restrict )"lcs.mit.edu";
#line 637
strcpy(__cil_tmp94, __cil_tmp95);
#line 639
tmp___7 = dnptrs;
#line 639
dnptrs = dnptrs + 1;
#line 639
__cil_tmp96 = 0 * 1UL;
#line 639
__cil_tmp97 = (unsigned long )(exp_dn) + __cil_tmp96;
#line 639
__cil_tmp98 = (char *)__cil_tmp97;
#line 639
*tmp___7 = (u_char *)__cil_tmp98;
#line 640
tmp___8 = dnptrs;
#line 640
dnptrs = dnptrs - 1;
#line 640
__cil_tmp99 = (void *)0;
#line 640
*tmp___8 = (u_char *)__cil_tmp99;
#line 642
__cil_tmp100 = (void *)0;
#line 642
lastdnptr = (u_char **)__cil_tmp100;
#line 644
__cil_tmp101 = (char const * __restrict )"Calling dn_comp..\n";
#line 644
printf(__cil_tmp101);
#line 645
__cil_tmp102 = 0 * 1UL;
#line 645
__cil_tmp103 = (unsigned long )(exp_dn) + __cil_tmp102;
#line 645
__cil_tmp104 = (char *)__cil_tmp103;
#line 645
__cil_tmp105 = (char const *)__cil_tmp104;
#line 645
comp_size = __dn_comp(__cil_tmp105, comp_dn, 200, dnptrs, lastdnptr);
#line 646
__cil_tmp106 = 0 * 1UL;
#line 646
__cil_tmp107 = (unsigned long )(exp_dn) + __cil_tmp106;
#line 646
__cil_tmp108 = (char *)__cil_tmp107;
#line 646
__cil_tmp109 = (char const *)__cil_tmp108;
#line 646
tmp___9 = strlen(__cil_tmp109);
#line 646
__cil_tmp110 = (char const * __restrict )"uncomp_size = %d\n";
#line 646
printf(__cil_tmp110, tmp___9);
#line 647
__cil_tmp111 = (char const * __restrict )"comp_size = %d\n";
#line 647
printf(__cil_tmp111, comp_size);
#line 648
__cil_tmp112 = (char const * __restrict )"exp_dn = %s, comp_dn = %s\n";
#line 648
__cil_tmp113 = 0 * 1UL;
#line 648
__cil_tmp114 = (unsigned long )(exp_dn) + __cil_tmp113;
#line 648
__cil_tmp115 = (char *)__cil_tmp114;
#line 648
__cil_tmp116 = (char *)comp_dn;
#line 648
printf(__cil_tmp112, __cil_tmp115, __cil_tmp116);
#line 650
i = 0;
}
{
#line 650
while (1) {
while_continue___0: /* CIL Label */ ;
#line 650
if (i < comp_size) {
} else {
#line 650
goto while_break___0;
}
#line 651
tmp___10 = p;
#line 651
p = p + 1;
#line 651
tmp___11 = comp_dn;
#line 651
comp_dn = comp_dn + 1;
#line 651
*tmp___10 = *tmp___11;
#line 650
i = i + 1;
}
while_break___0: /* CIL Label */ ;
}
#line 653
len = len + comp_size;
{
#line 655
while (1) {
while_continue___1: /* CIL Label */ ;
#line 655
t_s = (u_int16_t )24;
#line 655
t_cp = p;
#line 655
tmp___12 = t_cp;
#line 655
t_cp = t_cp + 1;
#line 655
__cil_tmp117 = (int )t_s;
#line 655
__cil_tmp118 = __cil_tmp117 >> 8;
#line 655
*tmp___12 = (u_char )__cil_tmp118;
#line 655
*t_cp = (u_char )t_s;
#line 655
p = p + 2;
#line 655
goto while_break___1;
}
while_break___1: /* CIL Label */ ;
}
#line 656
p = p + 2;
{
#line 658
while (1) {
while_continue___2: /* CIL Label */ ;
#line 658
t_s___0 = (u_int16_t )1;
#line 658
t_cp___0 = p;
#line 658
tmp___13 = t_cp___0;
#line 658
t_cp___0 = t_cp___0 + 1;
#line 658
__cil_tmp119 = (int )t_s___0;
#line 658
__cil_tmp120 = __cil_tmp119 >> 8;
#line 658
*tmp___13 = (u_char )__cil_tmp120;
#line 658
*t_cp___0 = (u_char )t_s___0;
#line 658
p = p + 2;
#line 658
goto while_break___2;
}
while_break___2: /* CIL Label */ ;
}
#line 659
p = p + 2;
{
#line 661
while (1) {
while_continue___3: /* CIL Label */ ;
#line 661
t_l = (u_int32_t )255;
#line 661
t_cp___1 = p;
#line 661
tmp___14 = t_cp___1;
#line 661
t_cp___1 = t_cp___1 + 1;
#line 661
__cil_tmp121 = t_l >> 24;
#line 661
*tmp___14 = (u_char )__cil_tmp121;
#line 661
tmp___15 = t_cp___1;
#line 661
t_cp___1 = t_cp___1 + 1;
#line 661
__cil_tmp122 = t_l >> 16;
#line 661
*tmp___15 = (u_char )__cil_tmp122;
#line 661
tmp___16 = t_cp___1;
#line 661
t_cp___1 = t_cp___1 + 1;
#line 661
__cil_tmp123 = t_l >> 8;
#line 661
*tmp___16 = (u_char )__cil_tmp123;
#line 661
*t_cp___1 = (u_char )t_l;
#line 661
p = p + 4;
#line 661
goto while_break___3;
}
while_break___3: /* CIL Label */ ;
}
#line 662
p = p + 4;
{
#line 664
while (1) {
while_continue___4: /* CIL Label */ ;
#line 664
t_s___1 = (u_int16_t )30;
#line 664
t_cp___2 = p;
#line 664
tmp___17 = t_cp___2;
#line 664
t_cp___2 = t_cp___2 + 1;
#line 664
__cil_tmp124 = (int )t_s___1;
#line 664
__cil_tmp125 = __cil_tmp124 >> 8;
#line 664
*tmp___17 = (u_char )__cil_tmp125;
#line 664
*t_cp___2 = (u_char )t_s___1;
#line 664
p = p + 2;
#line 664
goto while_break___4;
}
while_break___4: /* CIL Label */ ;
}
#line 667
p = p + 2;
#line 669
len = len + 10;
{
#line 671
while (1) {
while_continue___5: /* CIL Label */ ;
#line 671
t_s___2 = (u_int16_t )15;
#line 671
t_cp___3 = p;
#line 671
tmp___18 = t_cp___3;
#line 671
t_cp___3 = t_cp___3 + 1;
#line 671
__cil_tmp126 = (int )t_s___2;
#line 671
__cil_tmp127 = __cil_tmp126 >> 8;
#line 671
*tmp___18 = (u_char )__cil_tmp127;
#line 671
*t_cp___3 = (u_char )t_s___2;
#line 671
p = p + 2;
#line 671
goto while_break___5;
}
while_break___5: /* CIL Label */ ;
}
#line 672
p = p + 2;
{
#line 674
while (1) {
while_continue___6: /* CIL Label */ ;
#line 674
t_s___3 = (u_int16_t )512;
#line 674
t_cp___4 = p;
#line 674
tmp___19 = t_cp___4;
#line 674
t_cp___4 = t_cp___4 + 1;
#line 674
__cil_tmp128 = (int )t_s___3;
#line 674
__cil_tmp129 = __cil_tmp128 >> 8;
#line 674
*tmp___19 = (u_char )__cil_tmp129;
#line 674
*t_cp___4 = (u_char )t_s___3;
#line 674
p = p + 2;
#line 674
goto while_break___6;
}
while_break___6: /* CIL Label */ ;
}
#line 675
p = p + 2;
{
#line 677
while (1) {
while_continue___7: /* CIL Label */ ;
#line 677
t_l___0 = (u_int32_t )255;
#line 677
t_cp___5 = p;
#line 677
tmp___20 = t_cp___5;
#line 677
t_cp___5 = t_cp___5 + 1;
#line 677
__cil_tmp130 = t_l___0 >> 24;
#line 677
*tmp___20 = (u_char )__cil_tmp130;
#line 677
tmp___21 = t_cp___5;
#line 677
t_cp___5 = t_cp___5 + 1;
#line 677
__cil_tmp131 = t_l___0 >> 16;
#line 677
*tmp___21 = (u_char )__cil_tmp131;
#line 677
tmp___22 = t_cp___5;
#line 677
t_cp___5 = t_cp___5 + 1;
#line 677
__cil_tmp132 = t_l___0 >> 8;
#line 677
*tmp___22 = (u_char )__cil_tmp132;
#line 677
*t_cp___5 = (u_char )t_l___0;
#line 677
p = p + 4;
#line 677
goto while_break___7;
}
while_break___7: /* CIL Label */ ;
}
{
#line 678
p = p + 4;
#line 680
__cil_tmp133 = (void *)0;
#line 680
__cil_tmp134 = (time_t *)__cil_tmp133;
#line 680
tmp___23 = time(__cil_tmp134);
#line 680
now = (u_long )tmp___23;
#line 682
__cil_tmp135 = (char const * __restrict )"Signing at = %d\n";
#line 682
printf(__cil_tmp135, now);
}
{
#line 683
while (1) {
while_continue___8: /* CIL Label */ ;
#line 683
__cil_tmp136 = now + 20000UL;
#line 683
t_l___1 = (u_int32_t )__cil_tmp136;
#line 683
t_cp___6 = p;
#line 683
tmp___24 = t_cp___6;
#line 683
t_cp___6 = t_cp___6 + 1;
#line 683
__cil_tmp137 = t_l___1 >> 24;
#line 683
*tmp___24 = (u_char )__cil_tmp137;
#line 683
tmp___25 = t_cp___6;
#line 683
t_cp___6 = t_cp___6 + 1;
#line 683
__cil_tmp138 = t_l___1 >> 16;
#line 683
*tmp___25 = (u_char )__cil_tmp138;
#line 683
tmp___26 = t_cp___6;
#line 683
t_cp___6 = t_cp___6 + 1;
#line 683
__cil_tmp139 = t_l___1 >> 8;
#line 683
*tmp___26 = (u_char )__cil_tmp139;
#line 683
*t_cp___6 = (u_char )t_l___1;
#line 683
p = p + 4;
#line 683
goto while_break___8;
}
while_break___8: /* CIL Label */ ;
}
#line 684
p = p + 4;
{
#line 685
while (1) {
while_continue___9: /* CIL Label */ ;
#line 685
t_l___2 = (u_int32_t )now;
#line 685
t_cp___7 = p;
#line 685
tmp___27 = t_cp___7;
#line 685
t_cp___7 = t_cp___7 + 1;
#line 685
__cil_tmp140 = t_l___2 >> 24;
#line 685
*tmp___27 = (u_char )__cil_tmp140;
#line 685
tmp___28 = t_cp___7;
#line 685
t_cp___7 = t_cp___7 + 1;
#line 685
__cil_tmp141 = t_l___2 >> 16;
#line 685
*tmp___28 = (u_char )__cil_tmp141;
#line 685
tmp___29 = t_cp___7;
#line 685
t_cp___7 = t_cp___7 + 1;
#line 685
__cil_tmp142 = t_l___2 >> 8;
#line 685
*tmp___29 = (u_char )__cil_tmp142;
#line 685
*t_cp___7 = (u_char )t_l___2;
#line 685
p = p + 4;
#line 685
goto while_break___9;
}
while_break___9: /* CIL Label */ ;
}
#line 686
p = p + 4;
{
#line 688
while (1) {
while_continue___10: /* CIL Label */ ;
#line 688
t_s___4 = (u_int16_t )100;
#line 688
t_cp___8 = p;
#line 688
tmp___30 = t_cp___8;
#line 688
t_cp___8 = t_cp___8 + 1;
#line 688
__cil_tmp143 = (int )t_s___4;
#line 688
__cil_tmp144 = __cil_tmp143 >> 8;
#line 688
*tmp___30 = (u_char )__cil_tmp144;
#line 688
*t_cp___8 = (u_char )t_s___4;
#line 688
p = p + 2;
#line 688
goto while_break___10;
}
while_break___10: /* CIL Label */ ;
}
{
#line 689
p = p + 2;
#line 691
len = len + 18;
#line 693
__cil_tmp145 = 0 * 1UL;
#line 693
__cil_tmp146 = (unsigned long )(exp_dn2) + __cil_tmp145;
#line 693
__cil_tmp147 = (char *)__cil_tmp146;
#line 693
__cil_tmp148 = (char * __restrict )__cil_tmp147;
#line 693
__cil_tmp149 = (char const * __restrict )"sls.lcs.mit.edu";
#line 693
strcpy(__cil_tmp148, __cil_tmp149);
#line 695
tmp___31 = dnptrs2;
#line 695
dnptrs2 = dnptrs2 + 1;
#line 695
__cil_tmp150 = 0 * 1UL;
#line 695
__cil_tmp151 = (unsigned long )(exp_dn2) + __cil_tmp150;
#line 695
__cil_tmp152 = (char *)__cil_tmp151;
#line 695
*tmp___31 = (u_char *)__cil_tmp152;
#line 696
tmp___32 = dnptrs2;
#line 696
dnptrs2 = dnptrs2 - 1;
#line 696
__cil_tmp153 = (void *)0;
#line 696
*tmp___32 = (u_char *)__cil_tmp153;
#line 697
__cil_tmp154 = (void *)0;
#line 697
lastdnptr = (u_char **)__cil_tmp154;
#line 699
__cil_tmp155 = (char const * __restrict )"Calling dn_comp..\n";
#line 699
printf(__cil_tmp155);
#line 700
__cil_tmp156 = 0 * 1UL;
#line 700
__cil_tmp157 = (unsigned long )(exp_dn2) + __cil_tmp156;
#line 700
__cil_tmp158 = (char *)__cil_tmp157;
#line 700
__cil_tmp159 = (char const *)__cil_tmp158;
#line 700
comp_size = __dn_comp(__cil_tmp159, comp_dn2, 200, dnptrs2, lastdnptr);
#line 701
__cil_tmp160 = 0 * 1UL;
#line 701
__cil_tmp161 = (unsigned long )(exp_dn2) + __cil_tmp160;
#line 701
__cil_tmp162 = (char *)__cil_tmp161;
#line 701
__cil_tmp163 = (char const *)__cil_tmp162;
#line 701
tmp___33 = strlen(__cil_tmp163);
#line 701
__cil_tmp164 = (char const * __restrict )"uncomp_size = %d\n";
#line 701
printf(__cil_tmp164, tmp___33);
#line 702
__cil_tmp165 = (char const * __restrict )"comp_size = %d\n";
#line 702
printf(__cil_tmp165, comp_size);
#line 703
__cil_tmp166 = (char const * __restrict )"exp_dn2 = %s, comp_dn2 = %s\n";
#line 703
__cil_tmp167 = 0 * 1UL;
#line 703
__cil_tmp168 = (unsigned long )(exp_dn2) + __cil_tmp167;
#line 703
__cil_tmp169 = (char *)__cil_tmp168;
#line 703
__cil_tmp170 = (char *)comp_dn2;
#line 703
printf(__cil_tmp166, __cil_tmp169, __cil_tmp170);
#line 705
len = len + comp_size;
#line 707
i = 0;
}
{
#line 707
while (1) {
while_continue___11: /* CIL Label */ ;
#line 707
if (i < comp_size) {
} else {
#line 707
goto while_break___11;
}
#line 708
tmp___34 = p;
#line 708
p = p + 1;
#line 708
tmp___35 = comp_dn2;
#line 708
comp_dn2 = comp_dn2 + 1;
#line 708
*tmp___34 = *tmp___35;
#line 707
i = i + 1;
}
while_break___11: /* CIL Label */ ;
}
#line 710
i = 0;
{
#line 710
while (1) {
while_continue___12: /* CIL Label */ ;
#line 710
if (i < 11) {
} else {
#line 710
goto while_break___12;
}
{
#line 712
while (1) {
while_continue___13: /* CIL Label */ ;
#line 712
t_l___3 = (u_int32_t )123;
#line 712
t_cp___9 = p;
#line 712
tmp___36 = t_cp___9;
#line 712
t_cp___9 = t_cp___9 + 1;
#line 712
__cil_tmp171 = t_l___3 >> 24;
#line 712
*tmp___36 = (u_char )__cil_tmp171;
#line 712
tmp___37 = t_cp___9;
#line 712
t_cp___9 = t_cp___9 + 1;
#line 712
__cil_tmp172 = t_l___3 >> 16;
#line 712
*tmp___37 = (u_char )__cil_tmp172;
#line 712
tmp___38 = t_cp___9;
#line 712
t_cp___9 = t_cp___9 + 1;
#line 712
__cil_tmp173 = t_l___3 >> 8;
#line 712
*tmp___38 = (u_char )__cil_tmp173;
#line 712
*t_cp___9 = (u_char )t_l___3;
#line 712
p = p + 4;
#line 712
goto while_break___13;
}
while_break___13: /* CIL Label */ ;
}
#line 713
p = p + 4;
#line 714
len = len + 4;
#line 710
i = i + 1;
}
while_break___12: /* CIL Label */ ;
}
#line 717
return (p - buf);
}
}
#line 722 "sig-bad.c"
int main(void)
{ int msglen ;
int ret ;
u_char *dp ;
u_char *name ;
void *tmp ;
u_char *msg ;
void *tmp___0 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
char const * __restrict __cil_tmp10 ;
char const * __restrict __cil_tmp11 ;
char const * __restrict __cil_tmp12 ;
{
{
#line 726
__cil_tmp8 = 100UL * 1UL;
#line 726
tmp = malloc(__cil_tmp8);
#line 726
name = (u_char *)tmp;
#line 727
__cil_tmp9 = 1000UL * 1UL;
#line 727
tmp___0 = malloc(__cil_tmp9);
#line 727
msg = (u_char *)tmp___0;
#line 730
msglen = createSig(msg);
#line 731
__cil_tmp10 = (char const * __restrict )"msglen = %d\n";
#line 731
printf(__cil_tmp10, msglen);
#line 733
dp = msg + 12UL;
#line 735
__cil_tmp11 = (char const * __restrict )"Calling rrextract!\n";
#line 735
printf(__cil_tmp11);
#line 737
__res_init();
#line 738
ret = rrextract(msg, msglen, dp, name, 100);
#line 740
__cil_tmp12 = (char const * __restrict )"rrextract returned %d\n";
#line 740
printf(__cil_tmp12, ret);
}
#line 742
return (0);
}
}
|
the_stack_data/14742.c | #include<stdio.h>
void main()
{
int a,b,s ;
s = 0;
printf("\n\n To Check If Two Numbers Are Amicable Numbers Or Not \n\n");
printf(" Enter Number 1 : ");
scanf("%d",&a);
printf(" Enter Number 2 : ");
scanf("%d",&b);
for(int i = 1; i < a ; i++)
{
if( a % i == 0) s += i;
}
if(s == b)printf("\n\n The Numbers Are Amicable Numbers \n\n");
else printf("\n\n The Numbers Are Not Amicable Numbers \n\n");
} |
the_stack_data/89200681.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <search.h>
#include <errno.h>
#include <inttypes.h>
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define BIG_ENDIAN_HOST
#endif
#if defined (_WIN32) || defined (_WIN64)
typedef unsigned int lsearch_cnt_t;
#else
typedef size_t lsearch_cnt_t;
#endif
#pragma pack(1)
/**
* Name........: cap2hccapx.c
* Autor.......: Jens Steube <[email protected]>, Philipp "philsmd" Schmidt <[email protected]>
* License.....: MIT
*/
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
// from pcap.h
#define TCPDUMP_MAGIC 0xa1b2c3d4
#define TCPDUMP_CIGAM 0xd4c3b2a1
#define TCPDUMP_DECODE_LEN 65535
#define DLT_NULL 0 /* BSD loopback encapsulation */
#define DLT_EN10MB 1 /* Ethernet (10Mb) */
#define DLT_EN3MB 2 /* Experimental Ethernet (3Mb) */
#define DLT_AX25 3 /* Amateur Radio AX.25 */
#define DLT_PRONET 4 /* Proteon ProNET Token Ring */
#define DLT_CHAOS 5 /* Chaos */
#define DLT_IEEE802 6 /* IEEE 802 Networks */
#define DLT_ARCNET 7 /* ARCNET, with BSD-style header */
#define DLT_SLIP 8 /* Serial Line IP */
#define DLT_PPP 9 /* Point-to-point Protocol */
#define DLT_FDDI 10 /* FDDI */
#define DLT_RAW 12 /* Raw headers (no link layer) */
#define DLT_RAW2 14
#define DLT_RAW3 101
#define DLT_IEEE802_11 105 /* IEEE 802.11 wireless */
#define DLT_IEEE802_11_PRISM 119
#define DLT_IEEE802_11_RADIO 127
#define DLT_IEEE802_11_PPI_HDR 192
struct pcap_file_header {
u32 magic;
u16 version_major;
u16 version_minor;
u32 thiszone; /* gmt to local correction */
u32 sigfigs; /* accuracy of timestamps */
u32 snaplen; /* max length saved portion of each pkt */
u32 linktype; /* data link type (LINKTYPE_*) */
};
struct pcap_pkthdr {
u32 tv_sec; /* timestamp seconds */
u32 tv_usec; /* timestamp microseconds */
u32 caplen; /* length of portion present */
u32 len; /* length this packet (off wire) */
};
typedef struct pcap_file_header pcap_file_header_t;
typedef struct pcap_pkthdr pcap_pkthdr_t;
// from linux/ieee80211.h
struct ieee80211_hdr_3addr {
u16 frame_control;
u16 duration_id;
u8 addr1[6];
u8 addr2[6];
u8 addr3[6];
u16 seq_ctrl;
} __attribute__((packed));
struct ieee80211_qos_hdr {
u16 frame_control;
u16 duration_id;
u8 addr1[6];
u8 addr2[6];
u8 addr3[6];
u16 seq_ctrl;
u16 qos_ctrl;
} __attribute__((packed));
typedef struct ieee80211_hdr_3addr ieee80211_hdr_3addr_t;
typedef struct ieee80211_qos_hdr ieee80211_qos_hdr_t;
struct ieee80211_llc_snap_header
{
/* LLC part: */
u8 dsap; /**< Destination SAP ID */
u8 ssap; /**< Source SAP ID */
u8 ctrl; /**< Control information */
/* SNAP part: */
u8 oui[3]; /**< Organization code, usually 0 */
u16 ethertype; /**< Ethernet Type field */
} __attribute__((packed));
typedef struct ieee80211_llc_snap_header ieee80211_llc_snap_header_t;
#define IEEE80211_FCTL_FTYPE 0x000c
#define IEEE80211_FCTL_STYPE 0x00f0
#define IEEE80211_FCTL_TODS 0x0100
#define IEEE80211_FCTL_FROMDS 0x0200
#define IEEE80211_FTYPE_MGMT 0x0000
#define IEEE80211_FTYPE_DATA 0x0008
#define IEEE80211_STYPE_ASSOC_REQ 0x0000
#define IEEE80211_STYPE_ASSOC_RESP 0x0010
#define IEEE80211_STYPE_REASSOC_REQ 0x0020
#define IEEE80211_STYPE_REASSOC_RESP 0x0030
#define IEEE80211_STYPE_PROBE_REQ 0x0040
#define IEEE80211_STYPE_PROBE_RESP 0x0050
#define IEEE80211_STYPE_BEACON 0x0080
#define IEEE80211_STYPE_QOS_DATA 0x0080
#define IEEE80211_STYPE_ATIM 0x0090
#define IEEE80211_STYPE_DISASSOC 0x00A0
#define IEEE80211_STYPE_AUTH 0x00B0
#define IEEE80211_STYPE_DEAUTH 0x00C0
#define IEEE80211_STYPE_ACTION 0x00D0
#define IEEE80211_LLC_DSAP 0xAA
#define IEEE80211_LLC_SSAP 0xAA
#define IEEE80211_LLC_CTRL 0x03
#define IEEE80211_DOT1X_AUTHENTICATION 0x8E88
/* Management Frame Information Element Types */
#define MFIE_TYPE_SSID 0
#define MFIE_TYPE_RATES 1
#define MFIE_TYPE_FH_SET 2
#define MFIE_TYPE_DS_SET 3
#define MFIE_TYPE_CF_SET 4
#define MFIE_TYPE_TIM 5
#define MFIE_TYPE_IBSS_SET 6
#define MFIE_TYPE_CHALLENGE 16
#define MFIE_TYPE_ERP 42
#define MFIE_TYPE_RSN 48
#define MFIE_TYPE_RATES_EX 50
#define MFIE_TYPE_GENERIC 221
// from ks7010/eap_packet.h
#define WBIT(n) (1 << (n))
#define WPA_KEY_INFO_TYPE_MASK (WBIT(0) | WBIT(1) | WBIT(2))
#define WPA_KEY_INFO_TYPE_HMAC_MD5_RC4 WBIT(0)
#define WPA_KEY_INFO_TYPE_HMAC_SHA1_AES WBIT(1)
#define WPA_KEY_INFO_KEY_TYPE WBIT(3) /* 1 = Pairwise, 0 = Group key */
#define WPA_KEY_INFO_KEY_INDEX_MASK (WBIT(4) | WBIT(5))
#define WPA_KEY_INFO_KEY_INDEX_SHIFT 4
#define WPA_KEY_INFO_INSTALL WBIT(6) /* pairwise */
#define WPA_KEY_INFO_TXRX WBIT(6) /* group */
#define WPA_KEY_INFO_ACK WBIT(7)
#define WPA_KEY_INFO_MIC WBIT(8)
#define WPA_KEY_INFO_SECURE WBIT(9)
#define WPA_KEY_INFO_ERROR WBIT(10)
#define WPA_KEY_INFO_REQUEST WBIT(11)
#define WPA_KEY_INFO_ENCR_KEY_DATA WBIT(12) /* IEEE 802.11i/RSN only */
// radiotap header from http://www.radiotap.org/
struct ieee80211_radiotap_header
{
u8 it_version; /* set to 0 */
u8 it_pad;
u16 it_len; /* entire length */
u32 it_present; /* fields present */
} __attribute__((packed));
typedef struct ieee80211_radiotap_header ieee80211_radiotap_header_t;
// prism header
#define WLAN_DEVNAMELEN_MAX 16
struct prism_item
{
u32 did;
u16 status;
u16 len;
u32 data;
} __attribute__((packed));
struct prism_header
{
u32 msgcode;
u32 msglen;
char devname[WLAN_DEVNAMELEN_MAX];
struct prism_item hosttime;
struct prism_item mactime;
struct prism_item channel;
struct prism_item rssi;
struct prism_item sq;
struct prism_item signal;
struct prism_item noise;
struct prism_item rate;
struct prism_item istx;
struct prism_item frmlen;
} __attribute__((packed));
typedef struct prism_item prism_item_t;
typedef struct prism_header prism_header_t;
/* CACE PPI headers */
struct ppi_packet_header
{
uint8_t pph_version;
uint8_t pph_flags;
uint16_t pph_len;
uint32_t pph_dlt;
} __attribute__((packed));
typedef struct ppi_packet_header ppi_packet_header_t;
struct ppi_field_header
{
uint16_t pfh_datatype;
uint16_t pfh_datalen;
} __attribute__((__packed__));
typedef struct ppi_field_header ppi_field_header_t;
#define PPI_FIELD_11COMMON 2
#define PPI_FIELD_11NMAC 3
#define PPI_FIELD_11NMACPHY 4
#define PPI_FIELD_SPECMAP 5
#define PPI_FIELD_PROCINFO 6
#define PPI_FIELD_CAPINFO 7
// own structs
struct beaconinfo
{
u64 beacon_timestamp;
u16 beacon_interval;
u16 beacon_capabilities;
} __attribute__((packed));
typedef struct beaconinfo beacon_t;
struct associationreqf
{
u16 client_capabilities;
u16 client_listeninterval;
} __attribute__((packed));
typedef struct associationreqf assocreq_t;
struct reassociationreqf
{
u16 client_capabilities;
u16 client_listeninterval;
u8 addr[6];
} __attribute__((packed));
typedef struct reassociationreqf reassocreq_t;
struct auth_packet
{
u8 version;
u8 type;
u16 length;
u8 key_descriptor;
u16 key_information;
u16 key_length;
u64 replay_counter;
u8 wpa_key_nonce[32];
u8 wpa_key_iv[16];
u8 wpa_key_rsc[8];
u8 wpa_key_id[8];
u8 wpa_key_mic[16];
u16 wpa_key_data_length;
} __attribute__((packed));
typedef struct auth_packet auth_packet_t;
#define MAX_ESSID_LEN 32
typedef enum
{
ESSID_SOURCE_USER = 1,
ESSID_SOURCE_REASSOC = 2,
ESSID_SOURCE_ASSOC = 3,
ESSID_SOURCE_PROBE = 4,
ESSID_SOURCE_DIRECTED_PROBE = 5,
ESSID_SOURCE_BEACON = 6,
} essid_source_t;
typedef struct
{
u8 bssid[6];
char essid[MAX_ESSID_LEN + 4];
int essid_len;
int essid_source;
} essid_t;
#define EAPOL_TTL 1
#define TEST_REPLAYCOUNT 0
typedef enum
{
EXC_PKT_NUM_1 = 1,
EXC_PKT_NUM_2 = 2,
EXC_PKT_NUM_3 = 3,
EXC_PKT_NUM_4 = 4,
} exc_pkt_num_t;
typedef enum
{
MESSAGE_PAIR_M12E2 = 0,
MESSAGE_PAIR_M14E4 = 1,
MESSAGE_PAIR_M32E2 = 2,
MESSAGE_PAIR_M32E3 = 3,
MESSAGE_PAIR_M34E3 = 4,
MESSAGE_PAIR_M34E4 = 5,
} message_pair_t;
#define BROADCAST_MAC "\xff\xff\xff\xff\xff\xff"
typedef struct
{
int excpkt_num;
u32 tv_sec;
u32 tv_usec;
u64 replay_counter;
u8 mac_ap[6];
u8 mac_sta[6];
u8 nonce[32];
u16 eapol_len;
u8 eapol[256];
u8 keyver;
u8 keymic[16];
} excpkt_t;
// databases
#define DB_ESSID_MAX 50000
#define DB_EXCPKT_MAX 100000
essid_t *essids = NULL;
lsearch_cnt_t essids_cnt = 0;
excpkt_t *excpkts = NULL;
lsearch_cnt_t excpkts_cnt = 0;
// output
#define HCCAPX_VERSION 4
#define HCCAPX_SIGNATURE 0x58504348 // HCPX
struct hccapx
{
u32 signature;
u32 version;
u8 message_pair;
u8 essid_len;
u8 essid[32];
u8 keyver;
u8 keymic[16];
u8 mac_ap[6];
u8 nonce_ap[32];
u8 mac_sta[6];
u8 nonce_sta[32];
u16 eapol_len;
u8 eapol[256];
} __attribute__((packed));
typedef struct hccapx hccapx_t;
// functions
static u8 hex_convert (const u8 c)
{
return (c & 15) + (c >> 6) * 9;
}
static u8 hex_to_u8 (const u8 hex[2])
{
u8 v = 0;
v |= ((u8) hex_convert (hex[1]) << 0);
v |= ((u8) hex_convert (hex[0]) << 4);
return (v);
}
static u16 byte_swap_16 (const u16 n)
{
return (n & 0xff00) >> 8
| (n & 0x00ff) << 8;
}
static u32 byte_swap_32 (const u32 n)
{
return (n & 0xff000000) >> 24
| (n & 0x00ff0000) >> 8
| (n & 0x0000ff00) << 8
| (n & 0x000000ff) << 24;
}
static u64 byte_swap_64 (const u64 n)
{
return (n & 0xff00000000000000ULL) >> 56
| (n & 0x00ff000000000000ULL) >> 40
| (n & 0x0000ff0000000000ULL) >> 24
| (n & 0x000000ff00000000ULL) >> 8
| (n & 0x00000000ff000000ULL) << 8
| (n & 0x0000000000ff0000ULL) << 24
| (n & 0x000000000000ff00ULL) << 40
| (n & 0x00000000000000ffULL) << 56;
}
int comp_excpkt (const void *p1, const void *p2)
{
excpkt_t *e1 = (excpkt_t *) p1;
excpkt_t *e2 = (excpkt_t *) p2;
const int excpkt_diff = e1->excpkt_num - e2->excpkt_num;
if (excpkt_diff != 0) return excpkt_diff;
const int rc_nonce = memcmp (e1->nonce, e2->nonce, 32);
if (rc_nonce != 0) return rc_nonce;
const int rc_mac_ap = memcmp (e1->mac_ap, e2->mac_ap, 6);
if (rc_mac_ap != 0) return rc_mac_ap;
const int rc_mac_sta = memcmp (e1->mac_sta, e2->mac_sta, 6);
if (rc_mac_sta != 0) return rc_mac_sta;
if (e1->replay_counter < e2->replay_counter) return 1;
if (e1->replay_counter > e2->replay_counter) return -1;
return 0;
}
int comp_bssid (const void *p1, const void *p2)
{
essid_t *e1 = (essid_t *) p1;
essid_t *e2 = (essid_t *) p2;
return memcmp (e1->bssid, e2->bssid, 6);
}
static void db_excpkt_add (excpkt_t *excpkt, const u32 tv_sec, const u32 tv_usec, const u8 mac_ap[6], const u8 mac_sta[6])
{
if (essids_cnt == DB_EXCPKT_MAX)
{
fprintf (stderr, "Too many excpkt in dumpfile, aborting...\n");
exit (-1);
}
excpkt->tv_sec = tv_sec;
excpkt->tv_usec = tv_usec;
memcpy (excpkt->mac_ap, mac_ap, 6);
memcpy (excpkt->mac_sta, mac_sta, 6);
lsearch (excpkt, excpkts, &excpkts_cnt, sizeof (excpkt_t), comp_excpkt);
}
static void db_essid_add (essid_t *essid, const u8 addr3[6], const int essid_source)
{
if (essids_cnt == DB_ESSID_MAX)
{
fprintf (stderr, "Too many essid in dumpfile, aborting...\n");
exit (-1);
}
if (essid->essid_len == 0) return;
if (essid->essid[0] == 0) return;
memcpy (essid->bssid, addr3, 6);
void *ptr = lfind (essid, essids, &essids_cnt, sizeof (essid_t), comp_bssid);
if (ptr == NULL)
{
essid->essid_source = essid_source;
lsearch (essid, essids, &essids_cnt, sizeof (essid_t), comp_bssid);
}
else
{
essid_t *essid_old = (essid_t *) ptr;
if (essid_source > essid_old->essid_source)
{
memcpy (essid_old, essid, sizeof (essid_t));
essid_old->essid_source = essid_source;
}
}
}
static int handle_llc (const ieee80211_llc_snap_header_t *ieee80211_llc_snap_header)
{
if (ieee80211_llc_snap_header->dsap != IEEE80211_LLC_DSAP) return -1;
if (ieee80211_llc_snap_header->ssap != IEEE80211_LLC_SSAP) return -1;
if (ieee80211_llc_snap_header->ctrl != IEEE80211_LLC_CTRL) return -1;
if (ieee80211_llc_snap_header->ethertype != IEEE80211_DOT1X_AUTHENTICATION) return -1;
return 0;
}
static int handle_auth (const auth_packet_t *auth_packet, const int pkt_offset, const int pkt_size, excpkt_t *excpkt)
{
const u16 ap_length = byte_swap_16 (auth_packet->length);
const u16 ap_key_information = byte_swap_16 (auth_packet->key_information);
const u64 ap_replay_counter = byte_swap_64 (auth_packet->replay_counter);
const u16 ap_wpa_key_data_length = byte_swap_16 (auth_packet->wpa_key_data_length);
if (ap_length == 0) return -1;
// determine handshake exchange number
int excpkt_num = 0;
if (ap_key_information & WPA_KEY_INFO_ACK)
{
if (ap_key_information & WPA_KEY_INFO_INSTALL)
{
excpkt_num = EXC_PKT_NUM_3;
}
else
{
excpkt_num = EXC_PKT_NUM_1;
}
}
else
{
if (ap_key_information & WPA_KEY_INFO_SECURE)
{
excpkt_num = EXC_PKT_NUM_4;
}
else
{
excpkt_num = EXC_PKT_NUM_2;
}
}
// we're only interested in packets carrying a nonce
char zero[32] = { 0 };
if (memcmp (auth_packet->wpa_key_nonce, zero, 32) == 0) return -1;
// copy data
memcpy (excpkt->nonce, auth_packet->wpa_key_nonce, 32);
excpkt->replay_counter = ap_replay_counter;
excpkt->excpkt_num = excpkt_num;
excpkt->eapol_len = sizeof (auth_packet_t) + ap_wpa_key_data_length;
if ((pkt_offset + excpkt->eapol_len) > pkt_size) return -1;
if ((sizeof (auth_packet_t) + ap_wpa_key_data_length) > sizeof (excpkt->eapol)) return -1;
// we need to copy the auth_packet_t but have to clear the keymic
auth_packet_t auth_packet_orig;
memcpy (&auth_packet_orig, auth_packet, sizeof (auth_packet_t));
#ifdef BIG_ENDIAN_HOST
auth_packet_orig.length = byte_swap_16 (auth_packet_orig.length);
auth_packet_orig.key_information = byte_swap_16 (auth_packet_orig.key_information);
auth_packet_orig.key_length = byte_swap_16 (auth_packet_orig.key_length);
auth_packet_orig.replay_counter = byte_swap_64 (auth_packet_orig.replay_counter);
auth_packet_orig.wpa_key_data_length = byte_swap_16 (auth_packet_orig.wpa_key_data_length);
#endif
memset (auth_packet_orig.wpa_key_mic, 0, 16);
memcpy (excpkt->eapol, &auth_packet_orig, sizeof (auth_packet_t));
memcpy (excpkt->eapol + sizeof (auth_packet_t), auth_packet + 1, ap_wpa_key_data_length);
memcpy (excpkt->keymic, auth_packet->wpa_key_mic, 16);
excpkt->keyver = ap_key_information & WPA_KEY_INFO_TYPE_MASK;
if ((excpkt_num == EXC_PKT_NUM_3) || (excpkt_num == EXC_PKT_NUM_4))
{
excpkt->replay_counter--;
}
return 0;
}
static int get_essid_from_user (char *s, essid_t *essid)
{
char *man_essid = s;
char *man_bssid = strchr (man_essid, ':');
if (man_bssid == NULL)
{
fprintf (stderr, "Invalid format (%s), should be: MyESSID:d110391a58ac\n", s);
return -1;
}
*man_bssid = 0;
man_bssid++;
if (strlen (man_essid) >= 32)
{
fprintf (stderr, "Invalid format (%s), essid is too long\n", s);
return -1;
}
if (strlen (man_bssid) != 12)
{
fprintf (stderr, "Invalid format (%s), bssid must have length 12\n", s);
return -1;
}
strncpy (essid->essid, man_essid, 32);
essid->essid_len = strlen (essid->essid);
u8 bssid[6];
bssid[0] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[1] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[2] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[3] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[4] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[5] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
db_essid_add (essid, bssid, ESSID_SOURCE_USER);
return 0;
}
static int get_essid_from_tag (const u8 *packet, const pcap_pkthdr_t *header, u32 length_skip, essid_t *essid)
{
if (length_skip > header->caplen) return -1;
u32 length = header->caplen - length_skip;
const u8 *beacon = packet + length_skip;
const u8 *cur = beacon;
const u8 *end = beacon + length;
while (cur < end)
{
if ((cur + 2) >= end) break;
u8 tagtype = *cur++;
u8 taglen = *cur++;
if ((cur + taglen) >= end) break;
if (tagtype == MFIE_TYPE_SSID)
{
if (taglen < MAX_ESSID_LEN)
{
memcpy (essid->essid, cur, taglen);
essid->essid_len = taglen;
return 0;
}
}
cur += taglen;
}
return -1;
}
static void process_packet (const u8 *packet, const pcap_pkthdr_t *header)
{
if (header->caplen < sizeof (ieee80211_hdr_3addr_t)) return;
// our first header: ieee80211
ieee80211_hdr_3addr_t *ieee80211_hdr_3addr = (ieee80211_hdr_3addr_t *) packet;
#ifdef BIG_ENDIAN_HOST
ieee80211_hdr_3addr->frame_control = byte_swap_16 (ieee80211_hdr_3addr->frame_control);
ieee80211_hdr_3addr->duration_id = byte_swap_16 (ieee80211_hdr_3addr->duration_id);
ieee80211_hdr_3addr->seq_ctrl = byte_swap_16 (ieee80211_hdr_3addr->seq_ctrl);
#endif
const u16 frame_control = ieee80211_hdr_3addr->frame_control;
if ((frame_control & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_MGMT)
{
if (memcmp (ieee80211_hdr_3addr->addr3, BROADCAST_MAC, 6) == 0) return;
essid_t essid;
memset (&essid, 0, sizeof (essid_t));
const int stype = frame_control & IEEE80211_FCTL_STYPE;
if (stype == IEEE80211_STYPE_BEACON)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t) + sizeof (beacon_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_BEACON);
}
else if (stype == IEEE80211_STYPE_PROBE_REQ)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_PROBE);
}
else if (stype == IEEE80211_STYPE_PROBE_RESP)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t) + sizeof (beacon_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_PROBE);
}
else if (stype == IEEE80211_STYPE_ASSOC_REQ)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t) + sizeof (assocreq_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_ASSOC);
}
else if (stype == IEEE80211_STYPE_REASSOC_REQ)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t) + sizeof (reassocreq_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_REASSOC);
}
}
else if ((frame_control & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_DATA)
{
// process header: ieee80211
int addr4_exist = ((frame_control & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==
(IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS));
// find offset to llc/snap header
int llc_offset;
if ((frame_control & IEEE80211_FCTL_STYPE) == IEEE80211_STYPE_QOS_DATA)
{
llc_offset = sizeof (ieee80211_qos_hdr_t);
}
else
{
llc_offset = sizeof (ieee80211_hdr_3addr_t);
}
// process header: the llc/snap header
if (header->caplen < (llc_offset + sizeof (ieee80211_llc_snap_header_t))) return;
if (addr4_exist) llc_offset += 6;
ieee80211_llc_snap_header_t *ieee80211_llc_snap_header = (ieee80211_llc_snap_header_t *) &packet[llc_offset];
#ifdef BIG_ENDIAN_HOST
ieee80211_llc_snap_header->ethertype = byte_swap_16 (ieee80211_llc_snap_header->ethertype);
#endif
const int rc_llc = handle_llc (ieee80211_llc_snap_header);
if (rc_llc == -1) return;
// process header: the auth header
const int auth_offset = llc_offset + sizeof (ieee80211_llc_snap_header_t);
if (header->caplen < (auth_offset + sizeof (auth_packet_t))) return;
auth_packet_t *auth_packet = (auth_packet_t *) &packet[auth_offset];
#ifdef BIG_ENDIAN_HOST
auth_packet->length = byte_swap_16 (auth_packet->length);
auth_packet->key_information = byte_swap_16 (auth_packet->key_information);
auth_packet->key_length = byte_swap_16 (auth_packet->key_length);
auth_packet->replay_counter = byte_swap_64 (auth_packet->replay_counter);
auth_packet->wpa_key_data_length = byte_swap_16 (auth_packet->wpa_key_data_length);
#endif
excpkt_t excpkt;
memset (&excpkt, 0, sizeof (excpkt_t));
const int rc_auth = handle_auth (auth_packet, auth_offset, header->caplen, &excpkt);
if (rc_auth == -1) return;
if ((excpkt.excpkt_num == EXC_PKT_NUM_1) || (excpkt.excpkt_num == EXC_PKT_NUM_3))
{
db_excpkt_add (&excpkt, header->tv_sec, header->tv_usec, ieee80211_hdr_3addr->addr2, ieee80211_hdr_3addr->addr1);
}
else if ((excpkt.excpkt_num == EXC_PKT_NUM_2) || (excpkt.excpkt_num == EXC_PKT_NUM_4))
{
db_excpkt_add (&excpkt, header->tv_sec, header->tv_usec, ieee80211_hdr_3addr->addr1, ieee80211_hdr_3addr->addr2);
}
}
}
int main (int argc, char *argv[])
{
if ((argc != 3) && (argc != 4) && (argc != 5))
{
fprintf (stderr, "usage: %s input.pcap output.hccapx [filter by essid] [additional network essid:bssid]\n", argv[0]);
return -1;
}
char *in = argv[1];
char *out = argv[2];
char *essid_filter = NULL;
if (argc >= 4) essid_filter = argv[3];
// database initializations
essids = (essid_t *) calloc (DB_ESSID_MAX, sizeof (essid_t));
essids_cnt = 0;
excpkts = (excpkt_t *) calloc (DB_EXCPKT_MAX, sizeof (excpkt_t));
excpkts_cnt = 0;
// manual beacon
if (argc >= 5)
{
essid_t essid;
memset (&essid, 0, sizeof (essid_t));
const int rc = get_essid_from_user (argv[4], &essid);
if (rc == -1) return -1;
}
// start with pcap handling
FILE *pcap = fopen (in, "rb");
if (pcap == NULL)
{
fprintf (stderr, "%s: %s\n", in, strerror (errno));
return -1;
}
// check pcap header
pcap_file_header_t pcap_file_header;
const int nread = fread (&pcap_file_header, sizeof (pcap_file_header_t), 1, pcap);
if (nread != 1)
{
fprintf (stderr, "%s: Could not read pcap header\n", in);
return -1;
}
#ifdef BIG_ENDIAN_HOST
pcap_file_header.magic = byte_swap_32 (pcap_file_header.magic);
pcap_file_header.version_major = byte_swap_16 (pcap_file_header.version_major);
pcap_file_header.version_minor = byte_swap_16 (pcap_file_header.version_minor);
pcap_file_header.thiszone = byte_swap_32 (pcap_file_header.thiszone);
pcap_file_header.sigfigs = byte_swap_32 (pcap_file_header.sigfigs);
pcap_file_header.snaplen = byte_swap_32 (pcap_file_header.snaplen);
pcap_file_header.linktype = byte_swap_32 (pcap_file_header.linktype);
#endif
int bitness = 0;
if (pcap_file_header.magic == TCPDUMP_MAGIC)
{
bitness = 0;
}
else if (pcap_file_header.magic == TCPDUMP_CIGAM)
{
bitness = 1;
}
else
{
fprintf (stderr, "%s: Invalid pcap header\n", in);
return 1;
}
if (bitness == 1)
{
pcap_file_header.magic = byte_swap_32 (pcap_file_header.magic);
pcap_file_header.version_major = byte_swap_16 (pcap_file_header.version_major);
pcap_file_header.version_minor = byte_swap_16 (pcap_file_header.version_minor);
pcap_file_header.thiszone = byte_swap_32 (pcap_file_header.thiszone);
pcap_file_header.sigfigs = byte_swap_32 (pcap_file_header.sigfigs);
pcap_file_header.snaplen = byte_swap_32 (pcap_file_header.snaplen);
pcap_file_header.linktype = byte_swap_32 (pcap_file_header.linktype);
}
if ((pcap_file_header.linktype != DLT_IEEE802_11)
&& (pcap_file_header.linktype != DLT_IEEE802_11_PRISM)
&& (pcap_file_header.linktype != DLT_IEEE802_11_RADIO)
&& (pcap_file_header.linktype != DLT_IEEE802_11_PPI_HDR))
{
fprintf (stderr, "%s: Unsupported linktype detected\n", in);
return -1;
}
// walk the packets
while (!feof (pcap))
{
pcap_pkthdr_t header;
const int nread1 = fread (&header, sizeof (pcap_pkthdr_t), 1, pcap);
if (nread1 != 1) continue;
#ifdef BIG_ENDIAN_HOST
header.tv_sec = byte_swap_32 (header.tv_sec);
header.tv_usec = byte_swap_32 (header.tv_usec);
header.caplen = byte_swap_32 (header.caplen);
header.len = byte_swap_32 (header.len);
#endif
if (bitness == 1)
{
header.tv_sec = byte_swap_32 (header.tv_sec);
header.tv_usec = byte_swap_32 (header.tv_usec);
header.caplen = byte_swap_32 (header.caplen);
header.len = byte_swap_32 (header.len);
}
if ((header.tv_sec == 0) && (header.tv_usec == 0))
{
fprintf (stderr, "Zero value timestamps detected in file: %s.\n", in);
fprintf (stderr, "This prevents correct EAPOL-Key timeout calculation.\n");
fprintf (stderr, "Do not use preprocess the capture file with tools such as wpaclean.\n");
return -1;
}
u8 packet[TCPDUMP_DECODE_LEN];
if (header.caplen >= TCPDUMP_DECODE_LEN || (signed)header.caplen < 0)
{
fprintf (stderr, "%s: Oversized packet detected\n", in);
break;
}
const u32 nread2 = fread (&packet, sizeof (u8), header.caplen, pcap);
if (nread2 != header.caplen)
{
fprintf (stderr, "%s: Could not read pcap packet data\n", in);
break;
}
u8 *packet_ptr = packet;
if (pcap_file_header.linktype == DLT_IEEE802_11_PRISM)
{
if (header.caplen < sizeof (prism_header_t))
{
fprintf (stderr, "%s: Could not read prism header\n", in);
break;
}
prism_header_t *prism_header = (prism_header_t *) packet;
#ifdef BIG_ENDIAN_HOST
prism_header->msgcode = byte_swap_32 (prism_header->msgcode);
prism_header->msglen = byte_swap_32 (prism_header->msglen);
#endif
if ((signed)prism_header->msglen < 0)
{
fprintf (stderr, "%s: Oversized packet detected\n", in);
break;
}
if ((signed)(header.caplen - prism_header->msglen) < 0)
{
fprintf (stderr, "%s: Oversized packet detected\n", in);
break;
}
packet_ptr += prism_header->msglen;
header.caplen -= prism_header->msglen;
header.len -= prism_header->msglen;
}
else if (pcap_file_header.linktype == DLT_IEEE802_11_RADIO)
{
if (header.caplen < sizeof (ieee80211_radiotap_header_t))
{
fprintf (stderr, "%s: Could not read radiotap header\n", in);
break;
}
ieee80211_radiotap_header_t *ieee80211_radiotap_header = (ieee80211_radiotap_header_t *) packet;
#ifdef BIG_ENDIAN_HOST
ieee80211_radiotap_header->it_len = byte_swap_16 (ieee80211_radiotap_header->it_len);
ieee80211_radiotap_header->it_present = byte_swap_32 (ieee80211_radiotap_header->it_present);
#endif
if (ieee80211_radiotap_header->it_version != 0)
{
fprintf (stderr, "%s: Invalid radiotap header\n", in);
break;
}
packet_ptr += ieee80211_radiotap_header->it_len;
header.caplen -= ieee80211_radiotap_header->it_len;
header.len -= ieee80211_radiotap_header->it_len;
}
else if (pcap_file_header.linktype == DLT_IEEE802_11_PPI_HDR)
{
if (header.caplen < sizeof (ppi_packet_header_t))
{
fprintf (stderr, "%s: Could not read ppi header\n", in);
break;
}
ppi_packet_header_t *ppi_packet_header = (ppi_packet_header_t *) packet;
#ifdef BIG_ENDIAN_HOST
ppi_packet_header->pph_len = byte_swap_16 (ppi_packet_header->pph_len);
#endif
packet_ptr += ppi_packet_header->pph_len;
header.caplen -= ppi_packet_header->pph_len;
header.len -= ppi_packet_header->pph_len;
}
process_packet (packet_ptr, &header);
}
fclose (pcap);
// inform the user
printf ("Networks detected: %d\n", (int) essids_cnt);
printf ("\n");
if (essids_cnt == 0) return 0;
// prepare output files
FILE *fp = fopen (out, "wb");
if (fp == NULL)
{
fprintf (stderr, "%s: %s\n", out, strerror (errno));
return -1;
}
int written = 0;
// find matching packets
for (lsearch_cnt_t essids_pos = 0; essids_pos < essids_cnt; essids_pos++)
{
const essid_t *essid = essids + essids_pos;
if (essid_filter) if (strcmp (essid->essid, essid_filter)) continue;
printf ("[*] BSSID=%02x:%02x:%02x:%02x:%02x:%02x ESSID=%s (Length: %d)\n",
essid->bssid[0],
essid->bssid[1],
essid->bssid[2],
essid->bssid[3],
essid->bssid[4],
essid->bssid[5],
essid->essid,
essid->essid_len);
for (lsearch_cnt_t excpkt_ap_pos = 0; excpkt_ap_pos < excpkts_cnt; excpkt_ap_pos++)
{
const excpkt_t *excpkt_ap = excpkts + excpkt_ap_pos;
if ((excpkt_ap->excpkt_num != EXC_PKT_NUM_1) && (excpkt_ap->excpkt_num != EXC_PKT_NUM_3)) continue;
if (memcmp (essid->bssid, excpkt_ap->mac_ap, 6) != 0) continue;
for (lsearch_cnt_t excpkt_sta_pos = 0; excpkt_sta_pos < excpkts_cnt; excpkt_sta_pos++)
{
const excpkt_t *excpkt_sta = excpkts + excpkt_sta_pos;
if ((excpkt_sta->excpkt_num != EXC_PKT_NUM_2) && (excpkt_sta->excpkt_num != EXC_PKT_NUM_4)) continue;
if (memcmp (excpkt_ap->mac_ap, excpkt_sta->mac_ap, 6) != 0) continue;
if (memcmp (excpkt_ap->mac_sta, excpkt_sta->mac_sta, 6) != 0) continue;
const bool valid_replay_counter = (excpkt_ap->replay_counter == excpkt_sta->replay_counter) ? true : false;
if (excpkt_ap->excpkt_num < excpkt_sta->excpkt_num)
{
if (excpkt_ap->tv_sec > excpkt_sta->tv_sec) continue;
if ((excpkt_ap->tv_sec + EAPOL_TTL) < excpkt_sta->tv_sec) continue;
}
else
{
if (excpkt_sta->tv_sec > excpkt_ap->tv_sec) continue;
if ((excpkt_sta->tv_sec + EAPOL_TTL) < excpkt_ap->tv_sec) continue;
}
u8 message_pair = 255;
if ((excpkt_ap->excpkt_num == EXC_PKT_NUM_1) && (excpkt_sta->excpkt_num == EXC_PKT_NUM_2))
{
if (excpkt_sta->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M12E2;
}
else
{
continue;
}
}
else if ((excpkt_ap->excpkt_num == EXC_PKT_NUM_1) && (excpkt_sta->excpkt_num == EXC_PKT_NUM_4))
{
if (excpkt_sta->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M14E4;
}
else
{
continue;
}
}
else if ((excpkt_ap->excpkt_num == EXC_PKT_NUM_3) && (excpkt_sta->excpkt_num == EXC_PKT_NUM_2))
{
if (excpkt_sta->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M32E2;
}
else if (excpkt_ap->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M32E3;
}
else
{
continue;
}
}
else if ((excpkt_ap->excpkt_num == EXC_PKT_NUM_3) && (excpkt_sta->excpkt_num == EXC_PKT_NUM_4))
{
if (excpkt_ap->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M34E3;
}
else if (excpkt_sta->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M34E4;
}
else
{
continue;
}
}
else
{
fprintf (stderr, "BUG!!! AP:%d STA:%d\n", excpkt_ap->excpkt_num, excpkt_sta->excpkt_num);
}
int export = 1;
switch (message_pair)
{
case MESSAGE_PAIR_M32E3: export = 0; break;
case MESSAGE_PAIR_M34E3: export = 0; break;
}
if (export == 1)
{
printf (" --> STA=%02x:%02x:%02x:%02x:%02x:%02x, Message Pair=%u, Replay Counter=%" PRIu64 "\n",
excpkt_sta->mac_sta[0],
excpkt_sta->mac_sta[1],
excpkt_sta->mac_sta[2],
excpkt_sta->mac_sta[3],
excpkt_sta->mac_sta[4],
excpkt_sta->mac_sta[5],
message_pair,
excpkt_sta->replay_counter);
}
else
{
printf (" --> STA=%02x:%02x:%02x:%02x:%02x:%02x, Message Pair=%u [Skipped Export]\n",
excpkt_sta->mac_sta[0],
excpkt_sta->mac_sta[1],
excpkt_sta->mac_sta[2],
excpkt_sta->mac_sta[3],
excpkt_sta->mac_sta[4],
excpkt_sta->mac_sta[5],
message_pair);
continue;
}
// finally, write hccapx
hccapx_t hccapx;
memset (&hccapx, 0, sizeof (hccapx));
hccapx.signature = HCCAPX_SIGNATURE;
hccapx.version = HCCAPX_VERSION;
hccapx.message_pair = message_pair;
if (valid_replay_counter == false)
{
hccapx.message_pair |= 0x80;
}
hccapx.essid_len = essid->essid_len;
memcpy (&hccapx.essid, essid->essid, 32);
memcpy (&hccapx.mac_ap, excpkt_ap->mac_ap, 6);
memcpy (&hccapx.nonce_ap, excpkt_ap->nonce, 32);
memcpy (&hccapx.mac_sta, excpkt_sta->mac_sta, 6);
memcpy (&hccapx.nonce_sta, excpkt_sta->nonce, 32);
if (excpkt_sta->eapol_len > 0)
{
hccapx.keyver = excpkt_sta->keyver;
memcpy (&hccapx.keymic, excpkt_sta->keymic, 16);
hccapx.eapol_len = excpkt_sta->eapol_len;
memcpy (&hccapx.eapol, excpkt_sta->eapol, 256);
}
else
{
hccapx.keyver = excpkt_ap->keyver;
memcpy (&hccapx.keymic, excpkt_ap->keymic, 16);
hccapx.eapol_len = excpkt_ap->eapol_len;
memcpy (&hccapx.eapol, excpkt_ap->eapol, 256);
}
#ifdef BIG_ENDIAN_HOST
hccapx.signature = byte_swap_32 (hccapx.signature);
hccapx.version = byte_swap_32 (hccapx.version);
hccapx.eapol_len = byte_swap_16 (hccapx.eapol_len);
#endif
fwrite (&hccapx, sizeof (hccapx_t), 1, fp);
written++;
}
}
}
printf ("\n");
printf ("Written %d WPA Handshakes to: %s\n", written, out);
fclose (fp);
// clean up
free (excpkts);
free (essids);
return 0;
}
|
the_stack_data/545693.c | //*****************************************************************************
//
// startup_ccs.c - Startup code for use with TI's Code Composer Studio.
//
// Copyright (c) 2007-2013 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 10636 of the EK-LM3S8962 Firmware Package.
//
//*****************************************************************************
//*****************************************************************************
//
// Forward declaration of the default fault handlers.
//
//*****************************************************************************
void ResetISR(void);
static void NmiSR(void);
static void FaultISR(void);
static void IntDefaultHandler(void);
//*****************************************************************************
//
// External declaration for the reset handler that is to be called when the
// processor is started
//
//*****************************************************************************
extern void _c_int00(void);
//*****************************************************************************
//
// Linker variable that marks the top of the stack.
//
//*****************************************************************************
extern unsigned long __STACK_TOP;
//*****************************************************************************
//
// External declarations for the interrupt handlers used by the application.
//
//*****************************************************************************
extern void EthernetIntHandler(void);
extern void SysTickIntHandler(void);
//*****************************************************************************
//
// The vector table. Note that the proper constructs must be placed on this to
// ensure that it ends up at physical address 0x0000.0000 or at the start of
// the program if located at a start address other than 0.
//
//*****************************************************************************
#pragma DATA_SECTION(g_pfnVectors, ".intvecs")
void (* const g_pfnVectors[])(void) =
{
(void (*)(void))((unsigned long)&__STACK_TOP),
// The initial stack pointer
ResetISR, // The reset handler
NmiSR, // The NMI handler
FaultISR, // The hard fault handler
IntDefaultHandler, // The MPU fault handler
IntDefaultHandler, // The bus fault handler
IntDefaultHandler, // The usage fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // SVCall handler
IntDefaultHandler, // Debug monitor handler
0, // Reserved
IntDefaultHandler, // The PendSV handler
SysTickIntHandler, // The SysTick handler
IntDefaultHandler, // GPIO Port A
IntDefaultHandler, // GPIO Port B
IntDefaultHandler, // GPIO Port C
IntDefaultHandler, // GPIO Port D
IntDefaultHandler, // GPIO Port E
IntDefaultHandler, // UART0 Rx and Tx
IntDefaultHandler, // UART1 Rx and Tx
IntDefaultHandler, // SSI0 Rx and Tx
IntDefaultHandler, // I2C0 Master and Slave
IntDefaultHandler, // PWM Fault
IntDefaultHandler, // PWM Generator 0
IntDefaultHandler, // PWM Generator 1
IntDefaultHandler, // PWM Generator 2
IntDefaultHandler, // Quadrature Encoder 0
IntDefaultHandler, // ADC Sequence 0
IntDefaultHandler, // ADC Sequence 1
IntDefaultHandler, // ADC Sequence 2
IntDefaultHandler, // ADC Sequence 3
IntDefaultHandler, // Watchdog timer
IntDefaultHandler, // Timer 0 subtimer A
IntDefaultHandler, // Timer 0 subtimer B
IntDefaultHandler, // Timer 1 subtimer A
IntDefaultHandler, // Timer 1 subtimer B
IntDefaultHandler, // Timer 2 subtimer A
IntDefaultHandler, // Timer 2 subtimer B
IntDefaultHandler, // Analog Comparator 0
IntDefaultHandler, // Analog Comparator 1
IntDefaultHandler, // Analog Comparator 2
IntDefaultHandler, // System Control (PLL, OSC, BO)
IntDefaultHandler, // FLASH Control
IntDefaultHandler, // GPIO Port F
IntDefaultHandler, // GPIO Port G
IntDefaultHandler, // GPIO Port H
IntDefaultHandler, // UART2 Rx and Tx
IntDefaultHandler, // SSI1 Rx and Tx
IntDefaultHandler, // Timer 3 subtimer A
IntDefaultHandler, // Timer 3 subtimer B
IntDefaultHandler, // I2C1 Master and Slave
IntDefaultHandler, // Quadrature Encoder 1
IntDefaultHandler, // CAN0
IntDefaultHandler, // CAN1
IntDefaultHandler, // CAN2
EthernetIntHandler, // Ethernet
IntDefaultHandler // Hibernate
};
//*****************************************************************************
//
// This is the code that gets called when the processor first starts execution
// following a reset event. Only the absolutely necessary set is performed,
// after which the application supplied entry() routine is called. Any fancy
// actions (such as making decisions based on the reset cause register, and
// resetting the bits in that register) are left solely in the hands of the
// application.
//
//*****************************************************************************
void
ResetISR(void)
{
//
// Jump to the CCS C initialization routine.
//
__asm(" .global _c_int00\n"
" b.w _c_int00");
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a NMI. This
// simply enters an infinite loop, preserving the system state for examination
// by a debugger.
//
//*****************************************************************************
static void
NmiSR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a fault
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
FaultISR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives an unexpected
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
IntDefaultHandler(void)
{
//
// Go into an infinite loop.
//
while(1)
{
}
}
|
the_stack_data/938450.c | #include <stdio.h>
int strend(const char *, char *);
int main() {
printf("=====\nresult = %d\n=====\n\n", strend("12345111", "111"));
printf("=====\nresult = %d\n=====\n\n", strend("c++", "c"));
printf("=====\nresult = %d\n=====\n\n", strend("assembler", "bler"));
printf("=====\nresult = %d\n=====\n\n", strend("Sokolov Ilya", "Ilya"));
printf("=====\nresult = %d\n=====\n\n", strend("scala", "python"));
printf("=====\nresult = %d\n=====\n\n", strend("java", "kotlin"));
return 0;
}
int strend(const char *s, char *t) {
char *pt;
for (pt = t; *s != '\0'; ++s) {
if (*pt != '\0' && *s == *pt) {
++pt;
} else {
pt = t;
}
}
if (*s == '\0' && *pt == '\0') return 1;
return 0;
} |
the_stack_data/92327713.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int memory (int k, int f, int q, int max) {
int i, j, p_number, pid, on_memory, PF_k1 = 0, PF_k2 = 0, PF = 0, disk_write = 0, disk_read = 0, trace_entries = 0;
char p_number_str[5], p_oper[1], line[256];
char *token;
int **IPT;
/* Dynamic memory allocate for Inverted Page Table */
if ((IPT = malloc(f * sizeof(int*))) == NULL) {
printf("Error allocating memory\n");
return -1;
}
for (i = 0 ; i < f ; i++) {
if ((IPT[i] = malloc(4 * sizeof(int))) == NULL) {
printf("Error allocating memory\n");
return -1;
}
/* Initialization of valid bit to 0 */
IPT[i][3] = 0;
}
/* Open first trace files */
FILE* process1 = fopen("bzip.trace", "r");
if (process1 == NULL) {
printf("Error opening the trace file\n");
return -2;
}
/* Open second trace files */
FILE* process2 = fopen("gcc.trace", "r");
if (process2 == NULL) {
printf("Error opening the trace file\n");
return -2;
}
/* Loop while trace_entries match max */
while(1) {
/* Examine traces of q-size block from first process */
for (i = 0 ; i < q ; i++) {
/* Read one line of first trace file and update p_number, p_oper, pid */
pid = 1;
fgets(line, sizeof(line), process1);
token = strtok(line, " /t");
strncpy(p_number_str, token, 5);
p_number_str[5] = 0; // Null terminate destination
p_number = (int)strtol(p_number_str, NULL, 16);
token = strtok(NULL, " /t");
strcpy(p_oper, token);
p_oper[1] = 0; // Null terminate destination
on_memory = 0;
/* Search IPT for process with p_number */
for (j = 0 ; j < f ; j++) {
if (IPT[j][3] != 0) {
if (IPT[j][0] == pid && IPT[j][1] == p_number) {
if (!strcmp(p_oper, "W"))
IPT[j][2] = 1; // Set it dirty
on_memory = 1;
}
}
}
/* Trace not on IPT, page fault occurs*/
if (on_memory == 0) {
PF_k1++; // block page fault counter
PF++; // statistic total page fault counter
disk_read++;
if (PF_k1 > k) {
/* Execute PWF for traces with pid */
for (j = 0 ; j < f ; j++) {
if (IPT[j][0] == pid) {
if (IPT[j][2] == 1)
disk_write++;
IPT[j][3] = 0;
}
}
PF_k1 = 1;
}
/* Update IPT with new trace */
for (j = 0 ; j < f ; j++) {
if (IPT[j][3] == 0 && (IPT[j][0] == pid || IPT[j][0] == 0)){
IPT[j][0] = pid;
IPT[j][1] = p_number;
IPT[j][3] = 1;
if (!strcmp(p_oper, "W"))
IPT[j][2] = 1; // Set it dirty
else
IPT[j][2] = 0; // Set it clean
break;
}
}
}
trace_entries++;
/* Check if we already examine max entries from both trace files */
if (trace_entries == max) {
/* Execute PWF for whole IPT at exit and update statistic variables */
for (j = 0 ; j < f ; j++) {
if (IPT[j][3] != 0) {
if (IPT[j][2] == 1)
disk_write++;
IPT[j][3] = 0;
}
}
printf("Frames wrote on disc: %d\n", disk_write);
printf("Frames read from disc: %d\n", disk_read);
printf("Page faults: %d\n" , PF);
printf("Trace entries examined from files: %d\n", trace_entries);
printf("Memory frames: %d\n", f);
fclose(process1);
fclose(process2);
for (i = 0 ; i < f ; i++)
free(IPT[i]);
free(IPT);
return 0;
}
}
/* Examine traces of q-size block from second process */
for (i = 0 ; i < q ; i++) {
/* Read one line of second trace file and update p_number, p_oper, pid */
pid = 2;
fgets(line, sizeof(line), process2);
token = strtok(line, " /t");
strncpy(p_number_str, token, 5);
p_number_str[5] = 0; // Null terminate destination
p_number = (int)strtol(p_number_str, NULL, 16);
token = strtok(NULL, " /t");
strcpy(p_oper, token);
p_oper[1] = 0; // Null terminate destination
on_memory = 0;
/* Search IPT for process with p_number */
for (j = 0 ; j < f ; j++) {
if (IPT[j][3] != 0) {
if (IPT[j][0] == pid && IPT[j][1] == p_number) {
if (!strcmp(p_oper, "W"))
IPT[j][2] = 1; // Set it dirty
on_memory = 1;
}
}
}
/* Trace not on IPT, page fault occurs */
if (on_memory == 0) {
PF_k2++; // block page fault counter
PF++; // statistic total page fault counter
disk_read++;
if (PF_k2 > k) {
// Execute PWF
for (j = 0 ; j < f ; j++) {
if (IPT[j][0] == pid) {
if (IPT[j][2] == 1)
disk_write++;
IPT[j][3] = 0;
}
}
PF_k2 = 1;
}
/* Update IPT with new trace */
for (j = 0 ; j < f ; j++) {
if (IPT[j][3] == 0 && (IPT[j][0] == pid || IPT[j][0] == 0)){
IPT[j][0] = pid;
IPT[j][1] = p_number;
IPT[j][3] = 1;
if (!strcmp(p_oper, "W"))
IPT[j][2] = 1; // Set it dirty
else
IPT[j][2] = 0; // Set it clean
break;
}
}
}
trace_entries++;
/* Check if we already examine max entries from both trace files */
if (trace_entries == max) {
/* Execute PWF for whole IPT at exit and update statistic variables */
for (j = 0 ; j < f ; j++) {
if (IPT[j][3] != 0) {
if (IPT[j][2] == 1)
disk_write++;
IPT[j][3] = 0;
}
}
printf("Frames wrote on disc: %d\n", disk_write);
printf("Frames read from disc: %d\n", disk_read);
printf("Page faults: %d\n" , PF);
printf("Trace entries examined from files: %d\n", trace_entries);
printf("Memory frames: %d\n", f);
fclose(process1);
fclose(process2);
for (i = 0 ; i < f ; i++)
free(IPT[i]);
free(IPT);
return 0;
}
}
}
}
|
the_stack_data/45882.c | int thing(int a, int b) {
return a + b;
}
int main() {
int x0, x1, x2, x3, x4, x5, x6, x7, x8, x9;
for (int i = 0; i < 10; ++i) {
if (i == 0) x0 = thing(1, -2);
if (i == 1) x1 = thing(2, -3);
if (i == 2) x2 = thing(3, -4);
if (i == 3) x3 = thing(4, -5);
if (i == 4) x4 = thing(5, -6);
if (i == 5) x5 = thing(6, -7);
if (i == 6) x6 = thing(7, -8);
if (i == 7) x7 = thing(8, -9);
if (i == 8) x8 = thing(9, -10);
if (i == 9) x9 = thing(10, 0);
}
return x0 + x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9; // 1
}
|
the_stack_data/73574651.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
static const char BasicArray[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
// encryption for client
#define MAX_CHAR 80000
#define BASICLEN 27
// daemon server for encryption
// This child process of otp_enc_d must first check to make sure it is communicating with otp_enc (see otp_enc, below). After verifying that the connection to otp_enc_d is coming from otp_enc, then this child receives from otp_enc plaintext and a key via the communication socket (not the original listen socket). The otp_enc_d child will then write back the ciphertext to the otp_enc process that it is connected to via the same communication socket. Note that the key passed in must be at least as big as the plaintext.
//There are two ways we can recive the message from the client either I get the size of mesage and recieve the message or I can break it into two different things
// Not sure what to do :()
void error(const char *msg) { perror(msg); exit(1); } // Error function used for reporting issues
int main(int argc, char *argv[])
{
int listenSocketFD, establishedConnectionFD, portNumber, charsRead, charsWritten;
socklen_t sizeOfClientInfo;
int keygenlen=0;
int plain_textlen=0;
char buffer[10000];
int readBytes=0;
int countbytes=0;
int bytesRemain=0;
// char keygen[MAX_CHAR];
struct sockaddr_in serverAddress, clientAddress;
if (argc < 2) { fprintf(stderr,"USAGE: %s port\n", argv[0]); exit(1); } // Check usage & args
// Set up the address struct for this process (the server)
memset((char *)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct
portNumber = atoi(argv[1]); // Get the port number, convert to an integer from a string
serverAddress.sin_family = AF_INET; // Create a network-capable socket
serverAddress.sin_port = htons(portNumber); // Store the port number
serverAddress.sin_addr.s_addr = INADDR_ANY; // Any address is allowed for connection to this process
// Set up the socket
listenSocketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket
if (listenSocketFD < 0) error("ERROR opening socket");
// Enable the socket to begin listening
if (bind(listenSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to port
error("ERROR on binding");
listen(listenSocketFD, 5); // Flip the socket on - it can now receive up to 5 connections
while(1){
// Accept a connection, blocking if one is not available until one connects
sizeOfClientInfo = sizeof(clientAddress); // Get the size of the address for the client that will connect
establishedConnectionFD = accept(listenSocketFD, (struct sockaddr *)&clientAddress, &sizeOfClientInfo); // Accept
if (establishedConnectionFD < 0) error("ERROR on accept");
// printf("Server: Connected client at port %d\n", ntohs(clientAddress.sin_port));
int received_int = 0;
// reciving keygen length
charsRead = recv(establishedConnectionFD, &received_int, sizeof(received_int), 0); // Read the client's message from the socket
if (charsRead < 0) error("ERROR reading from socket");
// printf("SERVER: I received this from the client: \"%d\"\n", ntohl(received_int));
keygenlen=htonl(received_int);
// printf("Keygen length is %d\n", keygenlen);
// recieving plaintext length
received_int=0;
charsRead = recv(establishedConnectionFD, &received_int, sizeof(received_int), 0); // Read the client's message from the socket
if (charsRead < 0) error("ERROR reading from socket");
// printf("SERVER: I received this from the client: \"%d\"\n", ntohl(received_int));
plain_textlen=htonl(received_int);
// printf("encrypted text length is %d\n", plain_textlen);
// Get the message from the client and display it
// reciveing keygen
//lets do the same for keygen as we did to recieve plain_text
char* keygen=malloc(keygenlen);
memset(keygen, '\0', keygenlen);
charsRead=0;
int readBytes=0;
int countbytes=0;
int bytesRemain=keygenlen;
while (readBytes != keygenlen){
charsRead = recv(establishedConnectionFD, keygen, bytesRemain, 0);
if (charsRead < 0) error("ERRROR READING KEYGEN");
readBytes=readBytes+charsRead;
bytesRemain=keygenlen-readBytes;
// printf("Bytes reamining %d\n", bytesRemain);
}
printf("Keygen : %s\n", keygen);
// just for checking
// FILE *fptr1 = fopen("KeygenPlaintext", "wb");
// fprintf(fptr1, "%s\n", keygen);
// fclose(fptr1);
// recieving plaintext
char* plain_text=malloc(plain_textlen);
memset(plain_text, '\0', plain_textlen);
charsRead=0;
readBytes=0; //how much data was read
countbytes=0; //how much data is left to read
bytesRemain=plain_textlen; //total length of the bytes that supposed to be read
while (readBytes != plain_textlen){
charsRead = recv(establishedConnectionFD, plain_text, bytesRemain, 0);
if (charsRead < 0) error("ERROR reading from socket");
readBytes=readBytes+charsRead;
bytesRemain=plain_textlen-readBytes;
// countbytes=strlen(plain_text);
// printf("Bytes remaining %d\n", bytesRemain);
// if (bytesRemain == 0){
// break;
// }
} // Read the client's message from the socket
printf("I got this plain message %s\n", plain_text);
// printf("SERVER: I received this from the client: \"%d\"\n", strlen(plain_text));
if (strlen(plain_text) != plain_textlen){
error("Something is wrong, plaintext was not recieved properly");
}
char Encrypted_text[plain_textlen];
memset(Encrypted_text, '\0', plain_textlen);
//lets encrypted it
int keyintArray[keygenlen]; //converting key to int
int plaintIntArray[plain_textlen]; //converting plaintext to int
int i=0;
int j=0;
for (i=0; i<keygenlen; i++){
for (j=0; j<27; j++){
if (keygen[i] == BasicArray[j])
keyintArray[i] = j;
}
}
for (i=0; i<plain_textlen; i++){
for (j=0; j<27; j++){
if (plain_text[i] == BasicArray[j])
plaintIntArray[i] = j;
}
}
int EncryptedTextArray[plain_textlen];
for (i=0; i<plain_textlen; i++){
int messagekey=0;
messagekey=plaintIntArray[i]+keyintArray[i];
EncryptedTextArray[i] = ((messagekey) % 27);
}
for (i=0; i<plain_textlen; i++){
Encrypted_text[i]=BasicArray[EncryptedTextArray[i]];
}
//sending encrypted Text length
int encryptedtextlen = strlen(Encrypted_text);
int converted_number=htonl(encryptedtextlen);
charsWritten = send(establishedConnectionFD, &converted_number, sizeof(converted_number), 0); // Write to the server
if (charsWritten < 0) error("CLIENT: ERROR writing to socket");
if (charsWritten < sizeof(converted_number)) printf("CLIENT: WARNING: Not all data written to socket!\n");
charsWritten = send(establishedConnectionFD, Encrypted_text, encryptedtextlen, 0); // Write to the server
if (charsWritten < 0) error("CLIENT: ERROR writing to socket");
if (charsWritten < sizeof(converted_number)) printf("CLIENT: WARNING: Not all data written to socket!\n");
//lets send the encrypted text
// printf("length of encrypted Message %d\n", strlen(Encrypted_text));
// FILE *fptr1 = fopen("EncryptedText", "wb");
// fprintf(fptr1, "%s\n", Encrypted_text);
// fclose(fptr1);
//lets send it back to our client
close(establishedConnectionFD); // Close the existing socket which is connected to the client
}
close(listenSocketFD); // Close the listening socket
return 0;
}
|
the_stack_data/64199284.c |
#include <stdio.h>
int main (int argc, char **argv)
{
/*
setlinebuf(stdout);
*/
extern int errno;
errno=0;
printf ("Hello world!!\n");
/* Note: errno will be 9 for ptys */
/*
printf ("errno: %d\n", errno);
perror ("perror");
fflush (stdout);
*/
exit (0);
}
|
the_stack_data/125771.c | #include <stddef.h>
typedef int (fint)(int x); // better without *fint, so we can use it in declaration
fint inc;
int inc(int x) {return x+1;}
long long scalar_product(const int *a, const int *b, size_t len) {
long long ret =0;
if(a && b){
for(size_t i=0; i<len;++i)
ret += (long long)a[i]* (long long)b[i];
}
return ret;
}
int main(){
fint* fi = &inc;
fi(5);
return 0;
} |
the_stack_data/685838.c | /* Triangle/triangle intersection test routine,
* by Tomas Moller, 1997.
* See article "A Fast Triangle-Triangle Intersection Test",
* Journal of Graphics Tools, 2(2), 1997
*
* int tri_tri_intersect(float V0[3],float V1[3],float V2[3],
* float U0[3],float U1[3],float U2[3])
*
* parameters: vertices of triangle 1: V0,V1,V2
* vertices of triangle 2: U0,U1,U2
* result : returns 1 if the triangles intersect, otherwise 0
*
*/
#include <math.h>
/* if USE_EPSILON_TEST is true then we do a check:
if |dv|<EPSILON then dv=0.0;
else no check is done (which is less robust)
*/
#define USE_EPSILON_TEST TRUE
#define EPSILON 0.000001
/* some macros */
#define CROSS(dest,v1,v2) \
dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \
dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \
dest[2]=v1[0]*v2[1]-v1[1]*v2[0];
#define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2])
#define SUB(dest,v1,v2) \
dest[0]=v1[0]-v2[0]; \
dest[1]=v1[1]-v2[1]; \
dest[2]=v1[2]-v2[2];
/* sort so that a<=b */
#define SORT(a,b) \
if(a>b) \
{ \
float c; \
c=a; \
a=b; \
b=c; \
}
#define ISECT(VV0,VV1,VV2,D0,D1,D2,isect0,isect1) \
isect0=VV0+(VV1-VV0)*D0/(D0-D1); \
isect1=VV0+(VV2-VV0)*D0/(D0-D2);
#define COMPUTE_INTERVALS(VV0,VV1,VV2,D0,D1,D2,D0D1,D0D2,isect0,isect1) \
if(D0D1>0.0f) \
{ \
/* here we know that D0D2<=0.0 */ \
/* that is D0, D1 are on the same side, D2 on the other or on the plane */ \
ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1); \
} \
else if(D0D2>0.0f) \
{ \
/* here we know that d0d1<=0.0 */ \
ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1); \
} \
else if(D1*D2>0.0f || D0!=0.0f) \
{ \
/* here we know that d0d1<=0.0 or that D0!=0.0 */ \
ISECT(VV0,VV1,VV2,D0,D1,D2,isect0,isect1); \
} \
else if(D1!=0.0f) \
{ \
ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1); \
} \
else if(D2!=0.0f) \
{ \
ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1); \
} \
else \
{ \
/* triangles are coplanar */ \
return coplanar_tri_tri(N1,V0,V1,V2,U0,U1,U2); \
}
/* this edge to edge test is based on Franlin Antonio's gem:
"Faster Line Segment Intersection", in Graphics Gems III,
pp. 199-202 */
#define EDGE_EDGE_TEST(V0,U0,U1) \
Bx=U0[i0]-U1[i0]; \
By=U0[i1]-U1[i1]; \
Cx=V0[i0]-U0[i0]; \
Cy=V0[i1]-U0[i1]; \
f=Ay*Bx-Ax*By; \
d=By*Cx-Bx*Cy; \
if((f>0 && d>=0 && d<=f) || (f<0 && d<=0 && d>=f)) \
{ \
e=Ax*Cy-Ay*Cx; \
if(f>0) \
{ \
if(e>=0 && e<=f) return 1; \
} \
else \
{ \
if(e<=0 && e>=f) return 1; \
} \
}
#define EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2) \
{ \
float Ax,Ay,Bx,By,Cx,Cy,e,d,f; \
Ax=V1[i0]-V0[i0]; \
Ay=V1[i1]-V0[i1]; \
/* test edge U0,U1 against V0,V1 */ \
EDGE_EDGE_TEST(V0,U0,U1); \
/* test edge U1,U2 against V0,V1 */ \
EDGE_EDGE_TEST(V0,U1,U2); \
/* test edge U2,U1 against V0,V1 */ \
EDGE_EDGE_TEST(V0,U2,U0); \
}
#define POINT_IN_TRI(V0,U0,U1,U2) \
{ \
float a,b,c,d0,d1,d2; \
/* is T1 completly inside T2? */ \
/* check if V0 is inside tri(U0,U1,U2) */ \
a=U1[i1]-U0[i1]; \
b=-(U1[i0]-U0[i0]); \
c=-a*U0[i0]-b*U0[i1]; \
d0=a*V0[i0]+b*V0[i1]+c; \
\
a=U2[i1]-U1[i1]; \
b=-(U2[i0]-U1[i0]); \
c=-a*U1[i0]-b*U1[i1]; \
d1=a*V0[i0]+b*V0[i1]+c; \
\
a=U0[i1]-U2[i1]; \
b=-(U0[i0]-U2[i0]); \
c=-a*U2[i0]-b*U2[i1]; \
d2=a*V0[i0]+b*V0[i1]+c; \
if(d0*d1>0.0) \
{ \
if(d0*d2>0.0) return 1; \
} \
}
int coplanar_tri_tri(float N[3],float V0[3],float V1[3],float V2[3],
float U0[3],float U1[3],float U2[3])
{
float A[3];
short i0,i1;
/* first project onto an axis-aligned plane, that maximizes the area */
/* of the triangles, compute indices: i0,i1. */
A[0]=fabs(N[0]);
A[1]=fabs(N[1]);
A[2]=fabs(N[2]);
if(A[0]>A[1])
{
if(A[0]>A[2])
{
i0=1; /* A[0] is greatest */
i1=2;
}
else
{
i0=0; /* A[2] is greatest */
i1=1;
}
}
else /* A[0]<=A[1] */
{
if(A[2]>A[1])
{
i0=0; /* A[2] is greatest */
i1=1;
}
else
{
i0=0; /* A[1] is greatest */
i1=2;
}
}
/* test all edges of triangle 1 against the edges of triangle 2 */
EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2);
EDGE_AGAINST_TRI_EDGES(V1,V2,U0,U1,U2);
EDGE_AGAINST_TRI_EDGES(V2,V0,U0,U1,U2);
/* finally, test if tri1 is totally contained in tri2 or vice versa */
POINT_IN_TRI(V0,U0,U1,U2);
POINT_IN_TRI(U0,V0,V1,V2);
return 0;
}
int tri_tri_intersect(float V0[3],float V1[3],float V2[3],
float U0[3],float U1[3],float U2[3])
{
float E1[3],E2[3];
float N1[3],N2[3],d1,d2;
float du0,du1,du2,dv0,dv1,dv2;
float D[3];
float isect1[2], isect2[2];
float du0du1,du0du2,dv0dv1,dv0dv2;
short index;
float vp0,vp1,vp2;
float up0,up1,up2;
float b,c,max;
/* compute plane equation of triangle(V0,V1,V2) */
SUB(E1,V1,V0);
SUB(E2,V2,V0);
CROSS(N1,E1,E2);
d1=-DOT(N1,V0);
/* plane equation 1: N1.X+d1=0 */
/* put U0,U1,U2 into plane equation 1 to compute signed distances to the plane*/
du0=DOT(N1,U0)+d1;
du1=DOT(N1,U1)+d1;
du2=DOT(N1,U2)+d1;
/* coplanarity robustness check */
#if USE_EPSILON_TEST==TRUE
if(fabs(du0)<EPSILON) du0=0.0;
if(fabs(du1)<EPSILON) du1=0.0;
if(fabs(du2)<EPSILON) du2=0.0;
#endif
du0du1=du0*du1;
du0du2=du0*du2;
if(du0du1>0.0f && du0du2>0.0f) /* same sign on all of them + not equal 0 ? */
return 0; /* no intersection occurs */
/* compute plane of triangle (U0,U1,U2) */
SUB(E1,U1,U0);
SUB(E2,U2,U0);
CROSS(N2,E1,E2);
d2=-DOT(N2,U0);
/* plane equation 2: N2.X+d2=0 */
/* put V0,V1,V2 into plane equation 2 */
dv0=DOT(N2,V0)+d2;
dv1=DOT(N2,V1)+d2;
dv2=DOT(N2,V2)+d2;
#if USE_EPSILON_TEST==TRUE
if(fabs(dv0)<EPSILON) dv0=0.0;
if(fabs(dv1)<EPSILON) dv1=0.0;
if(fabs(dv2)<EPSILON) dv2=0.0;
#endif
dv0dv1=dv0*dv1;
dv0dv2=dv0*dv2;
if(dv0dv1>0.0f && dv0dv2>0.0f) /* same sign on all of them + not equal 0 ? */
return 0; /* no intersection occurs */
/* compute direction of intersection line */
CROSS(D,N1,N2);
/* compute and index to the largest component of D */
max=fabs(D[0]);
index=0;
b=fabs(D[1]);
c=fabs(D[2]);
if(b>max) max=b,index=1;
if(c>max) max=c,index=2;
/* this is the simplified projection onto L*/
vp0=V0[index];
vp1=V1[index];
vp2=V2[index];
up0=U0[index];
up1=U1[index];
up2=U2[index];
/* compute interval for triangle 1 */
COMPUTE_INTERVALS(vp0,vp1,vp2,dv0,dv1,dv2,dv0dv1,dv0dv2,isect1[0],isect1[1]);
/* compute interval for triangle 2 */
COMPUTE_INTERVALS(up0,up1,up2,du0,du1,du2,du0du1,du0du2,isect2[0],isect2[1]);
SORT(isect1[0],isect1[1]);
SORT(isect2[0],isect2[1]);
if(isect1[1]<isect2[0] || isect2[1]<isect1[0]) return 0;
return 1;
}
|
the_stack_data/37638211.c | /*
* Freescale i.MX23/i.MX28 SB image generator
*
* Copyright (C) 2012-2013 Marek Vasut <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifdef CONFIG_MXS
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <openssl/evp.h>
#include "imagetool.h"
#include "mxsimage.h"
#include "pbl_crc32.h"
#include <image.h>
/*
* DCD block
* |-Write to address command block
* | 0xf00 == 0xf33d
* | 0xba2 == 0xb33f
* |-ORR address with mask command block
* | 0xf00 |= 0x1337
* |-Write to address command block
* | 0xba2 == 0xd00d
* :
*/
#define SB_HAB_DCD_WRITE 0xccUL
#define SB_HAB_DCD_CHECK 0xcfUL
#define SB_HAB_DCD_NOOP 0xc0UL
#define SB_HAB_DCD_MASK_BIT (1 << 3)
#define SB_HAB_DCD_SET_BIT (1 << 4)
/* Addr.n = Value.n */
#define SB_DCD_WRITE \
(SB_HAB_DCD_WRITE << 24)
/* Addr.n &= ~Value.n */
#define SB_DCD_ANDC \
((SB_HAB_DCD_WRITE << 24) | SB_HAB_DCD_SET_BIT)
/* Addr.n |= Value.n */
#define SB_DCD_ORR \
((SB_HAB_DCD_WRITE << 24) | SB_HAB_DCD_SET_BIT | SB_HAB_DCD_MASK_BIT)
/* (Addr.n & Value.n) == 0 */
#define SB_DCD_CHK_EQZ \
(SB_HAB_DCD_CHECK << 24)
/* (Addr.n & Value.n) == Value.n */
#define SB_DCD_CHK_EQ \
((SB_HAB_DCD_CHECK << 24) | SB_HAB_DCD_SET_BIT)
/* (Addr.n & Value.n) != Value.n */
#define SB_DCD_CHK_NEQ \
((SB_HAB_DCD_CHECK << 24) | SB_HAB_DCD_MASK_BIT)
/* (Addr.n & Value.n) != 0 */
#define SB_DCD_CHK_NEZ \
((SB_HAB_DCD_CHECK << 24) | SB_HAB_DCD_SET_BIT | SB_HAB_DCD_MASK_BIT)
/* NOP */
#define SB_DCD_NOOP \
(SB_HAB_DCD_NOOP << 24)
struct sb_dcd_ctx {
struct sb_dcd_ctx *dcd;
uint32_t id;
/* The DCD block. */
uint32_t *payload;
/* Size of the whole DCD block. */
uint32_t size;
/* Pointer to previous DCD command block. */
uint32_t *prev_dcd_head;
};
/*
* IMAGE
* |-SECTION
* | |-CMD
* | |-CMD
* | `-CMD
* |-SECTION
* | |-CMD
* : :
*/
struct sb_cmd_list {
char *cmd;
size_t len;
unsigned int lineno;
};
struct sb_cmd_ctx {
uint32_t size;
struct sb_cmd_ctx *cmd;
uint8_t *data;
uint32_t length;
struct sb_command payload;
struct sb_command c_payload;
};
struct sb_section_ctx {
uint32_t size;
/* Section flags */
unsigned int boot:1;
struct sb_section_ctx *sect;
struct sb_cmd_ctx *cmd_head;
struct sb_cmd_ctx *cmd_tail;
struct sb_sections_header payload;
};
struct sb_image_ctx {
unsigned int in_section:1;
unsigned int in_dcd:1;
/* Image configuration */
unsigned int verbose_boot:1;
unsigned int silent_dump:1;
char *input_filename;
char *output_filename;
char *cfg_filename;
uint8_t image_key[16];
/* Number of section in the image */
unsigned int sect_count;
/* Bootable section */
unsigned int sect_boot;
unsigned int sect_boot_found:1;
struct sb_section_ctx *sect_head;
struct sb_section_ctx *sect_tail;
struct sb_dcd_ctx *dcd_head;
struct sb_dcd_ctx *dcd_tail;
EVP_CIPHER_CTX cipher_ctx;
EVP_MD_CTX md_ctx;
uint8_t digest[32];
struct sb_key_dictionary_key sb_dict_key;
struct sb_boot_image_header payload;
};
/*
* Instruction semantics:
* NOOP
* TAG [LAST]
* LOAD address file
* LOAD IVT address IVT_entry_point
* FILL address pattern length
* JUMP [HAB] address [r0_arg]
* CALL [HAB] address [r0_arg]
* MODE mode
* For i.MX23, mode = USB/I2C/SPI1_FLASH/SPI2_FLASH/NAND_BCH
* JTAG/SPI3_EEPROM/SD_SSP0/SD_SSP1
* For i.MX28, mode = USB/I2C/SPI2_FLASH/SPI3_FLASH/NAND_BCH
* JTAG/SPI2_EEPROM/SD_SSP0/SD_SSP1
*/
/*
* AES libcrypto
*/
static int sb_aes_init(struct sb_image_ctx *ictx, uint8_t *iv, int enc)
{
EVP_CIPHER_CTX *ctx = &ictx->cipher_ctx;
int ret;
/* If there is no init vector, init vector is all zeroes. */
if (!iv)
iv = ictx->image_key;
EVP_CIPHER_CTX_init(ctx);
ret = EVP_CipherInit(ctx, EVP_aes_128_cbc(), ictx->image_key, iv, enc);
if (ret == 1)
EVP_CIPHER_CTX_set_padding(ctx, 0);
return ret;
}
static int sb_aes_crypt(struct sb_image_ctx *ictx, uint8_t *in_data,
uint8_t *out_data, int in_len)
{
EVP_CIPHER_CTX *ctx = &ictx->cipher_ctx;
int ret, outlen;
uint8_t *outbuf;
outbuf = malloc(in_len);
if (!outbuf)
return -ENOMEM;
memset(outbuf, 0, sizeof(in_len));
ret = EVP_CipherUpdate(ctx, outbuf, &outlen, in_data, in_len);
if (!ret) {
ret = -EINVAL;
goto err;
}
if (out_data)
memcpy(out_data, outbuf, outlen);
err:
free(outbuf);
return ret;
}
static int sb_aes_deinit(EVP_CIPHER_CTX *ctx)
{
return EVP_CIPHER_CTX_cleanup(ctx);
}
static int sb_aes_reinit(struct sb_image_ctx *ictx, int enc)
{
int ret;
EVP_CIPHER_CTX *ctx = &ictx->cipher_ctx;
struct sb_boot_image_header *sb_header = &ictx->payload;
uint8_t *iv = sb_header->iv;
ret = sb_aes_deinit(ctx);
if (!ret)
return ret;
return sb_aes_init(ictx, iv, enc);
}
/*
* Debug
*/
static void soprintf(struct sb_image_ctx *ictx, const char *fmt, ...)
{
va_list ap;
if (ictx->silent_dump)
return;
va_start(ap, fmt);
vfprintf(stdout, fmt, ap);
va_end(ap);
}
/*
* Code
*/
static time_t sb_get_timestamp(void)
{
struct tm time_2000 = {
.tm_yday = 1, /* Jan. 1st */
.tm_year = 100, /* 2000 */
};
time_t seconds_to_2000 = mktime(&time_2000);
time_t seconds_to_now = time(NULL);
return seconds_to_now - seconds_to_2000;
}
static int sb_get_time(time_t time, struct tm *tm)
{
struct tm time_2000 = {
.tm_yday = 1, /* Jan. 1st */
.tm_year = 0, /* 1900 */
};
const time_t seconds_to_2000 = mktime(&time_2000);
const time_t seconds_to_now = seconds_to_2000 + time;
struct tm *ret;
ret = gmtime_r(&seconds_to_now, tm);
return ret ? 0 : -EINVAL;
}
static void sb_encrypt_sb_header(struct sb_image_ctx *ictx)
{
EVP_MD_CTX *md_ctx = &ictx->md_ctx;
struct sb_boot_image_header *sb_header = &ictx->payload;
uint8_t *sb_header_ptr = (uint8_t *)sb_header;
/* Encrypt the header, compute the digest. */
sb_aes_crypt(ictx, sb_header_ptr, NULL, sizeof(*sb_header));
EVP_DigestUpdate(md_ctx, sb_header_ptr, sizeof(*sb_header));
}
static void sb_encrypt_sb_sections_header(struct sb_image_ctx *ictx)
{
EVP_MD_CTX *md_ctx = &ictx->md_ctx;
struct sb_section_ctx *sctx = ictx->sect_head;
struct sb_sections_header *shdr;
uint8_t *sb_sections_header_ptr;
const int size = sizeof(*shdr);
while (sctx) {
shdr = &sctx->payload;
sb_sections_header_ptr = (uint8_t *)shdr;
sb_aes_crypt(ictx, sb_sections_header_ptr,
ictx->sb_dict_key.cbc_mac, size);
EVP_DigestUpdate(md_ctx, sb_sections_header_ptr, size);
sctx = sctx->sect;
};
}
static void sb_encrypt_key_dictionary_key(struct sb_image_ctx *ictx)
{
EVP_MD_CTX *md_ctx = &ictx->md_ctx;
sb_aes_crypt(ictx, ictx->image_key, ictx->sb_dict_key.key,
sizeof(ictx->sb_dict_key.key));
EVP_DigestUpdate(md_ctx, &ictx->sb_dict_key, sizeof(ictx->sb_dict_key));
}
static void sb_decrypt_key_dictionary_key(struct sb_image_ctx *ictx)
{
EVP_MD_CTX *md_ctx = &ictx->md_ctx;
EVP_DigestUpdate(md_ctx, &ictx->sb_dict_key, sizeof(ictx->sb_dict_key));
sb_aes_crypt(ictx, ictx->sb_dict_key.key, ictx->image_key,
sizeof(ictx->sb_dict_key.key));
}
static void sb_encrypt_tag(struct sb_image_ctx *ictx,
struct sb_cmd_ctx *cctx)
{
EVP_MD_CTX *md_ctx = &ictx->md_ctx;
struct sb_command *cmd = &cctx->payload;
sb_aes_crypt(ictx, (uint8_t *)cmd,
(uint8_t *)&cctx->c_payload, sizeof(*cmd));
EVP_DigestUpdate(md_ctx, &cctx->c_payload, sizeof(*cmd));
}
static int sb_encrypt_image(struct sb_image_ctx *ictx)
{
/* Start image-wide crypto. */
EVP_MD_CTX_init(&ictx->md_ctx);
EVP_DigestInit(&ictx->md_ctx, EVP_sha1());
/*
* SB image header.
*/
sb_aes_init(ictx, NULL, 1);
sb_encrypt_sb_header(ictx);
/*
* SB sections header.
*/
sb_encrypt_sb_sections_header(ictx);
/*
* Key dictionary.
*/
sb_aes_reinit(ictx, 1);
sb_encrypt_key_dictionary_key(ictx);
/*
* Section tags.
*/
struct sb_cmd_ctx *cctx;
struct sb_command *ccmd;
struct sb_section_ctx *sctx = ictx->sect_head;
while (sctx) {
cctx = sctx->cmd_head;
sb_aes_reinit(ictx, 1);
while (cctx) {
ccmd = &cctx->payload;
sb_encrypt_tag(ictx, cctx);
if (ccmd->header.tag == ROM_TAG_CMD) {
sb_aes_reinit(ictx, 1);
} else if (ccmd->header.tag == ROM_LOAD_CMD) {
sb_aes_crypt(ictx, cctx->data, cctx->data,
cctx->length);
EVP_DigestUpdate(&ictx->md_ctx, cctx->data,
cctx->length);
}
cctx = cctx->cmd;
}
sctx = sctx->sect;
};
/*
* Dump the SHA1 of the whole image.
*/
sb_aes_reinit(ictx, 1);
EVP_DigestFinal(&ictx->md_ctx, ictx->digest, NULL);
sb_aes_crypt(ictx, ictx->digest, ictx->digest, sizeof(ictx->digest));
/* Stop the encryption session. */
sb_aes_deinit(&ictx->cipher_ctx);
return 0;
}
static int sb_load_file(struct sb_cmd_ctx *cctx, char *filename)
{
long real_size, roundup_size;
uint8_t *data;
long ret;
unsigned long size;
FILE *fp;
if (!filename) {
fprintf(stderr, "ERR: Missing filename!\n");
return -EINVAL;
}
fp = fopen(filename, "r");
if (!fp)
goto err_open;
ret = fseek(fp, 0, SEEK_END);
if (ret < 0)
goto err_file;
real_size = ftell(fp);
if (real_size < 0)
goto err_file;
ret = fseek(fp, 0, SEEK_SET);
if (ret < 0)
goto err_file;
roundup_size = roundup(real_size, SB_BLOCK_SIZE);
data = calloc(1, roundup_size);
if (!data)
goto err_file;
size = fread(data, 1, real_size, fp);
if (size != (unsigned long)real_size)
goto err_alloc;
cctx->data = data;
cctx->length = roundup_size;
fclose(fp);
return 0;
err_alloc:
free(data);
err_file:
fclose(fp);
err_open:
fprintf(stderr, "ERR: Failed to load file \"%s\"\n", filename);
return -EINVAL;
}
static uint8_t sb_command_checksum(struct sb_command *inst)
{
uint8_t *inst_ptr = (uint8_t *)inst;
uint8_t csum = 0;
unsigned int i;
for (i = 0; i < sizeof(struct sb_command); i++)
csum += inst_ptr[i];
return csum;
}
static int sb_token_to_long(char *tok, uint32_t *rid)
{
char *endptr;
unsigned long id;
if (tok[0] != '0' || tok[1] != 'x') {
fprintf(stderr, "ERR: Invalid hexadecimal number!\n");
return -EINVAL;
}
tok += 2;
errno = 0;
id = strtoul(tok, &endptr, 16);
if ((errno == ERANGE && id == ULONG_MAX) || (errno != 0 && id == 0)) {
fprintf(stderr, "ERR: Value can't be decoded!\n");
return -EINVAL;
}
/* Check for 32-bit overflow. */
if (id > 0xffffffff) {
fprintf(stderr, "ERR: Value too big!\n");
return -EINVAL;
}
if (endptr == tok) {
fprintf(stderr, "ERR: Deformed value!\n");
return -EINVAL;
}
*rid = (uint32_t)id;
return 0;
}
static int sb_grow_dcd(struct sb_dcd_ctx *dctx, unsigned int inc_size)
{
uint32_t *tmp;
if (!inc_size)
return 0;
dctx->size += inc_size;
tmp = realloc(dctx->payload, dctx->size);
if (!tmp)
return -ENOMEM;
dctx->payload = tmp;
/* Assemble and update the HAB DCD header. */
dctx->payload[0] = htonl((SB_HAB_DCD_TAG << 24) |
(dctx->size << 8) |
SB_HAB_VERSION);
return 0;
}
static int sb_build_dcd(struct sb_image_ctx *ictx, struct sb_cmd_list *cmd)
{
struct sb_dcd_ctx *dctx;
char *tok;
uint32_t id;
int ret;
dctx = calloc(1, sizeof(*dctx));
if (!dctx)
return -ENOMEM;
ret = sb_grow_dcd(dctx, 4);
if (ret)
goto err_dcd;
/* Read DCD block number. */
tok = strtok(cmd->cmd, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: DCD block without number!\n",
cmd->lineno);
ret = -EINVAL;
goto err_dcd;
}
/* Parse the DCD block number. */
ret = sb_token_to_long(tok, &id);
if (ret) {
fprintf(stderr, "#%i ERR: Malformed DCD block number!\n",
cmd->lineno);
goto err_dcd;
}
dctx->id = id;
/*
* The DCD block is now constructed. Append it to the list.
* WARNING: The DCD size is still not computed and will be
* updated while parsing it's commands.
*/
if (!ictx->dcd_head) {
ictx->dcd_head = dctx;
ictx->dcd_tail = dctx;
} else {
ictx->dcd_tail->dcd = dctx;
ictx->dcd_tail = dctx;
}
return 0;
err_dcd:
free(dctx->payload);
free(dctx);
return ret;
}
static int sb_build_dcd_block(struct sb_image_ctx *ictx,
struct sb_cmd_list *cmd,
uint32_t type)
{
char *tok;
uint32_t address, value, length;
int ret;
struct sb_dcd_ctx *dctx = ictx->dcd_tail;
uint32_t *dcd;
if (dctx->prev_dcd_head && (type != SB_DCD_NOOP) &&
((dctx->prev_dcd_head[0] & 0xff0000ff) == type)) {
/* Same instruction as before, just append it. */
ret = sb_grow_dcd(dctx, 8);
if (ret)
return ret;
} else if (type == SB_DCD_NOOP) {
ret = sb_grow_dcd(dctx, 4);
if (ret)
return ret;
/* Update DCD command block pointer. */
dctx->prev_dcd_head = dctx->payload +
dctx->size / sizeof(*dctx->payload) - 1;
/* NOOP has only 4 bytes and no payload. */
goto noop;
} else {
/*
* Either a different instruction block started now
* or this is the first instruction block.
*/
ret = sb_grow_dcd(dctx, 12);
if (ret)
return ret;
/* Update DCD command block pointer. */
dctx->prev_dcd_head = dctx->payload +
dctx->size / sizeof(*dctx->payload) - 3;
}
dcd = dctx->payload + dctx->size / sizeof(*dctx->payload) - 2;
/*
* Prepare the command.
*/
tok = strtok(cmd->cmd, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Missing DCD address!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
/* Read DCD destination address. */
ret = sb_token_to_long(tok, &address);
if (ret) {
fprintf(stderr, "#%i ERR: Incorrect DCD address!\n",
cmd->lineno);
goto err;
}
tok = strtok(NULL, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Missing DCD value!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
/* Read DCD operation value. */
ret = sb_token_to_long(tok, &value);
if (ret) {
fprintf(stderr, "#%i ERR: Incorrect DCD value!\n",
cmd->lineno);
goto err;
}
/* Fill in the new DCD entry. */
dcd[0] = htonl(address);
dcd[1] = htonl(value);
noop:
/* Update the DCD command block. */
length = dctx->size -
((dctx->prev_dcd_head - dctx->payload) *
sizeof(*dctx->payload));
dctx->prev_dcd_head[0] = htonl(type | (length << 8));
err:
return ret;
}
static int sb_build_section(struct sb_image_ctx *ictx, struct sb_cmd_list *cmd)
{
struct sb_section_ctx *sctx;
struct sb_sections_header *shdr;
char *tok;
uint32_t bootable = 0;
uint32_t id;
int ret;
sctx = calloc(1, sizeof(*sctx));
if (!sctx)
return -ENOMEM;
/* Read section number. */
tok = strtok(cmd->cmd, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Section without number!\n",
cmd->lineno);
ret = -EINVAL;
goto err_sect;
}
/* Parse the section number. */
ret = sb_token_to_long(tok, &id);
if (ret) {
fprintf(stderr, "#%i ERR: Malformed section number!\n",
cmd->lineno);
goto err_sect;
}
/* Read section's BOOTABLE flag. */
tok = strtok(NULL, " ");
if (tok && (strlen(tok) == 8) && !strncmp(tok, "BOOTABLE", 8))
bootable = SB_SECTION_FLAG_BOOTABLE;
sctx->boot = bootable;
shdr = &sctx->payload;
shdr->section_number = id;
shdr->section_flags = bootable;
/*
* The section is now constructed. Append it to the list.
* WARNING: The section size is still not computed and will
* be updated while parsing it's commands.
*/
ictx->sect_count++;
/* Mark that this section is bootable one. */
if (bootable) {
if (ictx->sect_boot_found) {
fprintf(stderr,
"#%i WARN: Multiple bootable section!\n",
cmd->lineno);
} else {
ictx->sect_boot = id;
ictx->sect_boot_found = 1;
}
}
if (!ictx->sect_head) {
ictx->sect_head = sctx;
ictx->sect_tail = sctx;
} else {
ictx->sect_tail->sect = sctx;
ictx->sect_tail = sctx;
}
return 0;
err_sect:
free(sctx);
return ret;
}
static int sb_build_command_nop(struct sb_image_ctx *ictx)
{
struct sb_section_ctx *sctx = ictx->sect_tail;
struct sb_cmd_ctx *cctx;
struct sb_command *ccmd;
cctx = calloc(1, sizeof(*cctx));
if (!cctx)
return -ENOMEM;
ccmd = &cctx->payload;
/*
* Construct the command.
*/
ccmd->header.checksum = 0x5a;
ccmd->header.tag = ROM_NOP_CMD;
cctx->size = sizeof(*ccmd);
/*
* Append the command to the last section.
*/
if (!sctx->cmd_head) {
sctx->cmd_head = cctx;
sctx->cmd_tail = cctx;
} else {
sctx->cmd_tail->cmd = cctx;
sctx->cmd_tail = cctx;
}
return 0;
}
static int sb_build_command_tag(struct sb_image_ctx *ictx,
struct sb_cmd_list *cmd)
{
struct sb_section_ctx *sctx = ictx->sect_tail;
struct sb_cmd_ctx *cctx;
struct sb_command *ccmd;
char *tok;
cctx = calloc(1, sizeof(*cctx));
if (!cctx)
return -ENOMEM;
ccmd = &cctx->payload;
/*
* Prepare the command.
*/
/* Check for the LAST keyword. */
tok = strtok(cmd->cmd, " ");
if (tok && !strcmp(tok, "LAST"))
ccmd->header.flags = ROM_TAG_CMD_FLAG_ROM_LAST_TAG;
/*
* Construct the command.
*/
ccmd->header.checksum = 0x5a;
ccmd->header.tag = ROM_TAG_CMD;
cctx->size = sizeof(*ccmd);
/*
* Append the command to the last section.
*/
if (!sctx->cmd_head) {
sctx->cmd_head = cctx;
sctx->cmd_tail = cctx;
} else {
sctx->cmd_tail->cmd = cctx;
sctx->cmd_tail = cctx;
}
return 0;
}
static int sb_build_command_load(struct sb_image_ctx *ictx,
struct sb_cmd_list *cmd)
{
struct sb_section_ctx *sctx = ictx->sect_tail;
struct sb_cmd_ctx *cctx;
struct sb_command *ccmd;
char *tok;
int ret, is_ivt = 0, is_dcd = 0;
uint32_t dest, dcd = 0;
cctx = calloc(1, sizeof(*cctx));
if (!cctx)
return -ENOMEM;
ccmd = &cctx->payload;
/*
* Prepare the command.
*/
tok = strtok(cmd->cmd, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Missing LOAD address or 'IVT'!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
/* Check for "IVT" flag. */
if (!strcmp(tok, "IVT"))
is_ivt = 1;
if (!strcmp(tok, "DCD"))
is_dcd = 1;
if (is_ivt || is_dcd) {
tok = strtok(NULL, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Missing LOAD address!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
}
/* Read load destination address. */
ret = sb_token_to_long(tok, &dest);
if (ret) {
fprintf(stderr, "#%i ERR: Incorrect LOAD address!\n",
cmd->lineno);
goto err;
}
/* Read filename or IVT entrypoint or DCD block ID. */
tok = strtok(NULL, " ");
if (!tok) {
fprintf(stderr,
"#%i ERR: Missing LOAD filename or IVT ep or DCD block ID!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
if (is_ivt) {
/* Handle IVT. */
struct sb_ivt_header *ivt;
uint32_t ivtep;
ret = sb_token_to_long(tok, &ivtep);
if (ret) {
fprintf(stderr,
"#%i ERR: Incorrect IVT entry point!\n",
cmd->lineno);
goto err;
}
ivt = calloc(1, sizeof(*ivt));
if (!ivt) {
ret = -ENOMEM;
goto err;
}
ivt->header = sb_hab_ivt_header();
ivt->entry = ivtep;
ivt->self = dest;
cctx->data = (uint8_t *)ivt;
cctx->length = sizeof(*ivt);
} else if (is_dcd) {
struct sb_dcd_ctx *dctx = ictx->dcd_head;
uint32_t dcdid;
uint8_t *payload;
uint32_t asize;
ret = sb_token_to_long(tok, &dcdid);
if (ret) {
fprintf(stderr,
"#%i ERR: Incorrect DCD block ID!\n",
cmd->lineno);
goto err;
}
while (dctx) {
if (dctx->id == dcdid)
break;
dctx = dctx->dcd;
}
if (!dctx) {
fprintf(stderr, "#%i ERR: DCD block %08x not found!\n",
cmd->lineno, dcdid);
goto err;
}
asize = roundup(dctx->size, SB_BLOCK_SIZE);
payload = calloc(1, asize);
if (!payload) {
ret = -ENOMEM;
goto err;
}
memcpy(payload, dctx->payload, dctx->size);
cctx->data = payload;
cctx->length = asize;
/* Set the Load DCD flag. */
dcd = ROM_LOAD_CMD_FLAG_DCD_LOAD;
} else {
/* Regular LOAD of a file. */
ret = sb_load_file(cctx, tok);
if (ret) {
fprintf(stderr, "#%i ERR: Cannot load '%s'!\n",
cmd->lineno, tok);
goto err;
}
}
if (cctx->length & (SB_BLOCK_SIZE - 1)) {
fprintf(stderr, "#%i ERR: Unaligned payload!\n",
cmd->lineno);
}
/*
* Construct the command.
*/
ccmd->header.checksum = 0x5a;
ccmd->header.tag = ROM_LOAD_CMD;
ccmd->header.flags = dcd;
ccmd->load.address = dest;
ccmd->load.count = cctx->length;
ccmd->load.crc32 = pbl_crc32(0,
(const char *)cctx->data,
cctx->length);
cctx->size = sizeof(*ccmd) + cctx->length;
/*
* Append the command to the last section.
*/
if (!sctx->cmd_head) {
sctx->cmd_head = cctx;
sctx->cmd_tail = cctx;
} else {
sctx->cmd_tail->cmd = cctx;
sctx->cmd_tail = cctx;
}
return 0;
err:
free(cctx);
return ret;
}
static int sb_build_command_fill(struct sb_image_ctx *ictx,
struct sb_cmd_list *cmd)
{
struct sb_section_ctx *sctx = ictx->sect_tail;
struct sb_cmd_ctx *cctx;
struct sb_command *ccmd;
char *tok;
uint32_t address, pattern, length;
int ret;
cctx = calloc(1, sizeof(*cctx));
if (!cctx)
return -ENOMEM;
ccmd = &cctx->payload;
/*
* Prepare the command.
*/
tok = strtok(cmd->cmd, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Missing FILL address!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
/* Read fill destination address. */
ret = sb_token_to_long(tok, &address);
if (ret) {
fprintf(stderr, "#%i ERR: Incorrect FILL address!\n",
cmd->lineno);
goto err;
}
tok = strtok(NULL, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Missing FILL pattern!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
/* Read fill pattern address. */
ret = sb_token_to_long(tok, &pattern);
if (ret) {
fprintf(stderr, "#%i ERR: Incorrect FILL pattern!\n",
cmd->lineno);
goto err;
}
tok = strtok(NULL, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Missing FILL length!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
/* Read fill pattern address. */
ret = sb_token_to_long(tok, &length);
if (ret) {
fprintf(stderr, "#%i ERR: Incorrect FILL length!\n",
cmd->lineno);
goto err;
}
/*
* Construct the command.
*/
ccmd->header.checksum = 0x5a;
ccmd->header.tag = ROM_FILL_CMD;
ccmd->fill.address = address;
ccmd->fill.count = length;
ccmd->fill.pattern = pattern;
cctx->size = sizeof(*ccmd);
/*
* Append the command to the last section.
*/
if (!sctx->cmd_head) {
sctx->cmd_head = cctx;
sctx->cmd_tail = cctx;
} else {
sctx->cmd_tail->cmd = cctx;
sctx->cmd_tail = cctx;
}
return 0;
err:
free(cctx);
return ret;
}
static int sb_build_command_jump_call(struct sb_image_ctx *ictx,
struct sb_cmd_list *cmd,
unsigned int is_call)
{
struct sb_section_ctx *sctx = ictx->sect_tail;
struct sb_cmd_ctx *cctx;
struct sb_command *ccmd;
char *tok;
uint32_t dest, arg = 0x0;
uint32_t hab = 0;
int ret;
const char *cmdname = is_call ? "CALL" : "JUMP";
cctx = calloc(1, sizeof(*cctx));
if (!cctx)
return -ENOMEM;
ccmd = &cctx->payload;
/*
* Prepare the command.
*/
tok = strtok(cmd->cmd, " ");
if (!tok) {
fprintf(stderr,
"#%i ERR: Missing %s address or 'HAB'!\n",
cmd->lineno, cmdname);
ret = -EINVAL;
goto err;
}
/* Check for "HAB" flag. */
if (!strcmp(tok, "HAB")) {
hab = is_call ? ROM_CALL_CMD_FLAG_HAB : ROM_JUMP_CMD_FLAG_HAB;
tok = strtok(NULL, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Missing %s address!\n",
cmd->lineno, cmdname);
ret = -EINVAL;
goto err;
}
}
/* Read load destination address. */
ret = sb_token_to_long(tok, &dest);
if (ret) {
fprintf(stderr, "#%i ERR: Incorrect %s address!\n",
cmd->lineno, cmdname);
goto err;
}
tok = strtok(NULL, " ");
if (tok) {
ret = sb_token_to_long(tok, &arg);
if (ret) {
fprintf(stderr,
"#%i ERR: Incorrect %s argument!\n",
cmd->lineno, cmdname);
goto err;
}
}
/*
* Construct the command.
*/
ccmd->header.checksum = 0x5a;
ccmd->header.tag = is_call ? ROM_CALL_CMD : ROM_JUMP_CMD;
ccmd->header.flags = hab;
ccmd->call.address = dest;
ccmd->call.argument = arg;
cctx->size = sizeof(*ccmd);
/*
* Append the command to the last section.
*/
if (!sctx->cmd_head) {
sctx->cmd_head = cctx;
sctx->cmd_tail = cctx;
} else {
sctx->cmd_tail->cmd = cctx;
sctx->cmd_tail = cctx;
}
return 0;
err:
free(cctx);
return ret;
}
static int sb_build_command_jump(struct sb_image_ctx *ictx,
struct sb_cmd_list *cmd)
{
return sb_build_command_jump_call(ictx, cmd, 0);
}
static int sb_build_command_call(struct sb_image_ctx *ictx,
struct sb_cmd_list *cmd)
{
return sb_build_command_jump_call(ictx, cmd, 1);
}
static int sb_build_command_mode(struct sb_image_ctx *ictx,
struct sb_cmd_list *cmd)
{
struct sb_section_ctx *sctx = ictx->sect_tail;
struct sb_cmd_ctx *cctx;
struct sb_command *ccmd;
char *tok;
int ret;
unsigned int i;
uint32_t mode = 0xffffffff;
cctx = calloc(1, sizeof(*cctx));
if (!cctx)
return -ENOMEM;
ccmd = &cctx->payload;
/*
* Prepare the command.
*/
tok = strtok(cmd->cmd, " ");
if (!tok) {
fprintf(stderr, "#%i ERR: Missing MODE boot mode argument!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
for (i = 0; i < ARRAY_SIZE(modetable); i++) {
if (!strcmp(tok, modetable[i].name)) {
mode = modetable[i].mode;
break;
}
if (!modetable[i].altname)
continue;
if (!strcmp(tok, modetable[i].altname)) {
mode = modetable[i].mode;
break;
}
}
if (mode == 0xffffffff) {
fprintf(stderr, "#%i ERR: Invalid MODE boot mode argument!\n",
cmd->lineno);
ret = -EINVAL;
goto err;
}
/*
* Construct the command.
*/
ccmd->header.checksum = 0x5a;
ccmd->header.tag = ROM_MODE_CMD;
ccmd->mode.mode = mode;
cctx->size = sizeof(*ccmd);
/*
* Append the command to the last section.
*/
if (!sctx->cmd_head) {
sctx->cmd_head = cctx;
sctx->cmd_tail = cctx;
} else {
sctx->cmd_tail->cmd = cctx;
sctx->cmd_tail = cctx;
}
return 0;
err:
free(cctx);
return ret;
}
static int sb_prefill_image_header(struct sb_image_ctx *ictx)
{
struct sb_boot_image_header *hdr = &ictx->payload;
/* Fill signatures */
memcpy(hdr->signature1, "STMP", 4);
memcpy(hdr->signature2, "sgtl", 4);
/* SB Image version 1.1 */
hdr->major_version = SB_VERSION_MAJOR;
hdr->minor_version = SB_VERSION_MINOR;
/* Boot image major version */
hdr->product_version.major = htons(0x999);
hdr->product_version.minor = htons(0x999);
hdr->product_version.revision = htons(0x999);
/* Boot image major version */
hdr->component_version.major = htons(0x999);
hdr->component_version.minor = htons(0x999);
hdr->component_version.revision = htons(0x999);
/* Drive tag must be 0x0 for i.MX23 */
hdr->drive_tag = 0;
hdr->header_blocks =
sizeof(struct sb_boot_image_header) / SB_BLOCK_SIZE;
hdr->section_header_size =
sizeof(struct sb_sections_header) / SB_BLOCK_SIZE;
hdr->timestamp_us = sb_get_timestamp() * 1000000;
/* FIXME -- add proper config option */
hdr->flags = ictx->verbose_boot ? SB_IMAGE_FLAG_VERBOSE : 0,
/* FIXME -- We support only default key */
hdr->key_count = 1;
return 0;
}
static int sb_postfill_image_header(struct sb_image_ctx *ictx)
{
struct sb_boot_image_header *hdr = &ictx->payload;
struct sb_section_ctx *sctx = ictx->sect_head;
uint32_t kd_size, sections_blocks;
EVP_MD_CTX md_ctx;
/* The main SB header size in blocks. */
hdr->image_blocks = hdr->header_blocks;
/* Size of the key dictionary, which has single zero entry. */
kd_size = hdr->key_count * sizeof(struct sb_key_dictionary_key);
hdr->image_blocks += kd_size / SB_BLOCK_SIZE;
/* Now count the payloads. */
hdr->section_count = ictx->sect_count;
while (sctx) {
hdr->image_blocks += sctx->size / SB_BLOCK_SIZE;
sctx = sctx->sect;
}
if (!ictx->sect_boot_found) {
fprintf(stderr, "ERR: No bootable section selected!\n");
return -EINVAL;
}
hdr->first_boot_section_id = ictx->sect_boot;
/* The n * SB section size in blocks. */
sections_blocks = hdr->section_count * hdr->section_header_size;
hdr->image_blocks += sections_blocks;
/* Key dictionary offset. */
hdr->key_dictionary_block = hdr->header_blocks + sections_blocks;
/* Digest of the whole image. */
hdr->image_blocks += 2;
/* Pointer past the dictionary. */
hdr->first_boot_tag_block =
hdr->key_dictionary_block + kd_size / SB_BLOCK_SIZE;
/* Compute header digest. */
EVP_MD_CTX_init(&md_ctx);
EVP_DigestInit(&md_ctx, EVP_sha1());
EVP_DigestUpdate(&md_ctx, hdr->signature1,
sizeof(struct sb_boot_image_header) -
sizeof(hdr->digest));
EVP_DigestFinal(&md_ctx, hdr->digest, NULL);
return 0;
}
static int sb_fixup_sections_and_tags(struct sb_image_ctx *ictx)
{
/* Fixup the placement of sections. */
struct sb_boot_image_header *ihdr = &ictx->payload;
struct sb_section_ctx *sctx = ictx->sect_head;
struct sb_sections_header *shdr;
struct sb_cmd_ctx *cctx;
struct sb_command *ccmd;
uint32_t offset = ihdr->first_boot_tag_block;
while (sctx) {
shdr = &sctx->payload;
/* Fill in the section TAG offset. */
shdr->section_offset = offset + 1;
offset += shdr->section_size;
/* Section length is measured from the TAG block. */
shdr->section_size--;
/* Fixup the TAG command. */
cctx = sctx->cmd_head;
while (cctx) {
ccmd = &cctx->payload;
if (ccmd->header.tag == ROM_TAG_CMD) {
ccmd->tag.section_number = shdr->section_number;
ccmd->tag.section_length = shdr->section_size;
ccmd->tag.section_flags = shdr->section_flags;
}
/* Update the command checksum. */
ccmd->header.checksum = sb_command_checksum(ccmd);
cctx = cctx->cmd;
}
sctx = sctx->sect;
}
return 0;
}
static int sb_parse_line(struct sb_image_ctx *ictx, struct sb_cmd_list *cmd)
{
char *tok;
char *line = cmd->cmd;
char *rptr;
int ret;
/* Analyze the identifier on this line first. */
tok = strtok_r(line, " ", &rptr);
if (!tok || (strlen(tok) == 0)) {
fprintf(stderr, "#%i ERR: Invalid line!\n", cmd->lineno);
return -EINVAL;
}
cmd->cmd = rptr;
/* DCD */
if (!strcmp(tok, "DCD")) {
ictx->in_section = 0;
ictx->in_dcd = 1;
sb_build_dcd(ictx, cmd);
return 0;
}
/* Section */
if (!strcmp(tok, "SECTION")) {
ictx->in_section = 1;
ictx->in_dcd = 0;
sb_build_section(ictx, cmd);
return 0;
}
if (!ictx->in_section && !ictx->in_dcd) {
fprintf(stderr, "#%i ERR: Data outside of a section!\n",
cmd->lineno);
return -EINVAL;
}
if (ictx->in_section) {
/* Section commands */
if (!strcmp(tok, "NOP")) {
ret = sb_build_command_nop(ictx);
} else if (!strcmp(tok, "TAG")) {
ret = sb_build_command_tag(ictx, cmd);
} else if (!strcmp(tok, "LOAD")) {
ret = sb_build_command_load(ictx, cmd);
} else if (!strcmp(tok, "FILL")) {
ret = sb_build_command_fill(ictx, cmd);
} else if (!strcmp(tok, "JUMP")) {
ret = sb_build_command_jump(ictx, cmd);
} else if (!strcmp(tok, "CALL")) {
ret = sb_build_command_call(ictx, cmd);
} else if (!strcmp(tok, "MODE")) {
ret = sb_build_command_mode(ictx, cmd);
} else {
fprintf(stderr,
"#%i ERR: Unsupported instruction '%s'!\n",
cmd->lineno, tok);
return -ENOTSUP;
}
} else if (ictx->in_dcd) {
char *lptr;
uint32_t ilen = '1';
tok = strtok_r(tok, ".", &lptr);
if (!tok || (strlen(tok) == 0) || (lptr && strlen(lptr) != 1)) {
fprintf(stderr, "#%i ERR: Invalid line!\n",
cmd->lineno);
return -EINVAL;
}
if (lptr &&
(lptr[0] != '1' && lptr[0] != '2' && lptr[0] != '4')) {
fprintf(stderr, "#%i ERR: Invalid instruction width!\n",
cmd->lineno);
return -EINVAL;
}
if (lptr)
ilen = lptr[0] - '1';
/* DCD commands */
if (!strcmp(tok, "WRITE")) {
ret = sb_build_dcd_block(ictx, cmd,
SB_DCD_WRITE | ilen);
} else if (!strcmp(tok, "ANDC")) {
ret = sb_build_dcd_block(ictx, cmd,
SB_DCD_ANDC | ilen);
} else if (!strcmp(tok, "ORR")) {
ret = sb_build_dcd_block(ictx, cmd,
SB_DCD_ORR | ilen);
} else if (!strcmp(tok, "EQZ")) {
ret = sb_build_dcd_block(ictx, cmd,
SB_DCD_CHK_EQZ | ilen);
} else if (!strcmp(tok, "EQ")) {
ret = sb_build_dcd_block(ictx, cmd,
SB_DCD_CHK_EQ | ilen);
} else if (!strcmp(tok, "NEQ")) {
ret = sb_build_dcd_block(ictx, cmd,
SB_DCD_CHK_NEQ | ilen);
} else if (!strcmp(tok, "NEZ")) {
ret = sb_build_dcd_block(ictx, cmd,
SB_DCD_CHK_NEZ | ilen);
} else if (!strcmp(tok, "NOOP")) {
ret = sb_build_dcd_block(ictx, cmd, SB_DCD_NOOP);
} else {
fprintf(stderr,
"#%i ERR: Unsupported instruction '%s'!\n",
cmd->lineno, tok);
return -ENOTSUP;
}
} else {
fprintf(stderr, "#%i ERR: Unsupported instruction '%s'!\n",
cmd->lineno, tok);
return -ENOTSUP;
}
/*
* Here we have at least one section with one command, otherwise we
* would have failed already higher above.
*
* FIXME -- should the updating happen here ?
*/
if (ictx->in_section && !ret) {
ictx->sect_tail->size += ictx->sect_tail->cmd_tail->size;
ictx->sect_tail->payload.section_size =
ictx->sect_tail->size / SB_BLOCK_SIZE;
}
return ret;
}
static int sb_load_cmdfile(struct sb_image_ctx *ictx)
{
struct sb_cmd_list cmd;
int lineno = 1;
FILE *fp;
char *line = NULL;
ssize_t rlen;
size_t len;
fp = fopen(ictx->cfg_filename, "r");
if (!fp)
goto err_file;
while ((rlen = getline(&line, &len, fp)) > 0) {
memset(&cmd, 0, sizeof(cmd));
/* Strip the trailing newline. */
line[rlen - 1] = '\0';
cmd.cmd = line;
cmd.len = rlen;
cmd.lineno = lineno++;
sb_parse_line(ictx, &cmd);
}
free(line);
fclose(fp);
return 0;
err_file:
fclose(fp);
fprintf(stderr, "ERR: Failed to load file \"%s\"\n",
ictx->cfg_filename);
return -EINVAL;
}
static int sb_build_tree_from_cfg(struct sb_image_ctx *ictx)
{
int ret;
ret = sb_load_cmdfile(ictx);
if (ret)
return ret;
ret = sb_prefill_image_header(ictx);
if (ret)
return ret;
ret = sb_postfill_image_header(ictx);
if (ret)
return ret;
ret = sb_fixup_sections_and_tags(ictx);
if (ret)
return ret;
return 0;
}
static int sb_verify_image_header(struct sb_image_ctx *ictx,
FILE *fp, long fsize)
{
/* Verify static fields in the image header. */
struct sb_boot_image_header *hdr = &ictx->payload;
const char *stat[2] = { "[PASS]", "[FAIL]" };
struct tm tm;
int sz, ret = 0;
unsigned char digest[20];
EVP_MD_CTX md_ctx;
unsigned long size;
/* Start image-wide crypto. */
EVP_MD_CTX_init(&ictx->md_ctx);
EVP_DigestInit(&ictx->md_ctx, EVP_sha1());
soprintf(ictx, "---------- Verifying SB Image Header ----------\n");
size = fread(&ictx->payload, 1, sizeof(ictx->payload), fp);
if (size != sizeof(ictx->payload)) {
fprintf(stderr, "ERR: SB image header too short!\n");
return -EINVAL;
}
/* Compute header digest. */
EVP_MD_CTX_init(&md_ctx);
EVP_DigestInit(&md_ctx, EVP_sha1());
EVP_DigestUpdate(&md_ctx, hdr->signature1,
sizeof(struct sb_boot_image_header) -
sizeof(hdr->digest));
EVP_DigestFinal(&md_ctx, digest, NULL);
sb_aes_init(ictx, NULL, 1);
sb_encrypt_sb_header(ictx);
if (memcmp(digest, hdr->digest, 20))
ret = -EINVAL;
soprintf(ictx, "%s Image header checksum: %s\n", stat[!!ret],
ret ? "BAD" : "OK");
if (ret)
return ret;
if (memcmp(hdr->signature1, "STMP", 4) ||
memcmp(hdr->signature2, "sgtl", 4))
ret = -EINVAL;
soprintf(ictx, "%s Signatures: '%.4s' '%.4s'\n",
stat[!!ret], hdr->signature1, hdr->signature2);
if (ret)
return ret;
if ((hdr->major_version != SB_VERSION_MAJOR) ||
((hdr->minor_version != 1) && (hdr->minor_version != 2)))
ret = -EINVAL;
soprintf(ictx, "%s Image version: v%i.%i\n", stat[!!ret],
hdr->major_version, hdr->minor_version);
if (ret)
return ret;
ret = sb_get_time(hdr->timestamp_us / 1000000, &tm);
soprintf(ictx,
"%s Creation time: %02i:%02i:%02i %02i/%02i/%04i\n",
stat[!!ret], tm.tm_hour, tm.tm_min, tm.tm_sec,
tm.tm_mday, tm.tm_mon, tm.tm_year + 2000);
if (ret)
return ret;
soprintf(ictx, "%s Product version: %x.%x.%x\n", stat[0],
ntohs(hdr->product_version.major),
ntohs(hdr->product_version.minor),
ntohs(hdr->product_version.revision));
soprintf(ictx, "%s Component version: %x.%x.%x\n", stat[0],
ntohs(hdr->component_version.major),
ntohs(hdr->component_version.minor),
ntohs(hdr->component_version.revision));
if (hdr->flags & ~SB_IMAGE_FLAG_VERBOSE)
ret = -EINVAL;
soprintf(ictx, "%s Image flags: %s\n", stat[!!ret],
hdr->flags & SB_IMAGE_FLAG_VERBOSE ? "Verbose_boot" : "");
if (ret)
return ret;
if (hdr->drive_tag != 0)
ret = -EINVAL;
soprintf(ictx, "%s Drive tag: %i\n", stat[!!ret],
hdr->drive_tag);
if (ret)
return ret;
sz = sizeof(struct sb_boot_image_header) / SB_BLOCK_SIZE;
if (hdr->header_blocks != sz)
ret = -EINVAL;
soprintf(ictx, "%s Image header size (blocks): %i\n", stat[!!ret],
hdr->header_blocks);
if (ret)
return ret;
sz = sizeof(struct sb_sections_header) / SB_BLOCK_SIZE;
if (hdr->section_header_size != sz)
ret = -EINVAL;
soprintf(ictx, "%s Section header size (blocks): %i\n", stat[!!ret],
hdr->section_header_size);
if (ret)
return ret;
soprintf(ictx, "%s Sections count: %i\n", stat[!!ret],
hdr->section_count);
soprintf(ictx, "%s First bootable section %i\n", stat[!!ret],
hdr->first_boot_section_id);
if (hdr->image_blocks != fsize / SB_BLOCK_SIZE)
ret = -EINVAL;
soprintf(ictx, "%s Image size (blocks): %i\n", stat[!!ret],
hdr->image_blocks);
if (ret)
return ret;
sz = hdr->header_blocks + hdr->section_header_size * hdr->section_count;
if (hdr->key_dictionary_block != sz)
ret = -EINVAL;
soprintf(ictx, "%s Key dict offset (blocks): %i\n", stat[!!ret],
hdr->key_dictionary_block);
if (ret)
return ret;
if (hdr->key_count != 1)
ret = -EINVAL;
soprintf(ictx, "%s Number of encryption keys: %i\n", stat[!!ret],
hdr->key_count);
if (ret)
return ret;
sz = hdr->header_blocks + hdr->section_header_size * hdr->section_count;
sz += hdr->key_count *
sizeof(struct sb_key_dictionary_key) / SB_BLOCK_SIZE;
if (hdr->first_boot_tag_block != (unsigned)sz)
ret = -EINVAL;
soprintf(ictx, "%s First TAG block (blocks): %i\n", stat[!!ret],
hdr->first_boot_tag_block);
if (ret)
return ret;
return 0;
}
static void sb_decrypt_tag(struct sb_image_ctx *ictx,
struct sb_cmd_ctx *cctx)
{
EVP_MD_CTX *md_ctx = &ictx->md_ctx;
struct sb_command *cmd = &cctx->payload;
sb_aes_crypt(ictx, (uint8_t *)&cctx->c_payload,
(uint8_t *)&cctx->payload, sizeof(*cmd));
EVP_DigestUpdate(md_ctx, &cctx->c_payload, sizeof(*cmd));
}
static int sb_verify_command(struct sb_image_ctx *ictx,
struct sb_cmd_ctx *cctx, FILE *fp,
unsigned long *tsize)
{
struct sb_command *ccmd = &cctx->payload;
unsigned long size, asize;
char *csum, *flag = "";
int ret;
unsigned int i;
uint8_t csn, csc = ccmd->header.checksum;
ccmd->header.checksum = 0x5a;
csn = sb_command_checksum(ccmd);
ccmd->header.checksum = csc;
if (csc == csn)
ret = 0;
else
ret = -EINVAL;
csum = ret ? "checksum BAD" : "checksum OK";
switch (ccmd->header.tag) {
case ROM_NOP_CMD:
soprintf(ictx, " NOOP # %s\n", csum);
return ret;
case ROM_TAG_CMD:
if (ccmd->header.flags & ROM_TAG_CMD_FLAG_ROM_LAST_TAG)
flag = "LAST";
soprintf(ictx, " TAG %s # %s\n", flag, csum);
sb_aes_reinit(ictx, 0);
return ret;
case ROM_LOAD_CMD:
soprintf(ictx, " LOAD addr=0x%08x length=0x%08x # %s\n",
ccmd->load.address, ccmd->load.count, csum);
cctx->length = ccmd->load.count;
asize = roundup(cctx->length, SB_BLOCK_SIZE);
cctx->data = malloc(asize);
if (!cctx->data)
return -ENOMEM;
size = fread(cctx->data, 1, asize, fp);
if (size != asize) {
fprintf(stderr,
"ERR: SB LOAD command payload too short!\n");
return -EINVAL;
}
*tsize += size;
EVP_DigestUpdate(&ictx->md_ctx, cctx->data, asize);
sb_aes_crypt(ictx, cctx->data, cctx->data, asize);
if (ccmd->load.crc32 != pbl_crc32(0,
(const char *)cctx->data,
asize)) {
fprintf(stderr,
"ERR: SB LOAD command payload CRC32 invalid!\n");
return -EINVAL;
}
return 0;
case ROM_FILL_CMD:
soprintf(ictx,
" FILL addr=0x%08x length=0x%08x pattern=0x%08x # %s\n",
ccmd->fill.address, ccmd->fill.count,
ccmd->fill.pattern, csum);
return 0;
case ROM_JUMP_CMD:
if (ccmd->header.flags & ROM_JUMP_CMD_FLAG_HAB)
flag = " HAB";
soprintf(ictx,
" JUMP%s addr=0x%08x r0_arg=0x%08x # %s\n",
flag, ccmd->fill.address, ccmd->jump.argument, csum);
return 0;
case ROM_CALL_CMD:
if (ccmd->header.flags & ROM_CALL_CMD_FLAG_HAB)
flag = " HAB";
soprintf(ictx,
" CALL%s addr=0x%08x r0_arg=0x%08x # %s\n",
flag, ccmd->fill.address, ccmd->jump.argument, csum);
return 0;
case ROM_MODE_CMD:
for (i = 0; i < ARRAY_SIZE(modetable); i++) {
if (ccmd->mode.mode == modetable[i].mode) {
soprintf(ictx, " MODE %s # %s\n",
modetable[i].name, csum);
break;
}
}
fprintf(stderr, " MODE !INVALID! # %s\n", csum);
return 0;
}
return ret;
}
static int sb_verify_commands(struct sb_image_ctx *ictx,
struct sb_section_ctx *sctx, FILE *fp)
{
unsigned long size, tsize = 0;
struct sb_cmd_ctx *cctx;
int ret;
sb_aes_reinit(ictx, 0);
while (tsize < sctx->size) {
cctx = calloc(1, sizeof(*cctx));
if (!cctx)
return -ENOMEM;
if (!sctx->cmd_head) {
sctx->cmd_head = cctx;
sctx->cmd_tail = cctx;
} else {
sctx->cmd_tail->cmd = cctx;
sctx->cmd_tail = cctx;
}
size = fread(&cctx->c_payload, 1, sizeof(cctx->c_payload), fp);
if (size != sizeof(cctx->c_payload)) {
fprintf(stderr, "ERR: SB command header too short!\n");
return -EINVAL;
}
tsize += size;
sb_decrypt_tag(ictx, cctx);
ret = sb_verify_command(ictx, cctx, fp, &tsize);
if (ret)
return -EINVAL;
}
return 0;
}
static int sb_verify_sections_cmds(struct sb_image_ctx *ictx, FILE *fp)
{
struct sb_boot_image_header *hdr = &ictx->payload;
struct sb_sections_header *shdr;
unsigned int i;
int ret;
struct sb_section_ctx *sctx;
unsigned long size;
char *bootable = "";
soprintf(ictx, "----- Verifying SB Sections and Commands -----\n");
for (i = 0; i < hdr->section_count; i++) {
sctx = calloc(1, sizeof(*sctx));
if (!sctx)
return -ENOMEM;
if (!ictx->sect_head) {
ictx->sect_head = sctx;
ictx->sect_tail = sctx;
} else {
ictx->sect_tail->sect = sctx;
ictx->sect_tail = sctx;
}
size = fread(&sctx->payload, 1, sizeof(sctx->payload), fp);
if (size != sizeof(sctx->payload)) {
fprintf(stderr, "ERR: SB section header too short!\n");
return -EINVAL;
}
}
size = fread(&ictx->sb_dict_key, 1, sizeof(ictx->sb_dict_key), fp);
if (size != sizeof(ictx->sb_dict_key)) {
fprintf(stderr, "ERR: SB key dictionary too short!\n");
return -EINVAL;
}
sb_encrypt_sb_sections_header(ictx);
sb_aes_reinit(ictx, 0);
sb_decrypt_key_dictionary_key(ictx);
sb_aes_reinit(ictx, 0);
sctx = ictx->sect_head;
while (sctx) {
shdr = &sctx->payload;
if (shdr->section_flags & SB_SECTION_FLAG_BOOTABLE) {
sctx->boot = 1;
bootable = " BOOTABLE";
}
sctx->size = (shdr->section_size * SB_BLOCK_SIZE) +
sizeof(struct sb_command);
soprintf(ictx, "SECTION 0x%x%s # size = %i bytes\n",
shdr->section_number, bootable, sctx->size);
if (shdr->section_flags & ~SB_SECTION_FLAG_BOOTABLE)
fprintf(stderr, " WARN: Unknown section flag(s) %08x\n",
shdr->section_flags);
if ((shdr->section_flags & SB_SECTION_FLAG_BOOTABLE) &&
(hdr->first_boot_section_id != shdr->section_number)) {
fprintf(stderr,
" WARN: Bootable section does ID not match image header ID!\n");
}
ret = sb_verify_commands(ictx, sctx, fp);
if (ret)
return ret;
sctx = sctx->sect;
}
/*
* FIXME IDEA:
* check if the first TAG command is at sctx->section_offset
*/
return 0;
}
static int sb_verify_image_end(struct sb_image_ctx *ictx,
FILE *fp, off_t filesz)
{
uint8_t digest[32];
unsigned long size;
off_t pos;
int ret;
soprintf(ictx, "------------- Verifying image end -------------\n");
size = fread(digest, 1, sizeof(digest), fp);
if (size != sizeof(digest)) {
fprintf(stderr, "ERR: SB key dictionary too short!\n");
return -EINVAL;
}
pos = ftell(fp);
if (pos != filesz) {
fprintf(stderr, "ERR: Trailing data past the image!\n");
return -EINVAL;
}
/* Check the image digest. */
EVP_DigestFinal(&ictx->md_ctx, ictx->digest, NULL);
/* Decrypt the image digest from the input image. */
sb_aes_reinit(ictx, 0);
sb_aes_crypt(ictx, digest, digest, sizeof(digest));
/* Check all of 20 bytes of the SHA1 hash. */
ret = memcmp(digest, ictx->digest, 20) ? -EINVAL : 0;
if (ret)
soprintf(ictx, "[FAIL] Full-image checksum: BAD\n");
else
soprintf(ictx, "[PASS] Full-image checksum: OK\n");
return ret;
}
static int sb_build_tree_from_img(struct sb_image_ctx *ictx)
{
long filesize;
int ret;
FILE *fp;
if (!ictx->input_filename) {
fprintf(stderr, "ERR: Missing filename!\n");
return -EINVAL;
}
fp = fopen(ictx->input_filename, "r");
if (!fp)
goto err_open;
ret = fseek(fp, 0, SEEK_END);
if (ret < 0)
goto err_file;
filesize = ftell(fp);
if (filesize < 0)
goto err_file;
ret = fseek(fp, 0, SEEK_SET);
if (ret < 0)
goto err_file;
if (filesize < (signed)sizeof(ictx->payload)) {
fprintf(stderr, "ERR: File too short!\n");
goto err_file;
}
if (filesize & (SB_BLOCK_SIZE - 1)) {
fprintf(stderr, "ERR: The file is not aligned!\n");
goto err_file;
}
/* Load and verify image header */
ret = sb_verify_image_header(ictx, fp, filesize);
if (ret)
goto err_verify;
/* Load and verify sections and commands */
ret = sb_verify_sections_cmds(ictx, fp);
if (ret)
goto err_verify;
ret = sb_verify_image_end(ictx, fp, filesize);
if (ret)
goto err_verify;
ret = 0;
err_verify:
soprintf(ictx, "-------------------- Result -------------------\n");
soprintf(ictx, "Verification %s\n", ret ? "FAILED" : "PASSED");
/* Stop the encryption session. */
sb_aes_deinit(&ictx->cipher_ctx);
fclose(fp);
return ret;
err_file:
fclose(fp);
err_open:
fprintf(stderr, "ERR: Failed to load file \"%s\"\n",
ictx->input_filename);
return -EINVAL;
}
static void sb_free_image(struct sb_image_ctx *ictx)
{
struct sb_section_ctx *sctx = ictx->sect_head, *s_head;
struct sb_dcd_ctx *dctx = ictx->dcd_head, *d_head;
struct sb_cmd_ctx *cctx, *c_head;
while (sctx) {
s_head = sctx;
c_head = sctx->cmd_head;
while (c_head) {
cctx = c_head;
c_head = c_head->cmd;
if (cctx->data)
free(cctx->data);
free(cctx);
}
sctx = sctx->sect;
free(s_head);
}
while (dctx) {
d_head = dctx;
dctx = dctx->dcd;
free(d_head->payload);
free(d_head);
}
}
/*
* MXSSB-MKIMAGE glue code.
*/
static int mxsimage_check_image_types(uint8_t type)
{
if (type == IH_TYPE_MXSIMAGE)
return EXIT_SUCCESS;
else
return EXIT_FAILURE;
}
static void mxsimage_set_header(void *ptr, struct stat *sbuf, int ifd,
struct image_tool_params *params)
{
}
int mxsimage_check_params(struct image_tool_params *params)
{
if (!params)
return -1;
if (!strlen(params->imagename)) {
fprintf(stderr,
"Error: %s - Configuration file not specified, it is needed for mxsimage generation\n",
params->cmdname);
return -1;
}
/*
* Check parameters:
* XIP is not allowed and verify that incompatible
* parameters are not sent at the same time
* For example, if list is required a data image must not be provided
*/
return (params->dflag && (params->fflag || params->lflag)) ||
(params->fflag && (params->dflag || params->lflag)) ||
(params->lflag && (params->dflag || params->fflag)) ||
(params->xflag) || !(strlen(params->imagename));
}
static int mxsimage_verify_print_header(char *file, int silent)
{
int ret;
struct sb_image_ctx ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.input_filename = file;
ctx.silent_dump = silent;
ret = sb_build_tree_from_img(&ctx);
sb_free_image(&ctx);
return ret;
}
char *imagefile;
static int mxsimage_verify_header(unsigned char *ptr, int image_size,
struct image_tool_params *params)
{
struct sb_boot_image_header *hdr;
if (!ptr)
return -EINVAL;
hdr = (struct sb_boot_image_header *)ptr;
/*
* Check if the header contains the MXS image signatures,
* if so, do a full-image verification.
*/
if (memcmp(hdr->signature1, "STMP", 4) ||
memcmp(hdr->signature2, "sgtl", 4))
return -EINVAL;
imagefile = params->imagefile;
return mxsimage_verify_print_header(params->imagefile, 1);
}
static void mxsimage_print_header(const void *hdr)
{
if (imagefile)
mxsimage_verify_print_header(imagefile, 0);
}
static int sb_build_image(struct sb_image_ctx *ictx,
struct image_type_params *tparams)
{
struct sb_boot_image_header *sb_header = &ictx->payload;
struct sb_section_ctx *sctx;
struct sb_cmd_ctx *cctx;
struct sb_command *ccmd;
struct sb_key_dictionary_key *sb_dict_key = &ictx->sb_dict_key;
uint8_t *image, *iptr;
/* Calculate image size. */
uint32_t size = sizeof(*sb_header) +
ictx->sect_count * sizeof(struct sb_sections_header) +
sizeof(*sb_dict_key) + sizeof(ictx->digest);
sctx = ictx->sect_head;
while (sctx) {
size += sctx->size;
sctx = sctx->sect;
};
image = malloc(size);
if (!image)
return -ENOMEM;
iptr = image;
memcpy(iptr, sb_header, sizeof(*sb_header));
iptr += sizeof(*sb_header);
sctx = ictx->sect_head;
while (sctx) {
memcpy(iptr, &sctx->payload, sizeof(struct sb_sections_header));
iptr += sizeof(struct sb_sections_header);
sctx = sctx->sect;
};
memcpy(iptr, sb_dict_key, sizeof(*sb_dict_key));
iptr += sizeof(*sb_dict_key);
sctx = ictx->sect_head;
while (sctx) {
cctx = sctx->cmd_head;
while (cctx) {
ccmd = &cctx->payload;
memcpy(iptr, &cctx->c_payload, sizeof(cctx->payload));
iptr += sizeof(cctx->payload);
if (ccmd->header.tag == ROM_LOAD_CMD) {
memcpy(iptr, cctx->data, cctx->length);
iptr += cctx->length;
}
cctx = cctx->cmd;
}
sctx = sctx->sect;
};
memcpy(iptr, ictx->digest, sizeof(ictx->digest));
iptr += sizeof(ictx->digest);
/* Configure the mkimage */
tparams->hdr = image;
tparams->header_size = size;
return 0;
}
static int mxsimage_generate(struct image_tool_params *params,
struct image_type_params *tparams)
{
int ret;
struct sb_image_ctx ctx;
/* Do not copy the U-Boot image! */
params->skipcpy = 1;
memset(&ctx, 0, sizeof(ctx));
ctx.cfg_filename = params->imagename;
ctx.output_filename = params->imagefile;
ctx.verbose_boot = 1;
ret = sb_build_tree_from_cfg(&ctx);
if (ret)
goto fail;
ret = sb_encrypt_image(&ctx);
if (!ret)
ret = sb_build_image(&ctx, tparams);
fail:
sb_free_image(&ctx);
return ret;
}
/*
* mxsimage parameters
*/
static struct image_type_params mxsimage_params = {
.name = "Freescale MXS Boot Image support",
.header_size = 0,
.hdr = NULL,
.check_image_type = mxsimage_check_image_types,
.verify_header = mxsimage_verify_header,
.print_header = mxsimage_print_header,
.set_header = mxsimage_set_header,
.check_params = mxsimage_check_params,
.vrec_header = mxsimage_generate,
};
void init_mxs_image_type(void)
{
register_image_type(&mxsimage_params);
}
#else
void init_mxs_image_type(void)
{
}
#endif
|
the_stack_data/107952973.c | #include <stdio.h>
int main()
{
int a,b;
printf("Enter First No =");
scanf("%d",&a);
printf("Enter Second No =");
scanf("%d",&b);
int add=a+b;
printf("\n Addition Is =%d",add);
int mul=a*b;
printf("\n Multiplication Is =%d",mul);
float div1=a/b;
printf("\n Division Is =%f",div1);
int rem=a%b;
printf("\n Reminder Is =%d",rem);
} |
the_stack_data/102037.c | extern void abort (void);
extern void exit (int);
typedef __SIZE_TYPE__ size_t;
int
main (void)
{
int a = 0;
int *p;
size_t b;
b = (size_t)(p = &(int []){0, 1, 2}[1]);
if (*p != 1 || *(int *)b != 1)
abort ();
exit (0);
}
|
the_stack_data/162643771.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* match.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jde-oliv <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/24 11:00:37 by jde-oliv #+# #+# */
/* Updated: 2018/03/24 11:00:39 by jde-oliv ### ########.fr */
/* */
/* ************************************************************************** */
int length(char *str)
{
int len;
len = 0;
while (str[len])
len++;
return (len);
}
int last_occurancy_of_i(char *str, int i)
{
int j;
j = length(str);
while (str[j] != str[i])
j--;
return (j);
}
int match(char *s1, char *s2)
{
int i;
int j;
i = 0;
j = 0;
while (s1[i] || s2[j])
{
while (s2[j] == '*')
{
while ((s2[j + 1] != s1[i]) && s1[i])
i++;
i = last_occurancy_of_i(s1, i);
j++;
}
if (s1[i] == s2[j] && s1[i])
{
i++;
j++;
}
else if (s1[i] != s2[j])
return (0);
}
return (1);
}
|
the_stack_data/182953762.c | #include <stdio.h>
int main(int argc, char *argv[]) {
printf("%s","Lol");
} |
the_stack_data/67323949.c | // Copyright (c) 2016 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#include <netinet/in.h>
#ifndef IN6_IS_ADDR_MULTICAST
#error "IN6_IS_ADDR_MULTICAST is supposed to be a macro as well"
#endif
// clang-format off
int (IN6_IS_ADDR_MULTICAST)(const struct in6_addr *a) {
return IN6_IS_ADDR_MULTICAST(a);
}
|
the_stack_data/198580519.c |
extern const char *_mesa_lookup_enum_by_nr( int nr )
{
return "";
}
const char *_mesa_lookup_prim_by_nr( unsigned nr )
{
return "";
}
|
the_stack_data/151706119.c | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
PURPOSE.
Module Name:
IOCTL.C
Abstract:
This modules contains functions to register/deregsiter a control-
deviceobject for ioctl purposes and dispatch routine for handling
ioctl requests from usermode.
Revision History:
Notes:
--*/
#if defined(IOCTL_INTERFACE)
#include "miniport.h"
#include "public.h"
//
// Simple Mutual Exclusion constructs used in preference to
// using KeXXX calls since we don't have Mutex calls in NDIS.
// These can only be called at passive IRQL.
//
typedef struct _NIC_MUTEX
{
ULONG Counter;
ULONG ModuleAndLine; // useful for debugging
} NIC_MUTEX, *PNIC_MUTEX;
#define NIC_INIT_MUTEX(_pMutex) \
{ \
(_pMutex)->Counter = 0; \
(_pMutex)->ModuleAndLine = 0; \
}
#define NIC_ACQUIRE_MUTEX(_pMutex) \
{ \
while (NdisInterlockedIncrement((PLONG)&((_pMutex)->Counter)) != 1)\
{ \
NdisInterlockedDecrement((PLONG)&((_pMutex)->Counter)); \
NdisMSleep(10000); \
} \
(_pMutex)->ModuleAndLine = ('I' << 16) | __LINE__;\
}
#define NIC_RELEASE_MUTEX(_pMutex) \
{ \
(_pMutex)->ModuleAndLine = 0; \
NdisInterlockedDecrement((PLONG)&(_pMutex)->Counter); \
}
#define LINKNAME_STRING L"\\DosDevices\\NETVMINI"
#define NTDEVICE_STRING L"\\Device\\NETVMINI"
//
// Global variables
//
NDIS_HANDLE NdisDeviceHandle = NULL; // From NdisMRegisterDevice
LONG MiniportCount = 0; // Total number of miniports in existance
PDEVICE_OBJECT ControlDeviceObject = NULL; // Device for IOCTLs
NIC_MUTEX ControlDeviceMutex;
extern NDIS_HANDLE NdisWrapperHandle;
#pragma NDIS_PAGEABLE_FUNCTION(NICRegisterDevice)
#pragma NDIS_PAGEABLE_FUNCTION(NICDeregisterDevice)
#pragma NDIS_PAGEABLE_FUNCTION(NICDispatch)
NDIS_STATUS
NICRegisterDevice(
VOID
)
/*++
Routine Description:
Register an ioctl interface - a device object to be used for this
purpose is created by NDIS when we call NdisMRegisterDevice.
This routine is called whenever a new miniport instance is
initialized. However, we only create one global device object,
when the first miniport instance is initialized. This routine
handles potential race conditions with NICDeregisterDevice via
the ControlDeviceMutex.
NOTE: do not call this from DriverEntry; it will prevent the driver
from being unloaded (e.g. on uninstall).
Arguments:
None
Return Value:
NDIS_STATUS_SUCCESS if we successfully register a device object.
--*/
{
NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
UNICODE_STRING DeviceName;
UNICODE_STRING DeviceLinkUnicodeString;
PDRIVER_DISPATCH DispatchTable[IRP_MJ_MAXIMUM_FUNCTION+1];
DEBUGP(MP_TRACE, ("==>NICRegisterDevice\n"));
NIC_ACQUIRE_MUTEX(&ControlDeviceMutex);
++MiniportCount;
if (1 == MiniportCount)
{
NdisZeroMemory(DispatchTable, (IRP_MJ_MAXIMUM_FUNCTION+1) * sizeof(PDRIVER_DISPATCH));
DispatchTable[IRP_MJ_CREATE] = NICDispatch;
DispatchTable[IRP_MJ_CLEANUP] = NICDispatch;
DispatchTable[IRP_MJ_CLOSE] = NICDispatch;
DispatchTable[IRP_MJ_DEVICE_CONTROL] = NICDispatch;
NdisInitUnicodeString(&DeviceName, NTDEVICE_STRING);
NdisInitUnicodeString(&DeviceLinkUnicodeString, LINKNAME_STRING);
//
// Create a device object and register our dispatch handlers
//
Status = NdisMRegisterDevice(
NdisWrapperHandle,
&DeviceName,
&DeviceLinkUnicodeString,
&DispatchTable[0],
&ControlDeviceObject,
&NdisDeviceHandle
);
}
NIC_RELEASE_MUTEX(&ControlDeviceMutex);
DEBUGP(MP_TRACE, ("<==NICRegisterDevice: %x\n", Status));
return (Status);
}
NTSTATUS
NICDispatch(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
/*++
Routine Description:
Process IRPs sent to this device.
Arguments:
DeviceObject - pointer to a device object
Irp - pointer to an I/O Request Packet
Return Value:
NTSTATUS - STATUS_SUCCESS always - change this when adding
real code to handle ioctls.
--*/
{
PIO_STACK_LOCATION irpStack;
NTSTATUS status = STATUS_SUCCESS;
ULONG inlen;
PVOID buffer;
irpStack = IoGetCurrentIrpStackLocation(Irp);
DEBUGP(MP_TRACE, ("==>NICDispatch %d\n", irpStack->MajorFunction));
switch (irpStack->MajorFunction)
{
case IRP_MJ_CREATE:
break;
case IRP_MJ_CLEANUP:
break;
case IRP_MJ_CLOSE:
break;
case IRP_MJ_DEVICE_CONTROL:
{
buffer = Irp->AssociatedIrp.SystemBuffer;
inlen = irpStack->Parameters.DeviceIoControl.InputBufferLength;
switch (irpStack->Parameters.DeviceIoControl.IoControlCode)
{
//
// Add code here to handle ioctl commands.
//
case IOCTL_NETVMINI_READ_DATA:
DEBUGP(MP_TRACE, ("Received Read IOCTL\n"));
break;
case IOCTL_NETVMINI_WRITE_DATA:
DEBUGP(MP_TRACE, ("Received Write IOCTL\n"));
break;
default:
status = STATUS_UNSUCCESSFUL;
break;
}
break;
}
default:
break;
}
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
DEBUGP(MP_TRACE, ("<== NIC Dispatch\n"));
return status;
}
NDIS_STATUS
NICDeregisterDevice(
VOID
)
/*++
Routine Description:
Deregister the ioctl interface. This is called whenever a miniport
instance is halted. When the last miniport instance is halted, we
request NDIS to delete the device object
Arguments:
NdisDeviceHandle - Handle returned by NdisMRegisterDevice
Return Value:
NDIS_STATUS_SUCCESS if everything worked ok
--*/
{
NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
DEBUGP(MP_TRACE, ("==>NICDeregisterDevice\n"));
NIC_ACQUIRE_MUTEX(&ControlDeviceMutex);
ASSERT(MiniportCount > 0);
--MiniportCount;
if (0 == MiniportCount)
{
//
// All miniport instances have been halted.
// Deregister the control device.
//
if (NdisDeviceHandle != NULL)
{
Status = NdisMDeregisterDevice(NdisDeviceHandle);
NdisDeviceHandle = NULL;
}
}
NIC_RELEASE_MUTEX(&ControlDeviceMutex);
DEBUGP(MP_TRACE, ("<== NICDeregisterDevice: %x\n", Status));
return Status;
}
#endif
|
the_stack_data/37637207.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_isprint.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbeall <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/25 11:38:58 by jbeall #+# #+# */
/* Updated: 2018/10/30 11:03:50 by jbeall ### ########.fr */
/* */
/* ************************************************************************** */
int ft_isprint(int c)
{
if (c >= 32 && c <= 126)
return (1);
else
return (0);
}
|
the_stack_data/911088.c | #ifdef INTERFACE
void CheckBox_Click(entity me, entity other);
CLASS(CheckBox) EXTENDS(Button)
METHOD(CheckBox, configureCheckBox, void(entity, string, float, string))
METHOD(CheckBox, draw, void(entity))
METHOD(CheckBox, toString, string(entity))
METHOD(CheckBox, setChecked, void(entity, float))
ATTRIB(CheckBox, useDownAsChecked, float, 0)
ATTRIB(CheckBox, checked, float, 0)
ATTRIB(CheckBox, onClick, void(entity, entity), CheckBox_Click)
ATTRIB(CheckBox, srcMulti, float, 0)
ATTRIB(CheckBox, disabled, float, 0)
ENDCLASS(CheckBox)
#endif
#ifdef IMPLEMENTATION
void setCheckedCheckBox(entity me, float val)
{
me.checked = val;
}
void CheckBox_Click(entity me, entity other)
{
me.setChecked(me, !me.checked);
}
string toStringCheckBox(entity me)
{
return strcat(toStringLabel(me), ", ", me.checked ? "checked" : "unchecked");
}
void configureCheckBoxCheckBox(entity me, string txt, float sz, string gfx)
{
me.configureButton(me, txt, sz, gfx);
me.align = 0;
}
void drawCheckBox(entity me)
{
float s;
s = me.pressed;
if(me.useDownAsChecked)
{
me.srcSuffix = string_null;
me.forcePressed = me.checked;
}
else
me.srcSuffix = (me.checked ? "1" : "0");
drawButton(me);
me.pressed = s;
}
#endif
|
the_stack_data/161079818.c | /*
* Copyright (c) 2017 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <pthread.h>
#ifdef __APPLE__
// Spinlocks do not exist on mac
typedef struct {
int __whatever;
} pthread_spinlock_t;
extern int pthread_spin_init(pthread_spinlock_t *__lock, int __pshared);
extern int pthread_spin_destroy (pthread_spinlock_t *__lock);
extern int pthread_spin_lock (pthread_spinlock_t *__lock);
extern int pthread_spin_trylock (pthread_spinlock_t *__lock);
extern int pthread_spin_unlock (pthread_spinlock_t *__lock);
#endif
void spinlock_double_lock_bad(pthread_spinlock_t* m) {
pthread_spin_lock(m);
pthread_spin_lock(m);
}
void spinlock_double_lock_bad2() {
pthread_spinlock_t m;
spinlock_double_lock_bad(&m);
}
|
the_stack_data/11074911.c | #include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define ONE_K (1024)
int main() {
char *some_memory;
int size_to_allocate = ONE_K;
int megs_obtained = 0;
int ks_obtained = 0;
while (1) {
for (ks_obtained = 0; ks_obtained < 1024; ks_obtained++) {
some_memory = (char *)malloc(size_to_allocate);
if (some_memory == NULL) exit(EXIT_FAILURE);
sprintf(some_memory, "Hello World");
}
megs_obtained++;
printf("Now allocated %d Megabytes\n", megs_obtained);
}
exit(EXIT_SUCCESS);
}
|
the_stack_data/198581691.c | /* Code generated from eC source file: memory.ec */
#if defined(_WIN32)
#define __runtimePlatform 1
#elif defined(__APPLE__)
#define __runtimePlatform 3
#else
#define __runtimePlatform 2
#endif
#if defined(__GNUC__) || defined(__clang__)
#if defined(__clang__) && defined(__WIN32__)
#define int64 long long
#define uint64 unsigned long long
#if defined(_WIN64)
#define ssize_t long long
#else
#define ssize_t long
#endif
#else
typedef long long int64;
typedef unsigned long long uint64;
#endif
#ifndef _WIN32
#define __declspec(x)
#endif
#elif defined(__TINYC__)
#include <stdarg.h>
#define __builtin_va_list va_list
#define __builtin_va_start va_start
#define __builtin_va_end va_end
#ifdef _WIN32
#define strcasecmp stricmp
#define strncasecmp strnicmp
#define __declspec(x) __attribute__((x))
#else
#define __declspec(x)
#endif
typedef long long int64;
typedef unsigned long long uint64;
#else
typedef __int64 int64;
typedef unsigned __int64 uint64;
#endif
#ifdef __BIG_ENDIAN__
#define __ENDIAN_PAD(x) (8 - (x))
#else
#define __ENDIAN_PAD(x) 0
#endif
#if defined(_WIN32)
# if defined(__clang__) && defined(__WIN32__)
# define ecere_stdcall __stdcall
# define ecere_gcc_struct
# elif defined(__GNUC__) || defined(__TINYC__)
# define ecere_stdcall __attribute__((__stdcall__))
# define ecere_gcc_struct __attribute__((gcc_struct))
# else
# define ecere_stdcall __stdcall
# define ecere_gcc_struct
# endif
#else
# define ecere_stdcall
# define ecere_gcc_struct
#endif
#include <stdint.h>
#include <sys/types.h>
void __ecereNameSpace__ecere__sys__FillBytesBy2(void * area, unsigned short value, unsigned int count)
{
unsigned short * dest = area;
int c;
for(c = 0; c < count; c++)
dest[c] = value;
}
void __ecereNameSpace__ecere__sys__FillBytesBy4(void * area, unsigned int value, unsigned int count)
{
unsigned int * dest = area;
int c;
for(c = 0; c < count; c++)
dest[c] = value;
}
struct __ecereNameSpace__ecere__sys__OldList
{
void * first;
void * last;
int count;
unsigned int offset;
unsigned int circ;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__sys__BTNode;
struct __ecereNameSpace__ecere__com__DataValue
{
union
{
char c;
unsigned char uc;
short s;
unsigned short us;
int i;
unsigned int ui;
void * p;
float f;
double d;
long long i64;
uint64 ui64;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__SerialBuffer
{
unsigned char * _buffer;
size_t count;
size_t _size;
size_t pos;
} ecere_gcc_struct;
extern void * __ecereNameSpace__ecere__com__eSystem_New(unsigned int size);
extern void * __ecereNameSpace__ecere__com__eSystem_New0(unsigned int size);
extern void * __ecereNameSpace__ecere__com__eSystem_Renew(void * memory, unsigned int size);
extern void * __ecereNameSpace__ecere__com__eSystem_Renew0(void * memory, unsigned int size);
extern void __ecereNameSpace__ecere__com__eSystem_Delete(void * memory);
extern void * memmove(void * , const void * , size_t size);
extern void * memcpy(void * , const void * , size_t size);
extern void * memset(void * area, int value, size_t count);
struct __ecereNameSpace__ecere__com__GlobalFunction;
void __ecereNameSpace__ecere__sys__MoveBytes(void * dest, const void * source, unsigned int count)
{
memmove(dest, source, count);
}
void __ecereNameSpace__ecere__sys__CopyBytes(void * dest, const void * source, uint64 count)
{
memcpy(dest, source, count);
}
void __ecereNameSpace__ecere__sys__CopyBytesBy2(void * dest, const void * source, unsigned int count)
{
memcpy(dest, source, count << 1);
}
void __ecereNameSpace__ecere__sys__CopyBytesBy4(void * dest, const void * source, unsigned int count)
{
memcpy(dest, source, count << 2);
}
void __ecereNameSpace__ecere__sys__FillBytes(void * area, unsigned char value, unsigned int count)
{
memset(area, value, count);
}
struct __ecereNameSpace__ecere__com__Class;
struct __ecereNameSpace__ecere__com__Instance
{
void * * _vTbl;
struct __ecereNameSpace__ecere__com__Class * _class;
int _refCount;
} ecere_gcc_struct;
extern long long __ecereNameSpace__ecere__com__eClass_GetProperty(struct __ecereNameSpace__ecere__com__Class * _class, const char * name);
extern void __ecereNameSpace__ecere__com__eClass_SetProperty(struct __ecereNameSpace__ecere__com__Class * _class, const char * name, long long value);
extern void __ecereNameSpace__ecere__com__eInstance_SetMethod(struct __ecereNameSpace__ecere__com__Instance * instance, const char * name, void * function);
extern void __ecereNameSpace__ecere__com__eInstance_IncRef(struct __ecereNameSpace__ecere__com__Instance * instance);
struct __ecereNameSpace__ecere__sys__BinaryTree;
struct __ecereNameSpace__ecere__sys__BinaryTree
{
struct __ecereNameSpace__ecere__sys__BTNode * root;
int count;
int (* CompareKey)(struct __ecereNameSpace__ecere__sys__BinaryTree * tree, uintptr_t a, uintptr_t b);
void (* FreeKey)(void * key);
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__DataMember;
struct __ecereNameSpace__ecere__com__DataMember
{
struct __ecereNameSpace__ecere__com__DataMember * prev;
struct __ecereNameSpace__ecere__com__DataMember * next;
const char * name;
unsigned int isProperty;
int memberAccess;
int id;
struct __ecereNameSpace__ecere__com__Class * _class;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
struct __ecereNameSpace__ecere__com__Instance * dataType;
int type;
int offset;
int memberID;
struct __ecereNameSpace__ecere__sys__OldList members;
struct __ecereNameSpace__ecere__sys__BinaryTree membersAlpha;
int memberOffset;
short structAlignment;
short pointerAlignment;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Property;
struct __ecereNameSpace__ecere__com__Property
{
struct __ecereNameSpace__ecere__com__Property * prev;
struct __ecereNameSpace__ecere__com__Property * next;
const char * name;
unsigned int isProperty;
int memberAccess;
int id;
struct __ecereNameSpace__ecere__com__Class * _class;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
struct __ecereNameSpace__ecere__com__Instance * dataType;
void (* Set)(void * , int);
int (* Get)(void * );
unsigned int (* IsSet)(void * );
void * data;
void * symbol;
int vid;
unsigned int conversion;
unsigned int watcherOffset;
const char * category;
unsigned int compiled;
unsigned int selfWatchable;
unsigned int isWatchable;
} ecere_gcc_struct;
extern void __ecereNameSpace__ecere__com__eInstance_FireSelfWatchers(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property);
extern void __ecereNameSpace__ecere__com__eInstance_StopWatching(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property, struct __ecereNameSpace__ecere__com__Instance * object);
extern void __ecereNameSpace__ecere__com__eInstance_Watch(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property, void * object, void (* callback)(void * , void * ));
extern void __ecereNameSpace__ecere__com__eInstance_FireWatchers(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property);
struct __ecereNameSpace__ecere__com__Method;
struct __ecereNameSpace__ecere__com__ClassTemplateArgument
{
union
{
struct
{
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
} ecere_gcc_struct __anon1;
struct __ecereNameSpace__ecere__com__DataValue expression;
struct
{
const char * memberString;
union
{
struct __ecereNameSpace__ecere__com__DataMember * member;
struct __ecereNameSpace__ecere__com__Property * prop;
struct __ecereNameSpace__ecere__com__Method * method;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct __anon2;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Method
{
const char * name;
struct __ecereNameSpace__ecere__com__Method * parent;
struct __ecereNameSpace__ecere__com__Method * left;
struct __ecereNameSpace__ecere__com__Method * right;
int depth;
int (* function)();
int vid;
int type;
struct __ecereNameSpace__ecere__com__Class * _class;
void * symbol;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Instance * dataType;
int memberAccess;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Module;
extern struct __ecereNameSpace__ecere__com__GlobalFunction * __ecereNameSpace__ecere__com__eSystem_RegisterFunction(const char * name, const char * type, void * func, struct __ecereNameSpace__ecere__com__Instance * module, int declMode);
struct __ecereNameSpace__ecere__com__NameSpace;
struct __ecereNameSpace__ecere__com__NameSpace
{
const char * name;
struct __ecereNameSpace__ecere__com__NameSpace * btParent;
struct __ecereNameSpace__ecere__com__NameSpace * left;
struct __ecereNameSpace__ecere__com__NameSpace * right;
int depth;
struct __ecereNameSpace__ecere__com__NameSpace * parent;
struct __ecereNameSpace__ecere__sys__BinaryTree nameSpaces;
struct __ecereNameSpace__ecere__sys__BinaryTree classes;
struct __ecereNameSpace__ecere__sys__BinaryTree defines;
struct __ecereNameSpace__ecere__sys__BinaryTree functions;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Class
{
struct __ecereNameSpace__ecere__com__Class * prev;
struct __ecereNameSpace__ecere__com__Class * next;
const char * name;
int offset;
int structSize;
void * * _vTbl;
int vTblSize;
unsigned int (* Constructor)(void * );
void (* Destructor)(void * );
int offsetClass;
int sizeClass;
struct __ecereNameSpace__ecere__com__Class * base;
struct __ecereNameSpace__ecere__sys__BinaryTree methods;
struct __ecereNameSpace__ecere__sys__BinaryTree members;
struct __ecereNameSpace__ecere__sys__BinaryTree prop;
struct __ecereNameSpace__ecere__sys__OldList membersAndProperties;
struct __ecereNameSpace__ecere__sys__BinaryTree classProperties;
struct __ecereNameSpace__ecere__sys__OldList derivatives;
int memberID;
int startMemberID;
int type;
struct __ecereNameSpace__ecere__com__Instance * module;
struct __ecereNameSpace__ecere__com__NameSpace * nameSpace;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Instance * dataType;
int typeSize;
int defaultAlignment;
void (* Initialize)();
int memberOffset;
struct __ecereNameSpace__ecere__sys__OldList selfWatchers;
const char * designerClass;
unsigned int noExpansion;
const char * defaultProperty;
unsigned int comRedefinition;
int count;
int isRemote;
unsigned int internalDecl;
void * data;
unsigned int computeSize;
short structAlignment;
short pointerAlignment;
int destructionWatchOffset;
unsigned int fixed;
struct __ecereNameSpace__ecere__sys__OldList delayedCPValues;
int inheritanceAccess;
const char * fullName;
void * symbol;
struct __ecereNameSpace__ecere__sys__OldList conversions;
struct __ecereNameSpace__ecere__sys__OldList templateParams;
struct __ecereNameSpace__ecere__com__ClassTemplateArgument * templateArgs;
struct __ecereNameSpace__ecere__com__Class * templateClass;
struct __ecereNameSpace__ecere__sys__OldList templatized;
int numParams;
unsigned int isInstanceClass;
unsigned int byValueSystemClass;
void * bindingsClass;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Application
{
int argc;
const char * * argv;
int exitCode;
unsigned int isGUIApp;
struct __ecereNameSpace__ecere__sys__OldList allModules;
char * parsedCommand;
struct __ecereNameSpace__ecere__com__NameSpace systemNameSpace;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Module
{
struct __ecereNameSpace__ecere__com__Instance * application;
struct __ecereNameSpace__ecere__sys__OldList classes;
struct __ecereNameSpace__ecere__sys__OldList defines;
struct __ecereNameSpace__ecere__sys__OldList functions;
struct __ecereNameSpace__ecere__sys__OldList modules;
struct __ecereNameSpace__ecere__com__Instance * prev;
struct __ecereNameSpace__ecere__com__Instance * next;
const char * name;
void * library;
void * Unload;
int importType;
int origImportType;
struct __ecereNameSpace__ecere__com__NameSpace privateNameSpace;
struct __ecereNameSpace__ecere__com__NameSpace publicNameSpace;
} ecere_gcc_struct;
void __ecereRegisterModule_memory(struct __ecereNameSpace__ecere__com__Instance * module)
{
struct __ecereNameSpace__ecere__com__Class __attribute__((unused)) * class;
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("ecere::sys::MoveBytes", "void ecere::sys::MoveBytes(void * dest, const void * source, uint count)", __ecereNameSpace__ecere__sys__MoveBytes, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("ecere::sys::CopyBytes", "void ecere::sys::CopyBytes(void * dest, const void * source, uint64 count)", __ecereNameSpace__ecere__sys__CopyBytes, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("ecere::sys::CopyBytesBy2", "void ecere::sys::CopyBytesBy2(void * dest, const void * source, uint count)", __ecereNameSpace__ecere__sys__CopyBytesBy2, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("ecere::sys::CopyBytesBy4", "void ecere::sys::CopyBytesBy4(void * dest, const void * source, uint count)", __ecereNameSpace__ecere__sys__CopyBytesBy4, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("ecere::sys::FillBytes", "void ecere::sys::FillBytes(void * area, byte value, uint count)", __ecereNameSpace__ecere__sys__FillBytes, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("ecere::sys::FillBytesBy2", "void ecere::sys::FillBytesBy2(void * area, uint16 value, uint count)", __ecereNameSpace__ecere__sys__FillBytesBy2, module, 1);
__ecereNameSpace__ecere__com__eSystem_RegisterFunction("ecere::sys::FillBytesBy4", "void ecere::sys::FillBytesBy4(void * area, uint value, uint count)", __ecereNameSpace__ecere__sys__FillBytesBy4, module, 1);
}
void __ecereUnregisterModule_memory(struct __ecereNameSpace__ecere__com__Instance * module)
{
}
|
the_stack_data/181392652.c | #include<stdio.h>
#include<ctype.h>
int main()
{
char c = 'a';
printf("%c -> %c", c, toupper(c));
}
|
the_stack_data/92328705.c | #include<stdio.h>
int main() {
int TRUE = 1;
int FALSE = 0;
printf("Ini nilai TRUE AND TRUE: %d\n", TRUE && TRUE);
printf("Ini nilai TRUE OR FLASE: %d\n", TRUE || FALSE);
printf("Ini nilai FALSE AND TRUE: %d\n", FALSE && TRUE);
printf("Ini nilai FALSE OR FALSE: %d\n", FALSE || FALSE);
printf("Ini nilai NOT TRUE: %d\n", !TRUE);
printf("Ini nilai NOT FALSE: %d\n", !FALSE);
return 0;
} |
the_stack_data/325831.c | #include<stdio.h>
int a[10000005];
void qsort(int a[],int left,int right);
int main()
{
int n,k;
int i,rang=1,cnt=1;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&k);
qsort(a,0,n-1);
for(i=n-1;i>=1;i--)
{
if(a[i]!=a[i-1])
{
if(rang==k)
{
printf("%d %d\n",a[i],cnt);
return 0;
}
rang++;
cnt=1;
} else
{
cnt++;
}
}
printf("%d %d",a[0],cnt);
}
void qsort(int a[],int left,int right)
{
if(left>=right)
{
return;
}
int i=left,j=right;
int key=a[left];
while(i<j)
{
while(i<j&&key<=a[j])
{
j--;
}
a[i] = a[j];
while(i<j&&key>=a[i])
{
i++;
}
a[j] = a[i];
}
a[i] = key;
qsort(a,left,i-1);
qsort(a,i+1,right);
} |
the_stack_data/45449644.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(const char *msg) { perror(msg); exit(1); } // Error function used for reporting issues
int isNewline(char arr[1001]);
char* toPlaintext(char key[100000], char ciphertext[100000]);
int subtractChars(char keyChar, char ctChar);
int getSubstring(char* substring, char fullString[100000]);
int substrIdx = 0; // Global variable to track substring index starting point
int main(int argc, char *argv[])
{
// Original child process
pid_t childPID = -5;
int childExitStatus = -5;
// Background child process
pid_t childPID_Background = -5;
int childExitStatus_Background = -5;
int childProcess = -5; // Tracker for element number in childPID array
int listenSocketFD, establishedConnectionFD, portNumber, charsRead, stringLength, keyInput, dataSize;
socklen_t sizeOfClientInfo;
char key[100000], plaintext[100000], ciphertext[100000];
char sendChar[1001], buffer[1001];
char* s = sendChar;
struct sockaddr_in serverAddress, clientAddress;
int newline = 0;
int sendCharLength = 0;
char *socketName = "otp_dec";
// Check argument length
if (argc < 2) { fprintf(stderr,"USAGE: %s port\n", argv[0]); exit(1); } // Check usage & args
// Set up the address struct for this process (the server)
memset((char *)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct
portNumber = atoi(argv[1]); // Get the port number, convert to an integer from a string
serverAddress.sin_family = AF_INET; // Create a network-capable socket
serverAddress.sin_port = htons(portNumber); // Store the port number
serverAddress.sin_addr.s_addr = INADDR_ANY; // Any address is allowed for connection to this process
// Set up the socket
listenSocketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket
if (listenSocketFD < 0) error("ERROR opening socket");
// Enable the socket to begin listening
if (bind(listenSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { // Connect socket to port
perror("Error: on binding");
exit(2);
}
listen(listenSocketFD, 5); // Flip the socket on - it can now receive up to 5 connections
// Accept a connection, blocking if one is not available until one connects
while (1) {
memset(key, '\0', sizeof(key)); // Clear out the buffer array
memset(plaintext, '\0', sizeof(plaintext)); // Clear out the buffer array
memset(ciphertext, '\0', sizeof(ciphertext)); // Clear out the buffer array
sendCharLength = 0; // Reset length counter
substrIdx = 0; // Reset substring length tracker
dataSize = 0; // Reset data size tracker
// Check for terminated child process
childPID_Background = waitpid(-1, &childExitStatus_Background, WNOHANG);
// If background process terminated
if (childPID_Background > 0) {
// Decrement child process count
childProcess = childProcess - 1;
}
// Accept connection to client
sizeOfClientInfo = sizeof(clientAddress); // Get the size of the address for the client that will connect
establishedConnectionFD = accept(listenSocketFD, (struct sockaddr *)&clientAddress, &sizeOfClientInfo); // Accept
if (establishedConnectionFD < 0) error("ERROR on accept");
// Create child process
childProcess = childProcess + 1; // Increment child process counter for main process
childPID = fork();
// Evaluate childPID creation status
switch (childPID)
{
case -1: // Error creating child process
perror("Error creating new child process");
childProcess = childProcess - 1; // Decrement fork counter if process failed
exit(1);
break;
case 0: // Child process created successfully
// Read name of client connection
memset(buffer, '\0', sizeof(buffer)); // Clear out the buffer array
charsRead = recv(establishedConnectionFD, buffer, sizeof(buffer), 0); // Read the client's message from the socket
// Return name of server connection
keyInput = send(establishedConnectionFD, socketName, sizeof(socketName), 0); // Write to the client
if (keyInput < 0) { error("ERROR writing to socket"); } // Output if error writing
if (keyInput < sendCharLength) { printf("WARNING: Not all data written to socket!\n"); fflush(stdout); } // Output if error with data sent
// Only proceed if client connection name is correct
if (strcmp(buffer, socketName) == 0) {
// Retrieve key
do { // Loop until end of key found
// Receive size of incoming data and key substring
charsRead = recv(establishedConnectionFD, &dataSize, sizeof(int), 0); // Read the client's message from the socket
memset(buffer, '\0', sizeof(buffer)); // Clear out the buffer array
charsRead = recv(establishedConnectionFD, buffer, dataSize, 0); // Read the client's message from the socket
if (charsRead < 0) { error("ERROR reading from socket"); }; // Error if no data received
strcat(key, buffer); // Concatenate buffer to plaintext variable
newline = isNewline(buffer); // Check for end of string
} while(newline == 0);
newline = 0; // Reset newline
dataSize = 0; // Reset data size
// Retrieve ciphertext
do {
// Receive size of incoming data and key substring
charsRead = recv(establishedConnectionFD, &dataSize, sizeof(int), 0); // Read the client's message from the socket
memset(buffer, '\0', sizeof(buffer)); // Clear out the buffer array
charsRead = recv(establishedConnectionFD, buffer, dataSize, 0); // Read the client's message from the socket
if (charsRead < 0) { error("ERROR reading from socket"); }; // Error if no data received
strcat(ciphertext, buffer); // Concatenate buffer to key variable
newline = isNewline(buffer); // Check for end of string
} while(newline == 0);
// Remove trailing newlines from key and ciphertext
key[strcspn(key, "\n")] = 0;
ciphertext[strcspn(ciphertext, "\n")] = 0;
// Decipher ciphertext using key then re-introduce newline
strcpy(plaintext, toPlaintext(key, ciphertext));
strcat(plaintext, "\n");
stringLength = strlen(plaintext);
// Slice plaintext into substring(s) with max length 1000 and send to client
do { // Loop until last substring
memset(sendChar, '\0', sizeof(sendChar)); // Reset sendChar variable
sendCharLength = getSubstring(s, plaintext); // Get substring of key with max 1000 characters
// Send data size and substring to server
keyInput = send(establishedConnectionFD, &sendCharLength, sizeof(int), 0); // Write to the server
keyInput = send(establishedConnectionFD, sendChar, sendCharLength, 0); // Write to the client
if (keyInput < 0) { error("ERROR writing to socket"); } // Output if error writing
stringLength = stringLength - keyInput; // Decrement string length
} while(stringLength > 0);
close(establishedConnectionFD); // Close the existing socket which is connected to the client
exit(0); // Exit child process
}
else {
perror("Error: Connection rejected");
close(establishedConnectionFD); // Close the existing socket which is connected to the client
exit(2); // Exit child process
}
break;
default:
// Wait until system can handle more child processes (max 5)
while (childProcess >= 5) {
// Check for terminated child process
childPID_Background = waitpid(-1, &childExitStatus_Background, WNOHANG);
// If background process terminated
if (childPID_Background > 0) {
// Decrement child process count
childProcess = childProcess - 1;
}
}
break;
}
}
close(listenSocketFD); // Close the listening socket
return 0;
}
// Detects newline characters in passed char array
// Returns 1 if newline found
// Returns 0 if no newline found
int isNewline(char arr[1001]) {
int i;
// Loop through buffer input
for (i = 0 ; i < 1000; i++) {
// Break if end condition met
if (arr[i] == '\n') {
return 1;
}
}
// Return 0 if no newline found
return 0;
}
// Enciphers message using passed key
// Returns enciphered message
char* toPlaintext(char key[100000], char ciphertext[100000]) {
static char plaintext[100000]; // Ciphertext char array
int i; // Iterator
int asciiInt;
// Iterate through plaintext and use key to encipher
for (i = 0; i < strlen(ciphertext); i++) {
asciiInt = subtractChars(key[i], ciphertext[i]); // Convert to encoded ASCII number
plaintext[i] = asciiInt; // Save to character array
}
return plaintext;
}
// Calculates decipherment value of two characters
// Returns ASCII of decrypted character
int subtractChars(char keyChar, char ctChar) {
// Convert characters to integer
int k = keyChar;
int c = ctChar;
if (k == 32) {
k = 91;
}
if (c == 32) {
c = 91;
}
k = k - 65;
c = c - 65;
// Subtract key from ciphertext
int diff = c - k;
// Find modulus of difference
diff = (diff % 27 + 27) % 27;
// Convert value to uppercase
diff = diff + 65;
// Replace 91 with space character, if applicable
if (diff == 91) {
diff = 32;
}
return diff;
}
// Generates substring of given string with max 1000 characters
// Returns size of substring
int getSubstring(char* substring, char fullString[100000]) {
int i;
// Copy up to 1000 characters to substring
for (i = 0; i < 1000; i++) {
substring[i] = fullString[substrIdx];
substrIdx = substrIdx + 1; // Increment substring index variable
// Return if \n reached before reaching 1000
if (fullString[substrIdx - 1] == '\n') {
i = i + 1; // Increment i for newline
return i;
}
}
// Return if 1000 reached before newline
return i;
} |
the_stack_data/200142574.c | /*-
* BSD LICENSE
*
* Copyright(c) 2015-2017 Ansyun <[email protected]>. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Ansyun <[email protected]> nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <pthread.h>
int fd = -1;
#define TCP_CLIENT_SEND_LEN 2000
struct epoll_event events[20];
void set_nonblocking(int sockfd)
{
int opts;
opts = fcntl(sockfd, F_GETFL);
if(opts < 0)
{
printf("fcntl(F_GETFL) failed \n");
}
opts = (opts | O_NONBLOCK);
if(fcntl(sockfd, F_SETFL, opts) < 0)
{
printf("fcntl(F_SETFL) failed\n");
}
}
void tcp_send_thread()
{
int data_num = 0;
int data_len = 0;
char send_data[5000];
memset(send_data, 0, sizeof(send_data));
int send_len = 0;
while(1)
{
if(fd > 0)
{
data_num++;
sprintf(send_data, "Hello, linux tcp server, num:%d !", data_num);
send_len = 0;
// if(data_num == 1)
send_len = send(fd, send_data, 2000, 0);
if(send_len <= 0)
{
printf("send failed \n");
usleep(200000);
continue;
}
data_len += send_len;
printf("send len %d, data num %d, data len:%d \n", send_len, data_num, data_len);
}
usleep(20000);
}
}
int main(void)
{
int ret;
int i = 0 ;
int epfd;
int data_num =0;
struct sockaddr_in addr_in;
struct sockaddr_in remote_addr;
struct epoll_event event;
char recv_buf[5000];
int recv_len;
pthread_t id;
/* create epoll socket */
epfd = epoll_create(10);
if(epfd < 0)
{
printf("create epoll socket failed \n");
return -1;
}
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd < 0)
{
printf("create socket failed \n");
close(epfd);
return -1;
}
memset(&remote_addr, 0, sizeof(remote_addr));
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(8000);
remote_addr.sin_addr.s_addr = inet_addr("10.0.0.2");
if(connect(fd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) < 0)
{
printf("onnect to server failed \n");
close(fd);
close(epfd);
return -1;
}
set_nonblocking(fd);
event.data.fd = fd;
event.events = EPOLLIN | EPOLLET;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event);
if(ret != 0)
{
printf("epoll ctl failed \n");
close(fd);
close(epfd);
return -1;
}
printf("start dpdk tcp client application \n");
ret=pthread_create(&id, NULL, (void *) tcp_send_thread, NULL);
if(ret!=0)
{
printf ("Create pthread error!\n");
return 0;
}
int event_num = 0;
while(1)
{
event_num = epoll_wait (epfd, events, 20, -1);
if(event_num <= 0)
{
printf("epoll_wait failed \n");
continue;
}
for(i = 0; i < event_num; i++)
{
if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN)))
{
printf("linux socket(%d) error\n", events[i].data.fd);
close (events[i].data.fd);
fd = -1;
continue;
}
if (events[i].events & EPOLLIN)
{
while(1)
{
recv_len = recvfrom(events[i].data.fd, recv_buf, 5000, 0, NULL, NULL);
if((recv_len < 0) && (errno == EAGAIN))
{
// printf("no data in socket \n");
break;
}
else if(recv_len <= 0)
{
// socket error
printf("socket error: %d, errno %d \n", recv_len, errno);
close(fd);
break;
}
printf("Recv data, len: %d \n", recv_len);
data_num++;
}
}
else
{
printf("unknow event %x, fd:%d \n", events[i].events, events[i].data.fd);
}
}
}
close(fd);
close(epfd);
return 0;
}
|
the_stack_data/36076626.c | #include <stdio.h>
#include <stdlib.h>
FILE *arquivo;
int main()
{
int valores[10];
printf("Digite 10 valores inteiro: \n");
for (int i = 0; i < 10; i++)
{
printf("%i. ", i+1);
scanf("%i", &valores[i]);
}
arquivo=fopen("valores.txt", "w");
for (int i = 0; i < 10; i++)
{
if (valores[i] % 2 == 0)
{
fprintf(arquivo, "%i \n", valores[i]);
}else
{
valores[i] = 0;
fprintf(arquivo, "%i \n", valores[i]);
}
}
fclose(arquivo);
return 0;
}
|
the_stack_data/103266109.c | //z19.c
#include <stdio.h>
#include <stdlib.h>
#define MAXL 80
int main()
{
FILE *pf;
char str[MAXL];
pf=fopen("test.txt","r");
if(pf!=NULL){
while(fgets(str, MAXL, pf)!=NULL)
puts(str);
fclose(pf);
} else {
printf("%p\tNije moguce otvoriti datoteku ili datoteka ne postoji.",pf);
}
/*00000000 Nije moguce otvoriti datoteku ili datoteka ne postoji.*/
return EXIT_SUCCESS;
}
|
the_stack_data/233908.c | // Example for parameters
void coucou(int hello, int goodbye) {
}
void boo() {} |
the_stack_data/75139013.c | /*
* string/ffs.c
* Returns the index of the first set bit.
*/
#include <string.h>
int ffs(int val) {
return __builtin_ffs(val);
}
|
the_stack_data/93850.c | /*
* Copyright (c) 1999-2000 Vojtech Pavlik
* Copyright (c) 2009-2011 Red Hat, Inc
*/
/**
* @file
* Event device test program
*
* evtest prints the capabilities on the kernel devices in /dev/input/eventX
* and their events. Its primary purpose is for kernel or X driver
* debugging.
*
* See INSTALL for installation details or manually compile with
* gcc -o evtest evtest.c
*/
/*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <[email protected]>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#define _GNU_SOURCE /* for asprintf */
#include <stdio.h>
#include <stdint.h>
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <linux/version.h>
#include <linux/input.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <getopt.h>
#include <ctype.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#define BITS_PER_LONG (sizeof(long) * 8)
#define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1)
#define OFF(x) ((x)%BITS_PER_LONG)
#define BIT(x) (1UL<<OFF(x))
#define LONG(x) ((x)/BITS_PER_LONG)
#define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1)
#define DEV_INPUT_EVENT "/dev/input"
#define EVENT_DEV_NAME "event"
#ifndef EV_SYN
#define EV_SYN 0
#endif
#ifndef SYN_MAX
#define SYN_MAX 3
#define SYN_CNT (SYN_MAX + 1)
#endif
#ifndef SYN_MT_REPORT
#define SYN_MT_REPORT 2
#endif
#ifndef SYN_DROPPED
#define SYN_DROPPED 3
#endif
#define NAME_ELEMENT(element) [element] = #element
enum evtest_mode {
MODE_CAPTURE,
MODE_QUERY,
MODE_VERSION,
};
static const struct query_mode {
const char *name;
int event_type;
int max;
int rq;
} query_modes[] = {
{ "EV_KEY", EV_KEY, KEY_MAX, EVIOCGKEY(KEY_MAX) },
{ "EV_LED", EV_LED, LED_MAX, EVIOCGLED(LED_MAX) },
{ "EV_SND", EV_SND, SND_MAX, EVIOCGSND(SND_MAX) },
{ "EV_SW", EV_SW, SW_MAX, EVIOCGSW(SW_MAX) },
};
static int grab_flag = 0;
static volatile sig_atomic_t stop = 0;
static void interrupt_handler(int sig)
{
stop = 1;
}
/**
* Look up an entry in the query_modes table by its textual name.
*
* @param mode The name of the entry to be found.
*
* @return The requested query_mode, or NULL if it could not be found.
*/
static const struct query_mode *find_query_mode_by_name(const char *name)
{
int i;
for (i = 0; i < sizeof(query_modes) / sizeof(*query_modes); i++) {
const struct query_mode *mode = &query_modes[i];
if (strcmp(mode->name, name) == 0)
return mode;
}
return NULL;
}
/**
* Look up an entry in the query_modes table by value.
*
* @param event_type The value of the entry to be found.
*
* @return The requested query_mode, or NULL if it could not be found.
*/
static const struct query_mode *find_query_mode_by_value(int event_type)
{
int i;
for (i = 0; i < sizeof(query_modes) / sizeof(*query_modes); i++) {
const struct query_mode *mode = &query_modes[i];
if (mode->event_type == event_type)
return mode;
}
return NULL;
}
/**
* Find a query_mode based on a string identifier. The string can either
* be a numerical value (e.g. "5") or the name of the event type in question
* (e.g. "EV_SW").
*
* @param query_mode The mode to search for
*
* @return The requested code's numerical value, or negative on error.
*/
static const struct query_mode *find_query_mode(const char *query_mode)
{
if (isdigit(query_mode[0])) {
unsigned long val;
errno = 0;
val = strtoul(query_mode, NULL, 0);
if (errno)
return NULL;
return find_query_mode_by_value(val);
} else {
return find_query_mode_by_name(query_mode);
}
}
static const char * const events[EV_MAX + 1] = {
[0 ... EV_MAX] = NULL,
NAME_ELEMENT(EV_SYN), NAME_ELEMENT(EV_KEY),
NAME_ELEMENT(EV_REL), NAME_ELEMENT(EV_ABS),
NAME_ELEMENT(EV_MSC), NAME_ELEMENT(EV_LED),
NAME_ELEMENT(EV_SND), NAME_ELEMENT(EV_REP),
NAME_ELEMENT(EV_FF), NAME_ELEMENT(EV_PWR),
NAME_ELEMENT(EV_FF_STATUS), NAME_ELEMENT(EV_SW),
};
static const int maxval[EV_MAX + 1] = {
[0 ... EV_MAX] = -1,
[EV_SYN] = SYN_MAX,
[EV_KEY] = KEY_MAX,
[EV_REL] = REL_MAX,
[EV_ABS] = ABS_MAX,
[EV_MSC] = MSC_MAX,
[EV_SW] = SW_MAX,
[EV_LED] = LED_MAX,
[EV_SND] = SND_MAX,
[EV_REP] = REP_MAX,
[EV_FF] = FF_MAX,
[EV_FF_STATUS] = FF_STATUS_MAX,
};
#ifdef INPUT_PROP_SEMI_MT
static const char * const props[INPUT_PROP_MAX + 1] = {
[0 ... INPUT_PROP_MAX] = NULL,
NAME_ELEMENT(INPUT_PROP_POINTER),
NAME_ELEMENT(INPUT_PROP_DIRECT),
NAME_ELEMENT(INPUT_PROP_BUTTONPAD),
NAME_ELEMENT(INPUT_PROP_SEMI_MT),
#ifdef INPUT_PROP_TOPBUTTONPAD
NAME_ELEMENT(INPUT_PROP_TOPBUTTONPAD),
#endif
#ifdef INPUT_PROP_POINTING_STICK
NAME_ELEMENT(INPUT_PROP_POINTING_STICK),
#endif
};
#endif
static const char * const keys[KEY_MAX + 1] = {
[0 ... KEY_MAX] = NULL,
NAME_ELEMENT(KEY_RESERVED), NAME_ELEMENT(KEY_ESC),
NAME_ELEMENT(KEY_1), NAME_ELEMENT(KEY_2),
NAME_ELEMENT(KEY_3), NAME_ELEMENT(KEY_4),
NAME_ELEMENT(KEY_5), NAME_ELEMENT(KEY_6),
NAME_ELEMENT(KEY_7), NAME_ELEMENT(KEY_8),
NAME_ELEMENT(KEY_9), NAME_ELEMENT(KEY_0),
NAME_ELEMENT(KEY_MINUS), NAME_ELEMENT(KEY_EQUAL),
NAME_ELEMENT(KEY_BACKSPACE), NAME_ELEMENT(KEY_TAB),
NAME_ELEMENT(KEY_Q), NAME_ELEMENT(KEY_W),
NAME_ELEMENT(KEY_E), NAME_ELEMENT(KEY_R),
NAME_ELEMENT(KEY_T), NAME_ELEMENT(KEY_Y),
NAME_ELEMENT(KEY_U), NAME_ELEMENT(KEY_I),
NAME_ELEMENT(KEY_O), NAME_ELEMENT(KEY_P),
NAME_ELEMENT(KEY_LEFTBRACE), NAME_ELEMENT(KEY_RIGHTBRACE),
NAME_ELEMENT(KEY_ENTER), NAME_ELEMENT(KEY_LEFTCTRL),
NAME_ELEMENT(KEY_A), NAME_ELEMENT(KEY_S),
NAME_ELEMENT(KEY_D), NAME_ELEMENT(KEY_F),
NAME_ELEMENT(KEY_G), NAME_ELEMENT(KEY_H),
NAME_ELEMENT(KEY_J), NAME_ELEMENT(KEY_K),
NAME_ELEMENT(KEY_L), NAME_ELEMENT(KEY_SEMICOLON),
NAME_ELEMENT(KEY_APOSTROPHE), NAME_ELEMENT(KEY_GRAVE),
NAME_ELEMENT(KEY_LEFTSHIFT), NAME_ELEMENT(KEY_BACKSLASH),
NAME_ELEMENT(KEY_Z), NAME_ELEMENT(KEY_X),
NAME_ELEMENT(KEY_C), NAME_ELEMENT(KEY_V),
NAME_ELEMENT(KEY_B), NAME_ELEMENT(KEY_N),
NAME_ELEMENT(KEY_M), NAME_ELEMENT(KEY_COMMA),
NAME_ELEMENT(KEY_DOT), NAME_ELEMENT(KEY_SLASH),
NAME_ELEMENT(KEY_RIGHTSHIFT), NAME_ELEMENT(KEY_KPASTERISK),
NAME_ELEMENT(KEY_LEFTALT), NAME_ELEMENT(KEY_SPACE),
NAME_ELEMENT(KEY_CAPSLOCK), NAME_ELEMENT(KEY_F1),
NAME_ELEMENT(KEY_F2), NAME_ELEMENT(KEY_F3),
NAME_ELEMENT(KEY_F4), NAME_ELEMENT(KEY_F5),
NAME_ELEMENT(KEY_F6), NAME_ELEMENT(KEY_F7),
NAME_ELEMENT(KEY_F8), NAME_ELEMENT(KEY_F9),
NAME_ELEMENT(KEY_F10), NAME_ELEMENT(KEY_NUMLOCK),
NAME_ELEMENT(KEY_SCROLLLOCK), NAME_ELEMENT(KEY_KP7),
NAME_ELEMENT(KEY_KP8), NAME_ELEMENT(KEY_KP9),
NAME_ELEMENT(KEY_KPMINUS), NAME_ELEMENT(KEY_KP4),
NAME_ELEMENT(KEY_KP5), NAME_ELEMENT(KEY_KP6),
NAME_ELEMENT(KEY_KPPLUS), NAME_ELEMENT(KEY_KP1),
NAME_ELEMENT(KEY_KP2), NAME_ELEMENT(KEY_KP3),
NAME_ELEMENT(KEY_KP0), NAME_ELEMENT(KEY_KPDOT),
NAME_ELEMENT(KEY_ZENKAKUHANKAKU), NAME_ELEMENT(KEY_102ND),
NAME_ELEMENT(KEY_F11), NAME_ELEMENT(KEY_F12),
NAME_ELEMENT(KEY_RO), NAME_ELEMENT(KEY_KATAKANA),
NAME_ELEMENT(KEY_HIRAGANA), NAME_ELEMENT(KEY_HENKAN),
NAME_ELEMENT(KEY_KATAKANAHIRAGANA), NAME_ELEMENT(KEY_MUHENKAN),
NAME_ELEMENT(KEY_KPJPCOMMA), NAME_ELEMENT(KEY_KPENTER),
NAME_ELEMENT(KEY_RIGHTCTRL), NAME_ELEMENT(KEY_KPSLASH),
NAME_ELEMENT(KEY_SYSRQ), NAME_ELEMENT(KEY_RIGHTALT),
NAME_ELEMENT(KEY_LINEFEED), NAME_ELEMENT(KEY_HOME),
NAME_ELEMENT(KEY_UP), NAME_ELEMENT(KEY_PAGEUP),
NAME_ELEMENT(KEY_LEFT), NAME_ELEMENT(KEY_RIGHT),
NAME_ELEMENT(KEY_END), NAME_ELEMENT(KEY_DOWN),
NAME_ELEMENT(KEY_PAGEDOWN), NAME_ELEMENT(KEY_INSERT),
NAME_ELEMENT(KEY_DELETE), NAME_ELEMENT(KEY_MACRO),
NAME_ELEMENT(KEY_MUTE), NAME_ELEMENT(KEY_VOLUMEDOWN),
NAME_ELEMENT(KEY_VOLUMEUP), NAME_ELEMENT(KEY_POWER),
NAME_ELEMENT(KEY_KPEQUAL), NAME_ELEMENT(KEY_KPPLUSMINUS),
NAME_ELEMENT(KEY_PAUSE), NAME_ELEMENT(KEY_KPCOMMA),
NAME_ELEMENT(KEY_HANGUEL), NAME_ELEMENT(KEY_HANJA),
NAME_ELEMENT(KEY_YEN), NAME_ELEMENT(KEY_LEFTMETA),
NAME_ELEMENT(KEY_RIGHTMETA), NAME_ELEMENT(KEY_COMPOSE),
NAME_ELEMENT(KEY_STOP), NAME_ELEMENT(KEY_AGAIN),
NAME_ELEMENT(KEY_PROPS), NAME_ELEMENT(KEY_UNDO),
NAME_ELEMENT(KEY_FRONT), NAME_ELEMENT(KEY_COPY),
NAME_ELEMENT(KEY_OPEN), NAME_ELEMENT(KEY_PASTE),
NAME_ELEMENT(KEY_FIND), NAME_ELEMENT(KEY_CUT),
NAME_ELEMENT(KEY_HELP), NAME_ELEMENT(KEY_MENU),
NAME_ELEMENT(KEY_CALC), NAME_ELEMENT(KEY_SETUP),
NAME_ELEMENT(KEY_SLEEP), NAME_ELEMENT(KEY_WAKEUP),
NAME_ELEMENT(KEY_FILE), NAME_ELEMENT(KEY_SENDFILE),
NAME_ELEMENT(KEY_DELETEFILE), NAME_ELEMENT(KEY_XFER),
NAME_ELEMENT(KEY_PROG1), NAME_ELEMENT(KEY_PROG2),
NAME_ELEMENT(KEY_WWW), NAME_ELEMENT(KEY_MSDOS),
NAME_ELEMENT(KEY_COFFEE), NAME_ELEMENT(KEY_DIRECTION),
NAME_ELEMENT(KEY_CYCLEWINDOWS), NAME_ELEMENT(KEY_MAIL),
NAME_ELEMENT(KEY_BOOKMARKS), NAME_ELEMENT(KEY_COMPUTER),
NAME_ELEMENT(KEY_BACK), NAME_ELEMENT(KEY_FORWARD),
NAME_ELEMENT(KEY_CLOSECD), NAME_ELEMENT(KEY_EJECTCD),
NAME_ELEMENT(KEY_EJECTCLOSECD), NAME_ELEMENT(KEY_NEXTSONG),
NAME_ELEMENT(KEY_PLAYPAUSE), NAME_ELEMENT(KEY_PREVIOUSSONG),
NAME_ELEMENT(KEY_STOPCD), NAME_ELEMENT(KEY_RECORD),
NAME_ELEMENT(KEY_REWIND), NAME_ELEMENT(KEY_PHONE),
NAME_ELEMENT(KEY_ISO), NAME_ELEMENT(KEY_CONFIG),
NAME_ELEMENT(KEY_HOMEPAGE), NAME_ELEMENT(KEY_REFRESH),
NAME_ELEMENT(KEY_EXIT), NAME_ELEMENT(KEY_MOVE),
NAME_ELEMENT(KEY_EDIT), NAME_ELEMENT(KEY_SCROLLUP),
NAME_ELEMENT(KEY_SCROLLDOWN), NAME_ELEMENT(KEY_KPLEFTPAREN),
NAME_ELEMENT(KEY_KPRIGHTPAREN), NAME_ELEMENT(KEY_F13),
NAME_ELEMENT(KEY_F14), NAME_ELEMENT(KEY_F15),
NAME_ELEMENT(KEY_F16), NAME_ELEMENT(KEY_F17),
NAME_ELEMENT(KEY_F18), NAME_ELEMENT(KEY_F19),
NAME_ELEMENT(KEY_F20), NAME_ELEMENT(KEY_F21),
NAME_ELEMENT(KEY_F22), NAME_ELEMENT(KEY_F23),
NAME_ELEMENT(KEY_F24), NAME_ELEMENT(KEY_PLAYCD),
NAME_ELEMENT(KEY_PAUSECD), NAME_ELEMENT(KEY_PROG3),
NAME_ELEMENT(KEY_PROG4), NAME_ELEMENT(KEY_SUSPEND),
NAME_ELEMENT(KEY_CLOSE), NAME_ELEMENT(KEY_PLAY),
NAME_ELEMENT(KEY_FASTFORWARD), NAME_ELEMENT(KEY_BASSBOOST),
NAME_ELEMENT(KEY_PRINT), NAME_ELEMENT(KEY_HP),
NAME_ELEMENT(KEY_CAMERA), NAME_ELEMENT(KEY_SOUND),
NAME_ELEMENT(KEY_QUESTION), NAME_ELEMENT(KEY_EMAIL),
NAME_ELEMENT(KEY_CHAT), NAME_ELEMENT(KEY_SEARCH),
NAME_ELEMENT(KEY_CONNECT), NAME_ELEMENT(KEY_FINANCE),
NAME_ELEMENT(KEY_SPORT), NAME_ELEMENT(KEY_SHOP),
NAME_ELEMENT(KEY_ALTERASE), NAME_ELEMENT(KEY_CANCEL),
NAME_ELEMENT(KEY_BRIGHTNESSDOWN), NAME_ELEMENT(KEY_BRIGHTNESSUP),
NAME_ELEMENT(KEY_MEDIA), NAME_ELEMENT(KEY_UNKNOWN),
NAME_ELEMENT(KEY_OK),
NAME_ELEMENT(KEY_SELECT), NAME_ELEMENT(KEY_GOTO),
NAME_ELEMENT(KEY_CLEAR), NAME_ELEMENT(KEY_POWER2),
NAME_ELEMENT(KEY_OPTION), NAME_ELEMENT(KEY_INFO),
NAME_ELEMENT(KEY_TIME), NAME_ELEMENT(KEY_VENDOR),
NAME_ELEMENT(KEY_ARCHIVE), NAME_ELEMENT(KEY_PROGRAM),
NAME_ELEMENT(KEY_CHANNEL), NAME_ELEMENT(KEY_FAVORITES),
NAME_ELEMENT(KEY_EPG), NAME_ELEMENT(KEY_PVR),
NAME_ELEMENT(KEY_MHP), NAME_ELEMENT(KEY_LANGUAGE),
NAME_ELEMENT(KEY_TITLE), NAME_ELEMENT(KEY_SUBTITLE),
NAME_ELEMENT(KEY_ANGLE), NAME_ELEMENT(KEY_ZOOM),
NAME_ELEMENT(KEY_MODE), NAME_ELEMENT(KEY_KEYBOARD),
NAME_ELEMENT(KEY_SCREEN), NAME_ELEMENT(KEY_PC),
NAME_ELEMENT(KEY_TV), NAME_ELEMENT(KEY_TV2),
NAME_ELEMENT(KEY_VCR), NAME_ELEMENT(KEY_VCR2),
NAME_ELEMENT(KEY_SAT), NAME_ELEMENT(KEY_SAT2),
NAME_ELEMENT(KEY_CD), NAME_ELEMENT(KEY_TAPE),
NAME_ELEMENT(KEY_RADIO), NAME_ELEMENT(KEY_TUNER),
NAME_ELEMENT(KEY_PLAYER), NAME_ELEMENT(KEY_TEXT),
NAME_ELEMENT(KEY_DVD), NAME_ELEMENT(KEY_AUX),
NAME_ELEMENT(KEY_MP3), NAME_ELEMENT(KEY_AUDIO),
NAME_ELEMENT(KEY_VIDEO), NAME_ELEMENT(KEY_DIRECTORY),
NAME_ELEMENT(KEY_LIST), NAME_ELEMENT(KEY_MEMO),
NAME_ELEMENT(KEY_CALENDAR), NAME_ELEMENT(KEY_RED),
NAME_ELEMENT(KEY_GREEN), NAME_ELEMENT(KEY_YELLOW),
NAME_ELEMENT(KEY_BLUE), NAME_ELEMENT(KEY_CHANNELUP),
NAME_ELEMENT(KEY_CHANNELDOWN), NAME_ELEMENT(KEY_FIRST),
NAME_ELEMENT(KEY_LAST), NAME_ELEMENT(KEY_AB),
NAME_ELEMENT(KEY_NEXT), NAME_ELEMENT(KEY_RESTART),
NAME_ELEMENT(KEY_SLOW), NAME_ELEMENT(KEY_SHUFFLE),
NAME_ELEMENT(KEY_BREAK), NAME_ELEMENT(KEY_PREVIOUS),
NAME_ELEMENT(KEY_DIGITS), NAME_ELEMENT(KEY_TEEN),
NAME_ELEMENT(KEY_TWEN), NAME_ELEMENT(KEY_DEL_EOL),
NAME_ELEMENT(KEY_DEL_EOS), NAME_ELEMENT(KEY_INS_LINE),
NAME_ELEMENT(KEY_DEL_LINE),
NAME_ELEMENT(KEY_VIDEOPHONE), NAME_ELEMENT(KEY_GAMES),
NAME_ELEMENT(KEY_ZOOMIN), NAME_ELEMENT(KEY_ZOOMOUT),
NAME_ELEMENT(KEY_ZOOMRESET), NAME_ELEMENT(KEY_WORDPROCESSOR),
NAME_ELEMENT(KEY_EDITOR), NAME_ELEMENT(KEY_SPREADSHEET),
NAME_ELEMENT(KEY_GRAPHICSEDITOR), NAME_ELEMENT(KEY_PRESENTATION),
NAME_ELEMENT(KEY_DATABASE), NAME_ELEMENT(KEY_NEWS),
NAME_ELEMENT(KEY_VOICEMAIL), NAME_ELEMENT(KEY_ADDRESSBOOK),
NAME_ELEMENT(KEY_MESSENGER), NAME_ELEMENT(KEY_DISPLAYTOGGLE),
#ifdef KEY_SPELLCHECK
NAME_ELEMENT(KEY_SPELLCHECK),
#endif
#ifdef KEY_LOGOFF
NAME_ELEMENT(KEY_LOGOFF),
#endif
#ifdef KEY_DOLLAR
NAME_ELEMENT(KEY_DOLLAR),
#endif
#ifdef KEY_EURO
NAME_ELEMENT(KEY_EURO),
#endif
#ifdef KEY_FRAMEBACK
NAME_ELEMENT(KEY_FRAMEBACK),
#endif
#ifdef KEY_FRAMEFORWARD
NAME_ELEMENT(KEY_FRAMEFORWARD),
#endif
#ifdef KEY_CONTEXT_MENU
NAME_ELEMENT(KEY_CONTEXT_MENU),
#endif
#ifdef KEY_MEDIA_REPEAT
NAME_ELEMENT(KEY_MEDIA_REPEAT),
#endif
#ifdef KEY_10CHANNELSUP
NAME_ELEMENT(KEY_10CHANNELSUP),
#endif
#ifdef KEY_10CHANNELSDOWN
NAME_ELEMENT(KEY_10CHANNELSDOWN),
#endif
#ifdef KEY_IMAGES
NAME_ELEMENT(KEY_IMAGES),
#endif
NAME_ELEMENT(KEY_DEL_EOL), NAME_ELEMENT(KEY_DEL_EOS),
NAME_ELEMENT(KEY_INS_LINE), NAME_ELEMENT(KEY_DEL_LINE),
NAME_ELEMENT(KEY_FN), NAME_ELEMENT(KEY_FN_ESC),
NAME_ELEMENT(KEY_FN_F1), NAME_ELEMENT(KEY_FN_F2),
NAME_ELEMENT(KEY_FN_F3), NAME_ELEMENT(KEY_FN_F4),
NAME_ELEMENT(KEY_FN_F5), NAME_ELEMENT(KEY_FN_F6),
NAME_ELEMENT(KEY_FN_F7), NAME_ELEMENT(KEY_FN_F8),
NAME_ELEMENT(KEY_FN_F9), NAME_ELEMENT(KEY_FN_F10),
NAME_ELEMENT(KEY_FN_F11), NAME_ELEMENT(KEY_FN_F12),
NAME_ELEMENT(KEY_FN_1), NAME_ELEMENT(KEY_FN_2),
NAME_ELEMENT(KEY_FN_D), NAME_ELEMENT(KEY_FN_E),
NAME_ELEMENT(KEY_FN_F), NAME_ELEMENT(KEY_FN_S),
NAME_ELEMENT(KEY_FN_B),
NAME_ELEMENT(KEY_BRL_DOT1), NAME_ELEMENT(KEY_BRL_DOT2),
NAME_ELEMENT(KEY_BRL_DOT3), NAME_ELEMENT(KEY_BRL_DOT4),
NAME_ELEMENT(KEY_BRL_DOT5), NAME_ELEMENT(KEY_BRL_DOT6),
NAME_ELEMENT(KEY_BRL_DOT7), NAME_ELEMENT(KEY_BRL_DOT8),
NAME_ELEMENT(KEY_BRL_DOT9), NAME_ELEMENT(KEY_BRL_DOT10),
#ifdef KEY_NUMERIC_0
NAME_ELEMENT(KEY_NUMERIC_0), NAME_ELEMENT(KEY_NUMERIC_1),
NAME_ELEMENT(KEY_NUMERIC_2), NAME_ELEMENT(KEY_NUMERIC_3),
NAME_ELEMENT(KEY_NUMERIC_4), NAME_ELEMENT(KEY_NUMERIC_5),
NAME_ELEMENT(KEY_NUMERIC_6), NAME_ELEMENT(KEY_NUMERIC_7),
NAME_ELEMENT(KEY_NUMERIC_8), NAME_ELEMENT(KEY_NUMERIC_9),
NAME_ELEMENT(KEY_NUMERIC_STAR), NAME_ELEMENT(KEY_NUMERIC_POUND),
#endif
NAME_ELEMENT(KEY_BATTERY),
NAME_ELEMENT(KEY_BLUETOOTH), NAME_ELEMENT(KEY_BRIGHTNESS_CYCLE),
NAME_ELEMENT(KEY_BRIGHTNESS_ZERO),
#ifdef KEY_DASHBOARD
NAME_ELEMENT(KEY_DASHBOARD),
#endif
NAME_ELEMENT(KEY_DISPLAY_OFF), NAME_ELEMENT(KEY_DOCUMENTS),
NAME_ELEMENT(KEY_FORWARDMAIL), NAME_ELEMENT(KEY_NEW),
NAME_ELEMENT(KEY_KBDILLUMDOWN), NAME_ELEMENT(KEY_KBDILLUMUP),
NAME_ELEMENT(KEY_KBDILLUMTOGGLE), NAME_ELEMENT(KEY_REDO),
NAME_ELEMENT(KEY_REPLY), NAME_ELEMENT(KEY_SAVE),
#ifdef KEY_SCALE
NAME_ELEMENT(KEY_SCALE),
#endif
NAME_ELEMENT(KEY_SEND),
NAME_ELEMENT(KEY_SCREENLOCK), NAME_ELEMENT(KEY_SWITCHVIDEOMODE),
#ifdef KEY_UWB
NAME_ELEMENT(KEY_UWB),
#endif
#ifdef KEY_VIDEO_NEXT
NAME_ELEMENT(KEY_VIDEO_NEXT),
#endif
#ifdef KEY_VIDEO_PREV
NAME_ELEMENT(KEY_VIDEO_PREV),
#endif
#ifdef KEY_WIMAX
NAME_ELEMENT(KEY_WIMAX),
#endif
#ifdef KEY_WLAN
NAME_ELEMENT(KEY_WLAN),
#endif
#ifdef KEY_RFKILL
NAME_ELEMENT(KEY_RFKILL),
#endif
#ifdef KEY_MICMUTE
NAME_ELEMENT(KEY_MICMUTE),
#endif
#ifdef KEY_CAMERA_FOCUS
NAME_ELEMENT(KEY_CAMERA_FOCUS),
#endif
#ifdef KEY_WPS_BUTTON
NAME_ELEMENT(KEY_WPS_BUTTON),
#endif
#ifdef KEY_TOUCHPAD_TOGGLE
NAME_ELEMENT(KEY_TOUCHPAD_TOGGLE),
NAME_ELEMENT(KEY_TOUCHPAD_ON),
NAME_ELEMENT(KEY_TOUCHPAD_OFF),
#endif
#ifdef KEY_CAMERA_ZOOMIN
NAME_ELEMENT(KEY_CAMERA_ZOOMIN), NAME_ELEMENT(KEY_CAMERA_ZOOMOUT),
NAME_ELEMENT(KEY_CAMERA_UP), NAME_ELEMENT(KEY_CAMERA_DOWN),
NAME_ELEMENT(KEY_CAMERA_LEFT), NAME_ELEMENT(KEY_CAMERA_RIGHT),
#endif
#ifdef KEY_ATTENDANT_ON
NAME_ELEMENT(KEY_ATTENDANT_ON), NAME_ELEMENT(KEY_ATTENDANT_OFF),
NAME_ELEMENT(KEY_ATTENDANT_TOGGLE), NAME_ELEMENT(KEY_LIGHTS_TOGGLE),
#endif
NAME_ELEMENT(BTN_0), NAME_ELEMENT(BTN_1),
NAME_ELEMENT(BTN_2), NAME_ELEMENT(BTN_3),
NAME_ELEMENT(BTN_4), NAME_ELEMENT(BTN_5),
NAME_ELEMENT(BTN_6), NAME_ELEMENT(BTN_7),
NAME_ELEMENT(BTN_8), NAME_ELEMENT(BTN_9),
NAME_ELEMENT(BTN_LEFT), NAME_ELEMENT(BTN_RIGHT),
NAME_ELEMENT(BTN_MIDDLE), NAME_ELEMENT(BTN_SIDE),
NAME_ELEMENT(BTN_EXTRA), NAME_ELEMENT(BTN_FORWARD),
NAME_ELEMENT(BTN_BACK), NAME_ELEMENT(BTN_TASK),
NAME_ELEMENT(BTN_TRIGGER), NAME_ELEMENT(BTN_THUMB),
NAME_ELEMENT(BTN_THUMB2), NAME_ELEMENT(BTN_TOP),
NAME_ELEMENT(BTN_TOP2), NAME_ELEMENT(BTN_PINKIE),
NAME_ELEMENT(BTN_BASE), NAME_ELEMENT(BTN_BASE2),
NAME_ELEMENT(BTN_BASE3), NAME_ELEMENT(BTN_BASE4),
NAME_ELEMENT(BTN_BASE5), NAME_ELEMENT(BTN_BASE6),
NAME_ELEMENT(BTN_DEAD), NAME_ELEMENT(BTN_C),
#ifdef BTN_SOUTH
NAME_ELEMENT(BTN_SOUTH), NAME_ELEMENT(BTN_EAST),
NAME_ELEMENT(BTN_NORTH), NAME_ELEMENT(BTN_WEST),
#else
NAME_ELEMENT(BTN_A), NAME_ELEMENT(BTN_B),
NAME_ELEMENT(BTN_X), NAME_ELEMENT(BTN_Y),
#endif
NAME_ELEMENT(BTN_Z), NAME_ELEMENT(BTN_TL),
NAME_ELEMENT(BTN_TR), NAME_ELEMENT(BTN_TL2),
NAME_ELEMENT(BTN_TR2), NAME_ELEMENT(BTN_SELECT),
NAME_ELEMENT(BTN_START), NAME_ELEMENT(BTN_MODE),
NAME_ELEMENT(BTN_THUMBL), NAME_ELEMENT(BTN_THUMBR),
NAME_ELEMENT(BTN_TOOL_PEN), NAME_ELEMENT(BTN_TOOL_RUBBER),
NAME_ELEMENT(BTN_TOOL_BRUSH), NAME_ELEMENT(BTN_TOOL_PENCIL),
NAME_ELEMENT(BTN_TOOL_AIRBRUSH), NAME_ELEMENT(BTN_TOOL_FINGER),
NAME_ELEMENT(BTN_TOOL_MOUSE), NAME_ELEMENT(BTN_TOOL_LENS),
NAME_ELEMENT(BTN_TOUCH), NAME_ELEMENT(BTN_STYLUS),
NAME_ELEMENT(BTN_STYLUS2), NAME_ELEMENT(BTN_TOOL_DOUBLETAP),
NAME_ELEMENT(BTN_TOOL_TRIPLETAP),
#ifdef BTN_TOOL_QUADTAP
NAME_ELEMENT(BTN_TOOL_QUADTAP),
#endif
NAME_ELEMENT(BTN_GEAR_DOWN),
NAME_ELEMENT(BTN_GEAR_UP),
#ifdef BTN_DPAD_UP
NAME_ELEMENT(BTN_DPAD_UP), NAME_ELEMENT(BTN_DPAD_DOWN),
NAME_ELEMENT(BTN_DPAD_LEFT), NAME_ELEMENT(BTN_DPAD_RIGHT),
#endif
#ifdef KEY_ALS_TOGGLE
NAME_ELEMENT(KEY_ALS_TOGGLE),
#endif
#ifdef KEY_BUTTONCONFIG
NAME_ELEMENT(KEY_BUTTONCONFIG),
#endif
#ifdef KEY_TASKMANAGER
NAME_ELEMENT(KEY_TASKMANAGER),
#endif
#ifdef KEY_JOURNAL
NAME_ELEMENT(KEY_JOURNAL),
#endif
#ifdef KEY_CONTROLPANEL
NAME_ELEMENT(KEY_CONTROLPANEL),
#endif
#ifdef KEY_APPSELECT
NAME_ELEMENT(KEY_APPSELECT),
#endif
#ifdef KEY_SCREENSAVER
NAME_ELEMENT(KEY_SCREENSAVER),
#endif
#ifdef KEY_VOICECOMMAND
NAME_ELEMENT(KEY_VOICECOMMAND),
#endif
#ifdef KEY_BRIGHTNESS_MIN
NAME_ELEMENT(KEY_BRIGHTNESS_MIN),
#endif
#ifdef KEY_BRIGHTNESS_MAX
NAME_ELEMENT(KEY_BRIGHTNESS_MAX),
#endif
#ifdef KEY_KBDINPUTASSIST_PREV
NAME_ELEMENT(KEY_KBDINPUTASSIST_PREV),
#endif
#ifdef KEY_KBDINPUTASSIST_NEXT
NAME_ELEMENT(KEY_KBDINPUTASSIST_NEXT),
#endif
#ifdef KEY_KBDINPUTASSIST_PREVGROUP
NAME_ELEMENT(KEY_KBDINPUTASSIST_PREVGROUP),
#endif
#ifdef KEY_KBDINPUTASSIST_NEXTGROUP
NAME_ELEMENT(KEY_KBDINPUTASSIST_NEXTGROUP),
#endif
#ifdef KEY_KBDINPUTASSIST_ACCEPT
NAME_ELEMENT(KEY_KBDINPUTASSIST_ACCEPT),
#endif
#ifdef KEY_KBDINPUTASSIST_CANCEL
NAME_ELEMENT(KEY_KBDINPUTASSIST_CANCEL),
#endif
#ifdef BTN_TRIGGER_HAPPY
NAME_ELEMENT(BTN_TRIGGER_HAPPY1), NAME_ELEMENT(BTN_TRIGGER_HAPPY11),
NAME_ELEMENT(BTN_TRIGGER_HAPPY2), NAME_ELEMENT(BTN_TRIGGER_HAPPY12),
NAME_ELEMENT(BTN_TRIGGER_HAPPY3), NAME_ELEMENT(BTN_TRIGGER_HAPPY13),
NAME_ELEMENT(BTN_TRIGGER_HAPPY4), NAME_ELEMENT(BTN_TRIGGER_HAPPY14),
NAME_ELEMENT(BTN_TRIGGER_HAPPY5), NAME_ELEMENT(BTN_TRIGGER_HAPPY15),
NAME_ELEMENT(BTN_TRIGGER_HAPPY6), NAME_ELEMENT(BTN_TRIGGER_HAPPY16),
NAME_ELEMENT(BTN_TRIGGER_HAPPY7), NAME_ELEMENT(BTN_TRIGGER_HAPPY17),
NAME_ELEMENT(BTN_TRIGGER_HAPPY8), NAME_ELEMENT(BTN_TRIGGER_HAPPY18),
NAME_ELEMENT(BTN_TRIGGER_HAPPY9), NAME_ELEMENT(BTN_TRIGGER_HAPPY19),
NAME_ELEMENT(BTN_TRIGGER_HAPPY10), NAME_ELEMENT(BTN_TRIGGER_HAPPY20),
NAME_ELEMENT(BTN_TRIGGER_HAPPY21), NAME_ELEMENT(BTN_TRIGGER_HAPPY31),
NAME_ELEMENT(BTN_TRIGGER_HAPPY22), NAME_ELEMENT(BTN_TRIGGER_HAPPY32),
NAME_ELEMENT(BTN_TRIGGER_HAPPY23), NAME_ELEMENT(BTN_TRIGGER_HAPPY33),
NAME_ELEMENT(BTN_TRIGGER_HAPPY24), NAME_ELEMENT(BTN_TRIGGER_HAPPY34),
NAME_ELEMENT(BTN_TRIGGER_HAPPY25), NAME_ELEMENT(BTN_TRIGGER_HAPPY35),
NAME_ELEMENT(BTN_TRIGGER_HAPPY26), NAME_ELEMENT(BTN_TRIGGER_HAPPY36),
NAME_ELEMENT(BTN_TRIGGER_HAPPY27), NAME_ELEMENT(BTN_TRIGGER_HAPPY37),
NAME_ELEMENT(BTN_TRIGGER_HAPPY28), NAME_ELEMENT(BTN_TRIGGER_HAPPY38),
NAME_ELEMENT(BTN_TRIGGER_HAPPY29), NAME_ELEMENT(BTN_TRIGGER_HAPPY39),
NAME_ELEMENT(BTN_TRIGGER_HAPPY30), NAME_ELEMENT(BTN_TRIGGER_HAPPY40),
#endif
#ifdef BTN_TOOL_QUINTTAP
NAME_ELEMENT(BTN_TOOL_QUINTTAP),
#endif
};
static const char * const absval[6] = { "Value", "Min ", "Max ", "Fuzz ", "Flat ", "Resolution "};
static const char * const relatives[REL_MAX + 1] = {
[0 ... REL_MAX] = NULL,
NAME_ELEMENT(REL_X), NAME_ELEMENT(REL_Y),
NAME_ELEMENT(REL_Z), NAME_ELEMENT(REL_RX),
NAME_ELEMENT(REL_RY), NAME_ELEMENT(REL_RZ),
NAME_ELEMENT(REL_HWHEEL),
NAME_ELEMENT(REL_DIAL), NAME_ELEMENT(REL_WHEEL),
NAME_ELEMENT(REL_MISC),
};
static const char * const absolutes[ABS_MAX + 1] = {
[0 ... ABS_MAX] = NULL,
NAME_ELEMENT(ABS_X), NAME_ELEMENT(ABS_Y),
NAME_ELEMENT(ABS_Z), NAME_ELEMENT(ABS_RX),
NAME_ELEMENT(ABS_RY), NAME_ELEMENT(ABS_RZ),
NAME_ELEMENT(ABS_THROTTLE), NAME_ELEMENT(ABS_RUDDER),
NAME_ELEMENT(ABS_WHEEL), NAME_ELEMENT(ABS_GAS),
NAME_ELEMENT(ABS_BRAKE), NAME_ELEMENT(ABS_HAT0X),
NAME_ELEMENT(ABS_HAT0Y), NAME_ELEMENT(ABS_HAT1X),
NAME_ELEMENT(ABS_HAT1Y), NAME_ELEMENT(ABS_HAT2X),
NAME_ELEMENT(ABS_HAT2Y), NAME_ELEMENT(ABS_HAT3X),
NAME_ELEMENT(ABS_HAT3Y), NAME_ELEMENT(ABS_PRESSURE),
NAME_ELEMENT(ABS_DISTANCE), NAME_ELEMENT(ABS_TILT_X),
NAME_ELEMENT(ABS_TILT_Y), NAME_ELEMENT(ABS_TOOL_WIDTH),
NAME_ELEMENT(ABS_VOLUME), NAME_ELEMENT(ABS_MISC),
#ifdef ABS_MT_BLOB_ID
NAME_ELEMENT(ABS_MT_TOUCH_MAJOR),
NAME_ELEMENT(ABS_MT_TOUCH_MINOR),
NAME_ELEMENT(ABS_MT_WIDTH_MAJOR),
NAME_ELEMENT(ABS_MT_WIDTH_MINOR),
NAME_ELEMENT(ABS_MT_ORIENTATION),
NAME_ELEMENT(ABS_MT_POSITION_X),
NAME_ELEMENT(ABS_MT_POSITION_Y),
NAME_ELEMENT(ABS_MT_TOOL_TYPE),
NAME_ELEMENT(ABS_MT_BLOB_ID),
#endif
#ifdef ABS_MT_TRACKING_ID
NAME_ELEMENT(ABS_MT_TRACKING_ID),
#endif
#ifdef ABS_MT_PRESSURE
NAME_ELEMENT(ABS_MT_PRESSURE),
#endif
#ifdef ABS_MT_SLOT
NAME_ELEMENT(ABS_MT_SLOT),
#endif
#ifdef ABS_MT_TOOL_X
NAME_ELEMENT(ABS_MT_TOOL_X),
NAME_ELEMENT(ABS_MT_TOOL_Y),
NAME_ELEMENT(ABS_MT_DISTANCE),
#endif
};
static const char * const misc[MSC_MAX + 1] = {
[ 0 ... MSC_MAX] = NULL,
NAME_ELEMENT(MSC_SERIAL), NAME_ELEMENT(MSC_PULSELED),
NAME_ELEMENT(MSC_GESTURE), NAME_ELEMENT(MSC_RAW),
NAME_ELEMENT(MSC_SCAN),
#ifdef MSC_TIMESTAMP
NAME_ELEMENT(MSC_TIMESTAMP),
#endif
};
static const char * const leds[LED_MAX + 1] = {
[0 ... LED_MAX] = NULL,
NAME_ELEMENT(LED_NUML), NAME_ELEMENT(LED_CAPSL),
NAME_ELEMENT(LED_SCROLLL), NAME_ELEMENT(LED_COMPOSE),
NAME_ELEMENT(LED_KANA), NAME_ELEMENT(LED_SLEEP),
NAME_ELEMENT(LED_SUSPEND), NAME_ELEMENT(LED_MUTE),
NAME_ELEMENT(LED_MISC),
#ifdef LED_MAIL
NAME_ELEMENT(LED_MAIL),
#endif
#ifdef LED_CHARGING
NAME_ELEMENT(LED_CHARGING),
#endif
};
static const char * const repeats[REP_MAX + 1] = {
[0 ... REP_MAX] = NULL,
NAME_ELEMENT(REP_DELAY), NAME_ELEMENT(REP_PERIOD)
};
static const char * const sounds[SND_MAX + 1] = {
[0 ... SND_MAX] = NULL,
NAME_ELEMENT(SND_CLICK), NAME_ELEMENT(SND_BELL),
NAME_ELEMENT(SND_TONE)
};
static const char * const syns[SYN_MAX + 1] = {
[0 ... SYN_MAX] = NULL,
NAME_ELEMENT(SYN_REPORT),
NAME_ELEMENT(SYN_CONFIG),
NAME_ELEMENT(SYN_MT_REPORT),
NAME_ELEMENT(SYN_DROPPED)
};
static const char * const switches[SW_MAX + 1] = {
[0 ... SW_MAX] = NULL,
NAME_ELEMENT(SW_LID),
NAME_ELEMENT(SW_TABLET_MODE),
NAME_ELEMENT(SW_HEADPHONE_INSERT),
#ifdef SW_RFKILL_ALL
NAME_ELEMENT(SW_RFKILL_ALL),
#endif
#ifdef SW_MICROPHONE_INSERT
NAME_ELEMENT(SW_MICROPHONE_INSERT),
#endif
#ifdef SW_DOCK
NAME_ELEMENT(SW_DOCK),
#endif
#ifdef SW_LINEOUT_INSERT
NAME_ELEMENT(SW_LINEOUT_INSERT),
#endif
#ifdef SW_JACK_PHYSICAL_INSERT
NAME_ELEMENT(SW_JACK_PHYSICAL_INSERT),
#endif
#ifdef SW_VIDEOOUT_INSERT
NAME_ELEMENT(SW_VIDEOOUT_INSERT),
#endif
#ifdef SW_CAMERA_LENS_COVER
NAME_ELEMENT(SW_CAMERA_LENS_COVER),
NAME_ELEMENT(SW_KEYPAD_SLIDE),
NAME_ELEMENT(SW_FRONT_PROXIMITY),
#endif
#ifdef SW_ROTATE_LOCK
NAME_ELEMENT(SW_ROTATE_LOCK),
#endif
#ifdef SW_LINEIN_INSERT
NAME_ELEMENT(SW_LINEIN_INSERT),
#endif
#ifdef SW_MUTE_DEVICE
NAME_ELEMENT(SW_MUTE_DEVICE),
#endif
};
static const char * const force[FF_MAX + 1] = {
[0 ... FF_MAX] = NULL,
NAME_ELEMENT(FF_RUMBLE), NAME_ELEMENT(FF_PERIODIC),
NAME_ELEMENT(FF_CONSTANT), NAME_ELEMENT(FF_SPRING),
NAME_ELEMENT(FF_FRICTION), NAME_ELEMENT(FF_DAMPER),
NAME_ELEMENT(FF_INERTIA), NAME_ELEMENT(FF_RAMP),
NAME_ELEMENT(FF_SQUARE), NAME_ELEMENT(FF_TRIANGLE),
NAME_ELEMENT(FF_SINE), NAME_ELEMENT(FF_SAW_UP),
NAME_ELEMENT(FF_SAW_DOWN), NAME_ELEMENT(FF_CUSTOM),
NAME_ELEMENT(FF_GAIN), NAME_ELEMENT(FF_AUTOCENTER),
};
static const char * const forcestatus[FF_STATUS_MAX + 1] = {
[0 ... FF_STATUS_MAX] = NULL,
NAME_ELEMENT(FF_STATUS_STOPPED), NAME_ELEMENT(FF_STATUS_PLAYING),
};
static const char * const * const names[EV_MAX + 1] = {
[0 ... EV_MAX] = NULL,
[EV_SYN] = syns, [EV_KEY] = keys,
[EV_REL] = relatives, [EV_ABS] = absolutes,
[EV_MSC] = misc, [EV_LED] = leds,
[EV_SND] = sounds, [EV_REP] = repeats,
[EV_SW] = switches,
[EV_FF] = force, [EV_FF_STATUS] = forcestatus,
};
/**
* Convert a string to a specific key/snd/led/sw code. The string can either
* be the name of the key in question (e.g. "SW_DOCK") or the numerical
* value, either as decimal (e.g. "5") or as hex (e.g. "0x5").
*
* @param mode The mode being queried (key, snd, led, sw)
* @param kstr The string to parse and convert
*
* @return The requested code's numerical value, or negative on error.
*/
static int get_keycode(const struct query_mode *query_mode, const char *kstr)
{
if (isdigit(kstr[0])) {
unsigned long val;
errno = 0;
val = strtoul(kstr, NULL, 0);
if (errno) {
fprintf(stderr, "Could not interpret value %s\n", kstr);
return -1;
}
return (int) val;
} else {
const char * const *keynames = names[query_mode->event_type];
int i;
for (i = 0; i < query_mode->max; i++) {
const char *name = keynames[i];
if (name && strcmp(name, kstr) == 0)
return i;
}
return -1;
}
}
/**
* Filter for the AutoDevProbe scandir on /dev/input.
*
* @param dir The current directory entry provided by scandir.
*
* @return Non-zero if the given directory entry starts with "event", or zero
* otherwise.
*/
static int is_event_device(const struct dirent *dir) {
return strncmp(EVENT_DEV_NAME, dir->d_name, 5) == 0;
}
/**
* Scans all /dev/input/event*, display them and ask the user which one to
* open.
*
* @return The event device file name of the device file selected. This
* string is allocated and must be freed by the caller.
*/
static char* scan_devices(void)
{
struct dirent **namelist;
int i, ndev, devnum;
char *filename;
int max_device = 0;
ndev = scandir(DEV_INPUT_EVENT, &namelist, is_event_device, versionsort);
if (ndev <= 0)
return NULL;
fprintf(stderr, "Available devices:\n");
for (i = 0; i < ndev; i++)
{
char fname[64];
int fd = -1;
char name[256] = "???";
snprintf(fname, sizeof(fname),
"%s/%s", DEV_INPUT_EVENT, namelist[i]->d_name);
fd = open(fname, O_RDONLY);
if (fd < 0)
continue;
ioctl(fd, EVIOCGNAME(sizeof(name)), name);
fprintf(stderr, "%s: %s\n", fname, name);
close(fd);
sscanf(namelist[i]->d_name, "event%d", &devnum);
if (devnum > max_device)
max_device = devnum;
free(namelist[i]);
}
fprintf(stderr, "Select the device event number [0-%d]: ", max_device);
scanf("%d", &devnum);
if (devnum > max_device || devnum < 0)
return NULL;
asprintf(&filename, "%s/%s%d",
DEV_INPUT_EVENT, EVENT_DEV_NAME,
devnum);
return filename;
}
static int version(void)
{
#ifndef PACKAGE_VERSION
#define PACKAGE_VERSION "<version undefined>"
#endif
printf("%s %s\n", program_invocation_short_name, PACKAGE_VERSION);
return EXIT_SUCCESS;
}
/**
* Print usage information.
*/
static int usage(void)
{
printf("USAGE:\n");
printf(" Capture mode:\n");
printf(" %s [--grab] /dev/input/eventX\n", program_invocation_short_name);
printf(" --grab grab the device for exclusive access\n");
printf("\n");
printf(" Query mode: (check exit code)\n");
printf(" %s --query /dev/input/eventX <type> <value>\n",
program_invocation_short_name);
printf("\n");
printf("<type> is one of: EV_KEY, EV_SW, EV_LED, EV_SND\n");
printf("<value> can either be a numerical value, or the textual name of the\n");
printf("key/switch/LED/sound being queried (e.g. SW_DOCK).\n");
return EXIT_FAILURE;
}
/**
* Print additional information for absolute axes (min/max, current value,
* etc.).
*
* @param fd The file descriptor to the device.
* @param axis The axis identifier (e.g. ABS_X).
*/
static void print_absdata(int fd, int axis)
{
int abs[6] = {0};
int k;
ioctl(fd, EVIOCGABS(axis), abs);
for (k = 0; k < 6; k++)
if ((k < 3) || abs[k])
printf(" %s %6d\n", absval[k], abs[k]);
}
static void print_repdata(int fd)
{
int i;
unsigned int rep[2];
ioctl(fd, EVIOCGREP, rep);
for (i = 0; i <= REP_MAX; i++) {
printf(" Repeat code %d (%s)\n", i, names[EV_REP] ? (names[EV_REP][i] ? names[EV_REP][i] : "?") : "?");
printf(" Value %6d\n", rep[i]);
}
}
static inline const char* typename(unsigned int type)
{
return (type <= EV_MAX && events[type]) ? events[type] : "?";
}
static inline const char* codename(unsigned int type, unsigned int code)
{
return (type <= EV_MAX && code <= maxval[type] && names[type] && names[type][code]) ? names[type][code] : "?";
}
#ifdef INPUT_PROP_SEMI_MT
static inline const char* propname(unsigned int prop)
{
return (prop <= INPUT_PROP_MAX && props[prop]) ? props[prop] : "?";
}
#endif
/**
* Print static device information (no events). This information includes
* version numbers, device name and all bits supported by this device.
*
* @param fd The file descriptor to the device.
* @return 0 on success or 1 otherwise.
*/
static int print_device_info(int fd)
{
unsigned int type, code;
int version;
unsigned short id[4];
char name[256] = "Unknown";
unsigned long bit[EV_MAX][NBITS(KEY_MAX)];
#ifdef INPUT_PROP_SEMI_MT
unsigned int prop;
unsigned long propbits[INPUT_PROP_MAX];
#endif
if (ioctl(fd, EVIOCGVERSION, &version)) {
perror("evtest: can't get version");
return 1;
}
printf("Input driver version is %d.%d.%d\n",
version >> 16, (version >> 8) & 0xff, version & 0xff);
ioctl(fd, EVIOCGID, id);
printf("Input device ID: bus 0x%x vendor 0x%x product 0x%x version 0x%x\n",
id[ID_BUS], id[ID_VENDOR], id[ID_PRODUCT], id[ID_VERSION]);
ioctl(fd, EVIOCGNAME(sizeof(name)), name);
printf("Input device name: \"%s\"\n", name);
memset(bit, 0, sizeof(bit));
ioctl(fd, EVIOCGBIT(0, EV_MAX), bit[0]);
printf("Supported events:\n");
for (type = 0; type < EV_MAX; type++) {
if (test_bit(type, bit[0]) && type != EV_REP) {
printf(" Event type %d (%s)\n", type, typename(type));
if (type == EV_SYN) continue;
ioctl(fd, EVIOCGBIT(type, KEY_MAX), bit[type]);
for (code = 0; code < KEY_MAX; code++)
if (test_bit(code, bit[type])) {
printf(" Event code %d (%s)\n", code, codename(type, code));
if (type == EV_ABS)
print_absdata(fd, code);
}
}
}
if (test_bit(EV_REP, bit[0])) {
printf("Key repeat handling:\n");
printf(" Repeat type %d (%s)\n", EV_REP, events[EV_REP] ? events[EV_REP] : "?");
print_repdata(fd);
}
#ifdef INPUT_PROP_SEMI_MT
memset(propbits, 0, sizeof(propbits));
ioctl(fd, EVIOCGPROP(sizeof(propbits)), propbits);
printf("Properties:\n");
for (prop = 0; prop < INPUT_PROP_MAX; prop++) {
if (test_bit(prop, propbits))
printf(" Property type %d (%s)\n", prop, propname(prop));
}
#endif
return 0;
}
/**
* Print device events as they come in.
*
* @param fd The file descriptor to the device.
* @return 0 on success or 1 otherwise.
*/
static int print_events(int fd)
{
struct input_event ev[64];
int i, rd;
fd_set rdfs;
FD_ZERO(&rdfs);
FD_SET(fd, &rdfs);
while (!stop) {
select(fd + 1, &rdfs, NULL, NULL, NULL);
if (stop)
break;
rd = read(fd, ev, sizeof(ev));
if (rd < (int) sizeof(struct input_event)) {
printf("expected %d bytes, got %d\n", (int) sizeof(struct input_event), rd);
perror("\nevtest: error reading");
return 1;
}
for (i = 0; i < rd / sizeof(struct input_event); i++) {
unsigned int type, code;
type = ev[i].type;
code = ev[i].code;
printf("Event: time %ld.%06ld, ", ev[i].time.tv_sec, ev[i].time.tv_usec);
if (type == EV_SYN) {
if (code == SYN_MT_REPORT)
printf("++++++++++++++ %s ++++++++++++\n", codename(type, code));
else if (code == SYN_DROPPED)
printf(">>>>>>>>>>>>>> %s <<<<<<<<<<<<\n", codename(type, code));
else
printf("-------------- %s ------------\n", codename(type, code));
} else {
printf("type %d (%s), code %d (%s), ",
type, typename(type),
code, codename(type, code));
if (type == EV_MSC && (code == MSC_RAW || code == MSC_SCAN))
printf("value %02x\n", ev[i].value);
else
printf("value %d\n", ev[i].value);
}
}
}
ioctl(fd, EVIOCGRAB, (void*)0);
return EXIT_SUCCESS;
}
/**
* Grab and immediately ungrab the device.
*
* @param fd The file descriptor to the device.
* @return 0 if the grab was successful, or 1 otherwise.
*/
static int test_grab(int fd, int grab_flag)
{
int rc;
rc = ioctl(fd, EVIOCGRAB, (void*)1);
if (rc == 0 && !grab_flag)
ioctl(fd, EVIOCGRAB, (void*)0);
return rc;
}
/**
* Enter capture mode. The requested event device will be monitored, and any
* captured events will be decoded and printed on the console.
*
* @param device The device to monitor, or NULL if the user should be prompted.
* @return 0 on success, non-zero on error.
*/
static int do_capture(const char *device, int grab_flag)
{
int fd;
char *filename = NULL;
if (!device) {
fprintf(stderr, "No device specified, trying to scan all of %s/%s*\n",
DEV_INPUT_EVENT, EVENT_DEV_NAME);
if (getuid() != 0)
fprintf(stderr, "Not running as root, no devices may be available.\n");
filename = scan_devices();
if (!filename)
return usage();
} else
filename = strdup(device);
if (!filename)
return EXIT_FAILURE;
if ((fd = open(filename, O_RDONLY)) < 0) {
perror("evtest");
if (errno == EACCES && getuid() != 0)
fprintf(stderr, "You do not have access to %s. Try "
"running as root instead.\n",
filename);
goto error;
}
if (!isatty(fileno(stdout)))
setbuf(stdout, NULL);
if (print_device_info(fd))
goto error;
printf("Testing ... (interrupt to exit)\n");
if (test_grab(fd, grab_flag))
{
printf("***********************************************\n");
printf(" This device is grabbed by another process.\n");
printf(" No events are available to evtest while the\n"
" other grab is active.\n");
printf(" In most cases, this is caused by an X driver,\n"
" try VT-switching and re-run evtest again.\n");
printf(" Run the following command to see processes with\n"
" an open fd on this device\n"
" \"fuser -v %s\"\n", filename);
printf("***********************************************\n");
}
signal(SIGINT, interrupt_handler);
signal(SIGTERM, interrupt_handler);
free(filename);
return print_events(fd);
error:
free(filename);
return EXIT_FAILURE;
}
/**
* Perform a one-shot state query on a specific device. The query can be of
* any known mode, on any valid keycode.
*
* @param device Path to the evdev device node that should be queried.
* @param query_mode The event type that is being queried (e.g. key, switch)
* @param keycode The code of the key/switch/sound/LED to be queried
* @return 0 if the state bit is unset, 10 if the state bit is set, 1 on error.
*/
static int query_device(const char *device, const struct query_mode *query_mode, int keycode)
{
int fd;
int r;
unsigned long state[NBITS(query_mode->max)];
fd = open(device, O_RDONLY);
if (fd < 0) {
perror("open");
return EXIT_FAILURE;
}
memset(state, 0, sizeof(state));
r = ioctl(fd, query_mode->rq, state);
close(fd);
if (r == -1) {
perror("ioctl");
return EXIT_FAILURE;
}
if (test_bit(keycode, state))
return 10; /* different from EXIT_FAILURE */
else
return 0;
}
/**
* Enter query mode. The requested event device will be queried for the state
* of a particular switch/key/sound/LED.
*
* @param device The device to query.
* @param mode The mode (event type) that is to be queried (snd, sw, key, led)
* @param keycode The key code to query the state of.
* @return 0 if the state bit is unset, 10 if the state bit is set.
*/
static int do_query(const char *device, const char *event_type, const char *keyname)
{
const struct query_mode *query_mode;
int keycode;
if (!device) {
fprintf(stderr, "Device argument is required for query.\n");
return usage();
}
query_mode = find_query_mode(event_type);
if (!query_mode) {
fprintf(stderr, "Unrecognised event type: %s\n", event_type);
return usage();
}
keycode = get_keycode(query_mode, keyname);
if (keycode < 0) {
fprintf(stderr, "Unrecognised key name: %s\n", keyname);
return usage();
} else if (keycode > query_mode->max) {
fprintf(stderr, "Key %d is out of bounds.\n", keycode);
return EXIT_FAILURE;
}
return query_device(device, query_mode, keycode);
}
static const struct option long_options[] = {
{ "grab", no_argument, &grab_flag, 1 },
{ "query", no_argument, NULL, MODE_QUERY },
{ "version", no_argument, NULL, MODE_VERSION },
{ 0, },
};
int main (int argc, char **argv)
{
const char *device = NULL;
const char *keyname;
const char *event_type;
enum evtest_mode mode = MODE_CAPTURE;
while (1) {
int option_index = 0;
int c = getopt_long(argc, argv, "", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
break;
case MODE_QUERY:
mode = c;
break;
case MODE_VERSION:
return version();
default:
return usage();
}
}
if (optind < argc)
device = argv[optind++];
if (mode == MODE_CAPTURE)
return do_capture(device, grab_flag);
if ((argc - optind) < 2) {
fprintf(stderr, "Query mode requires device, type and key parameters\n");
return usage();
}
event_type = argv[optind++];
keyname = argv[optind++];
return do_query(device, event_type, keyname);
}
/* vim: set noexpandtab tabstop=8 shiftwidth=8: */
|
the_stack_data/56703.c | #include <stdio.h> // cc -o microrg32 microrg32.c ; WORK=3 ; LEN=4 #######
#include <stdint.h> // SECRET="Something random like qhohxks5mx9elv6ujgx3"
#include <stdlib.h> // export P="$LEN:$SECRET:x.org" ## Public domain code
#define b(z) for(c=0;c<(z);c++) // ./microrg32 $WORK $LEN | head -1 | tail
uint32_t c,e[42],f[42],g=19,h=13,r,s,n[45],i,k;char*q;void m(){int c;r=0;b
(12)f[c+c%3*h]^=e[c+1];b(g){r=(r+c)%32;i=c*7%g;k=e[i++];k^=e[i%g]|~e[(i+1)
%g];n[c]=n[c+g]=k>>r|k<<-r%32;}for(c=39;c--;f[c+1]=f[c])e[c]=n[c]^n[c+1]^n
[c+4];*e^=1;b(3)e[c+h]^=f[c*h]=f[c*h+h];}int main(int p,char **v){q=getenv
("P");if(q&&p>2){for(;;m()){b(3){for(r=0;r<4;){f[c*h]^=k=(*q?*q&255:1)<<8*
r++;e[16+c]^=k;if(!*q++){p=0;b(17+(1<<*v[1]%32))m();b(983){s=e[1+c%2];r=c;
b(4){p=p>0?p:*v[2]%16;i=s;s>>=8;if(p!=0){i&=31;i+=i<8?50:89;}printf(p?"%c"
:"%02x",i&255);}c=r;if(c%2)m();if(--p<1||c>981)puts("");}return 0;}}}}}}//
|
the_stack_data/71045.c | #include <stdio.h>
#include <math.h>
#include <time.h>
/*
* pi_bbp_bench.c
*
* DIGIT 2005, Javat tanítok
* Bátfai Norbert, [email protected]
*
* A PiBBP.java-ból kivettük az "objektumorientáltságot", így kaptuk
* a PiBBPBench osztályt, amit pedig átírtuk C nyelvre.
*
*/
/*
* 16^n mod k
* [BBP ALGORITMUS] David H. Bailey: The
* BBP Algorithm for Pi. alapján.
*/
long
n16modk (int n, int k)
{
long r = 1;
int t = 1;
while (t <= n)
t *= 2;
for (;;)
{
if (n >= t)
{
r = (16 * r) % k;
n = n - t;
}
t = t / 2;
if (t < 1)
break;
r = (r * r) % k;
}
return r;
}
/* {16^d Sj}
* [BBP ALGORITMUS] David H. Bailey: The
* BBP Algorithm for Pi. alapján.
*/
double
d16Sj (int d, int j)
{
double d16Sj = 0.0;
int k;
for (k = 0; k <= d; ++k)
d16Sj += (double) n16modk (d - k, 8 * k + j) / (double) (8 * k + j);
/*
for(k=d+1; k<=2*d; ++k)
d16Sj += pow(16.0, d-k) / (double)(8*k + j);
*/
return d16Sj - floor (d16Sj);
}
/*
* {16^d Pi} = {4*{16^d S1} - 2*{16^d S4} - {16^d S5} - {16^d S6}}
* [BBP ALGORITMUS] David H. Bailey: The
* BBP Algorithm for Pi. alapján.
*/
int main ()
{
double d16Pi = 0.0;
double d16S1t = 0.0;
double d16S4t = 0.0;
double d16S5t = 0.0;
double d16S6t = 0.0;
int jegy;
int d;
clock_t delta = clock ();
for (d = 100000000; d < 100000001; ++d)
{
d16Pi = 0.0;
d16S1t = d16Sj (d, 1);
d16S4t = d16Sj (d, 4);
d16S5t = d16Sj (d, 5);
d16S6t = d16Sj (d, 6);
d16Pi = 4.0 * d16S1t - 2.0 * d16S4t - d16S5t - d16S6t;
d16Pi = d16Pi - floor (d16Pi);
jegy = (int) floor (16.0 * d16Pi);
}
printf ("%d\n", jegy);
delta = clock () - delta;
printf ("%f\n", (double) delta / CLOCKS_PER_SEC);
} |
the_stack_data/217095.c | extern const unsigned char Pods_CalculatorPP_ExampleVersionString[];
extern const double Pods_CalculatorPP_ExampleVersionNumber;
const unsigned char Pods_CalculatorPP_ExampleVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:Pods_CalculatorPP_Example PROJECT:Pods-1" "\n";
const double Pods_CalculatorPP_ExampleVersionNumber __attribute__ ((used)) = (double)1.;
|
the_stack_data/1120163.c | /*
* Verify the COMMPAGE emulation
*
* The ARM commpage is a set of user space helper functions provided
* by the kernel in an effort to ease portability of user space code
* between different CPUs with potentially different capabilities. It
* is a 32 bit invention and similar to the vdso segment in many ways.
*
* The ABI is documented in the Linux kernel:
* Documentation/arm/kernel_userspace_helpers.rst
*
* Copyright (c) 2020 Linaro Ltd
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#define ARM_COMMPAGE (0xffff0f00u)
#define ARM_KUSER_VERSION (*(int32_t *)(ARM_COMMPAGE + 0xfc))
typedef void * (get_tls_fn)(void);
#define ARM_KUSER_GET_TLS (*(get_tls_fn *)(ARM_COMMPAGE + 0xe0))
typedef int (cmpxchg_fn)(int oldval, int newval, volatile int *ptr);
#define ARM_KUSER_CMPXCHG (*(cmpxchg_fn *)(ARM_COMMPAGE + 0xc0))
typedef void (dmb_fn)(void);
#define ARM_KUSER_DMB (*(dmb_fn *)(ARM_COMMPAGE + 0xa0))
typedef int (cmpxchg64_fn)(const int64_t *oldval,
const int64_t *newval,
volatile int64_t *ptr);
#define ARM_KUSER_CMPXCHG64 (*(cmpxchg64_fn *)(ARM_COMMPAGE + 0x60))
#define fail_unless(x) \
do { \
if (!(x)) { \
fprintf(stderr, "FAILED at %s:%d\n", __FILE__, __LINE__); \
exit(EXIT_FAILURE); \
} \
} while (0)
int main(int argc, char *argv[argc])
{
void *kuser_tls;
int val = 1;
const int64_t oldval = 1, newval = 2;
int64_t val64 = 1;
fail_unless(ARM_KUSER_VERSION == 0x5);
kuser_tls = ARM_KUSER_GET_TLS();
printf("TLS = %p\n", kuser_tls);
fail_unless(kuser_tls != 0);
fail_unless(ARM_KUSER_CMPXCHG(1, 2, &val) == 0);
printf("val = %d\n", val);
/* this is a crash test, not checking an actual barrier occurs */
ARM_KUSER_DMB();
fail_unless(ARM_KUSER_CMPXCHG64(&oldval, &newval, &val64) == 0);
printf("val64 = %lld\n", val64);
return 0;
}
|
the_stack_data/91503.c | #include<stdio.h>
#include<stdlib.h>
#define MAX 30
struct queue{
int data[MAX];
int front,rear;
};
void init(struct queue *q)
{
q->front=-1;
q->rear=-1;
}
int isempty(struct queue *q)
{
if(q->rear==-1)
return(1);
else
return(0);
}
int full(struct queue *q)
{
if(q->rear+q->front==MAX-1)
{
printf("Queue is full\n");
return(1);
}
else
return(0);
}
void display(struct queue *q)
{
int i;
if(q->rear==-1)
{
printf("Queue is empty\n");
}
else
{
printf("The elements of the queue are:\n");
for(i=q->front;i<=q->rear;i++)
{
printf("%d\t",q->data[i]);
}
printf("\n");
}
}
void insert_front(struct queue *q,int ele)
{
int temp=0,i=q->rear+1;
if(full(q))
{
printf("the queue is full\n");
}
else if(isempty(q))
{
q->front=q->rear=0;
q->data[q->front]=ele;
}
else
{
while(i>=q->front)
{
q->data[i]=q->data[i-1];
i--;
}
q->data[q->front]=ele;
q->rear=q->rear+1;
}
}
void insert_rear(struct queue *q,int ele)
{
if(full(q))
{
printf("The queue is full\n");
}
else if(isempty(q))
{
q->front=q->rear=0;
q->data[q->rear]=ele;
}
else
{
q->rear++;
q->data[q->rear]=ele;
}
}
int delete_rear(struct queue *q)
{
int c=0;
if(isempty(q))
{
printf("Queue empty\n");
}
else
{
c=q->data[q->rear];
q->data[q->rear]=0;
if(q->rear==q->front)
{
init(q);
}
else
{
q->rear--;
}
}
return(c);
}
int delete_front(struct queue *q)
{
int c=0;
if(isempty(q))
{
printf("Queue empty\n");
}
else
{
c=q->data[q->front];
q->data[q->front]=0;
if(q->rear==q->front)
{
init(q);
}
else
{
q->front++;
}
}
return(c);
}
int main()
{
int choice;
int ele;
struct queue r;
init(&r);
do{
printf("Enter your choice:\n1-insert at front\n2-insert at rear\n3-delete front\n");
printf("4-delete rear\n5-display\n6-exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :printf("Enter the element to be inserted:\n");
scanf("%d",&ele);
insert_front(&r,ele);
break;
case 2 :printf("Enter the element to be inserted:\n");
scanf("%d",&ele);
insert_rear(&r,ele);
break;
case 3 : ele=delete_front(&r);
printf("The deleted element is %d \n",ele);
break;
case 4 : ele=delete_rear(&r);
printf("The deleted element is %d \n",ele);
break;
case 5 : display(&r);
}
}
while(choice!=6);
return(0);
}
|
the_stack_data/206393745.c | int minimumTotal(int** triangle, int triangleSize, int* triangleColSize)
{
for (int i = triangleSize - 2; i >= 0; i--)
for (int j = 0; j < triangleColSize[i]; j++)
triangle[i][j] += triangle[i + 1][j] > triangle[i + 1][j + 1] ?
triangle[i + 1][j + 1] : triangle[i + 1][j];
return triangle[0][0];
}
|
the_stack_data/11076442.c | /*Exercise 2 - Selection
Write a program to calculate the amount to be paid for a rented vehicle.
• Input the distance the van has travelled
• The first 30 km is at a rate of 50/= per km.
• The remaining distance is calculated at the rate of 40/= per km.
e.g.
Distance -> 20
Amount = 20 x 50 = 1000
Distance -> 50
Amount = 30 x 50 + (50-30) x 40 = 2300*/
#include <stdio.h>
int main()
{
//declare variables
int distance;
int price;
//user inputs
printf("enter the distance:");
scanf("%d",&distance);
//Selection
if(distance<30)
{
price = distance * 50;
}
if(distance>30)
{
price = 30 * 50 + (distance-30) * 40;
}
//dispaly
printf("price:%d",price);
return 0;
}
|
the_stack_data/181391889.c | /*
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
Example: 64 25 12 22 11
Will find the minimum element of the arry in range 0 to 4 and place it at the the beginning of the chosen array range.
11 25 12 22 64
then will find min element of thw array in range 1 to 4.
11 12 25 22 64
then in range 2 to 4.
11 12 22 25 64
*/
#include <stdio.h>
void main()
{
int i,j,k,l,temp,min;
int n=5;
int arry[5];
printf("Enter Elements: ");
for(i=0;i<n;i++)
scanf("%d",&arry[i]);
for(j=0;j<n-1;j++)
{
min=j;
for (k=j+1;k<n;k++)
{
if (arry[k]<arry[min])
min=k;
}
if (min!=j)
{
temp=arry[j];
arry[j]=arry[min];
arry[min]=temp;
}
}
printf("Sorted array: ");
for(l=0;l<n;l++)
printf("%d\t",arry[l]);
} |
the_stack_data/140076.c | ///TAFFO_TEST_ARGS -Xvra -propagate-all
#include <stdio.h>
int main(int argc, char *argv[])
{
__attribute__((annotate("scalar()"))) double magic = 1.234567890123456789;
printf("%a\n", magic + 2.3456778912345678);
}
|
the_stack_data/167329558.c | #include <stdio.h>
int main(){
double S=1.0, i=2;
while(i<=100.0){
S = S+(1/i);
i = i+1.0;
}
printf("%0.2lf\n" , S);
return 0;
} |
the_stack_data/93888289.c | #include <stdio.h>
#define FOUR_OVER_THREE_PI (4.0f / 3.0f * 3.142f)
int main(void)
{
float r, v;
printf("Input the radius: ");
scanf("%f", &r);
v = FOUR_OVER_THREE_PI * r * r * r;
printf("Volume of sphere for r=%.1f is %.3f", r, v);
return 0;
} |
the_stack_data/22013687.c | #include <stdio.h>
#include <string.h>
int main() {
char s[1001], t[1001];
scanf("%s%s", s, t);
int ans = -1;
if (strlen(s) != strlen(t)) {
printf("%d\n", ans);
return 0;
}
int s_len = strlen(s);
char ss[2001];
memcpy(ss, s, s_len);
memcpy(ss + s_len, s, s_len);
ss[s_len * 2] = '\0';
char *rot_s_left = ss + s_len;
for (int i = 0; i < s_len; i++) {
if (memcmp(t, rot_s_left, s_len) == 0) {
ans = i;
break;
}
rot_s_left--;
}
printf("%d\n", ans);
return 0;
}
|
the_stack_data/86276.c | #include <stdio.h>
int input = 0;
int input2 = 0;
int output = 0;
int output2 = 0;
int output3 = 0;
int* inputCell() {
return &input;
}
int* inputCell2() {
return &input2;
}
int* outputCell() {
return &output;
}
int* outputCell2() {
return &output2;
}
int* outputCell3() {
return &output3;
}
void cinput() {
printf("Enter first input:\n");
int x = scanf("%d", &input);
printf("Enter second input:\n");
x = scanf("%d", &input2);
} |
the_stack_data/165765595.c | #include<stdio.h>
int main(){
char c;
printf("please input a character : ");
c = getchar();
if(c < 32){
printf("This is a control character \n");
}else if(c >= '0' && c <= '9'){
printf("This is digit \n");
}else if(c >= 'A' && c <= 'Z'){
printf("This is a capital letter \n");
}else if(c >= 'a' && c <= 'z'){
printf("This is a small letter");
}else{
printf("This is an other character");
}
return 0;
}
|
the_stack_data/66730.c | void main()
{
float xx=2.3, yy=2.51;
int x = round(xx), y = round(yy);
print("x 2");
printid(x);
print("y 3");
printid(y);
print("x -2");
x = round(-xx);
printid(x);
print("y -3");
y = round(-yy);
printid(y);
}
|
the_stack_data/41076.c | #include <stdio.h>
#include <string.h>
int main()
{
int count = 0,count2 = 0,i,j;
char ch[10];
for(j=0;j<10;j++)
{
ch[j] = 0;
}
gets(ch);
for(j=0;j<10;j++)
{
if(ch[j]!=0)
{
count++;
}
}
printf("%d",count );
system("pause");
}
|
the_stack_data/25138926.c | int n;
int getint(){int x;scanf("%d",&x);return x;}
int putint(int x){printf("%d",x);}
int putchar(int x);
int f(int n)
{
putint(n);
n = 10;
putchar(n);
return 0;
}
int main()
{
n = getint();
if (n > 5) {
int n;
n = getint();
f(n);
}
else
f(getint());
f(n);
return 0;
}
|
the_stack_data/187644551.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_iterative_factorial.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ckala <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/11 20:05:20 by ckala #+# #+# */
/* Updated: 2021/12/14 09:45:57 by ckala ### ########.fr */
/* */
/* ************************************************************************** */
int ft_iterative_factorial(int nb)
{
int product;
product = 1;
if (nb < 0)
{
return (0);
}
else if (nb <= 1)
{
return (1);
}
while (nb != 0)
{
product = product * nb;
nb--;
}
return (product);
}
/*#include <stdio.h>
int main(){
int n;
n = 3;
printf("%d! = %d\n",n,ft_iterative_factorial(n));
return 0;
}*/
|
the_stack_data/168893630.c | // A basic clang -cc1 command-line, and simple environment check.
// RUN: %clang %s -### -no-canonical-prefixes -target riscv32 2>&1 | FileCheck -check-prefix=CC1 %s
// CC1: clang{{.*}} "-cc1" "-triple" "riscv32"
// RUN: %clang %s -### -no-canonical-prefixes \
// RUN: -target riscv32-unknown-elf \
// RUN: --gcc-toolchain=%S/Inputs/basic_riscv32_tree \
// RUN: --sysroot=%S/Inputs/basic_riscv32_tree/riscv32-unknown-elf 2>&1 \
// RUN: | FileCheck -check-prefix=C-RV32-BAREMETAL-ILP32 %s
// C-RV32-BAREMETAL-ILP32: "-fuse-init-array"
// C-RV32-BAREMETAL-ILP32: "{{.*}}Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../bin{{/|\\\\}}riscv32-unknown-elf-ld"
// C-RV32-BAREMETAL-ILP32: "--sysroot={{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf"
// C-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib{{/|\\\\}}crt0.o"
// C-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtbegin.o"
// C-RV32-BAREMETAL-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib"
// C-RV32-BAREMETAL-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1"
// C-RV32-BAREMETAL-ILP32: "--start-group" "-lc" "-lgloss" "--end-group" "-lgcc"
// C-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtend.o"
// RUN: %clang %s -### -no-canonical-prefixes \
// RUN: -target riscv32-unknown-elf \
// RUN: --sysroot= \
// RUN: --gcc-toolchain=%S/Inputs/basic_riscv32_tree 2>&1 \
// RUN: | FileCheck -check-prefix=C-RV32-BAREMETAL-NOSYSROOT-ILP32 %s
// C-RV32-BAREMETAL-NOSYSROOT-ILP32: "-fuse-init-array"
// C-RV32-BAREMETAL-NOSYSROOT-ILP32: "{{.*}}Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../bin{{/|\\\\}}riscv32-unknown-elf-ld"
// C-RV32-BAREMETAL-NOSYSROOT-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../riscv32-unknown-elf/lib{{/|\\\\}}crt0.o"
// C-RV32-BAREMETAL-NOSYSROOT-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtbegin.o"
// C-RV32-BAREMETAL-NOSYSROOT-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../riscv32-unknown-elf{{/|\\\\}}lib"
// C-RV32-BAREMETAL-NOSYSROOT-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1"
// C-RV32-BAREMETAL-NOSYSROOT-ILP32: "--start-group" "-lc" "-lgloss" "--end-group" "-lgcc"
// C-RV32-BAREMETAL-NOSYSROOT-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtend.o"
// RUN: %clangxx %s -### -no-canonical-prefixes \
// RUN: -target riscv32-unknown-elf -stdlib=libstdc++ \
// RUN: --gcc-toolchain=%S/Inputs/basic_riscv32_tree \
// RUN: --sysroot=%S/Inputs/basic_riscv32_tree/riscv32-unknown-elf 2>&1 \
// RUN: | FileCheck -check-prefix=CXX-RV32-BAREMETAL-ILP32 %s
// CXX-RV32-BAREMETAL-ILP32: "-fuse-init-array"
// CXX-RV32-BAREMETAL-ILP32: "-internal-isystem" "{{.*}}Inputs/basic_riscv32_tree/riscv32-unknown-elf/include/c++{{/|\\\\}}8.0.1"
// CXX-RV32-BAREMETAL-ILP32: "{{.*}}Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../bin{{/|\\\\}}riscv32-unknown-elf-ld"
// CXX-RV32-BAREMETAL-ILP32: "--sysroot={{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf"
// CXX-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib{{/|\\\\}}crt0.o"
// CXX-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtbegin.o"
// CXX-RV32-BAREMETAL-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib"
// CXX-RV32-BAREMETAL-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1"
// CXX-RV32-BAREMETAL-ILP32: "-lstdc++" "--start-group" "-lc" "-lgloss" "--end-group" "-lgcc"
// CXX-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtend.o"
// RUN: %clangxx %s -### -no-canonical-prefixes \
// RUN: -target riscv32-unknown-elf -stdlib=libstdc++ \
// RUN: --sysroot= \
// RUN: --gcc-toolchain=%S/Inputs/basic_riscv32_tree 2>&1 \
// RUN: | FileCheck -check-prefix=CXX-RV32-BAREMETAL-NOSYSROOT-ILP32 %s
// CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "-fuse-init-array"
// CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "-internal-isystem" "{{.*}}Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../riscv32-unknown-elf/include/c++{{/|\\\\}}8.0.1"
// CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "{{.*}}Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../bin{{/|\\\\}}riscv32-unknown-elf-ld"
// CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../riscv32-unknown-elf/lib{{/|\\\\}}crt0.o"
// CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtbegin.o"
// CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../riscv32-unknown-elf/lib"
// CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1"
// CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "-lstdc++" "--start-group" "-lc" "-lgloss" "--end-group" "-lgcc"
// CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtend.o"
// RUN: %clang %s -### -no-canonical-prefixes -fuse-ld=ld \
// RUN: -target riscv32-unknown-linux-gnu \
// RUN: --gcc-toolchain=%S/Inputs/multilib_riscv_linux_sdk \
// RUN: --sysroot=%S/Inputs/multilib_riscv_linux_sdk/sysroot 2>&1 \
// RUN: | FileCheck -check-prefix=C-RV32-LINUX-MULTI-ILP32 %s
// C-RV32-LINUX-MULTI-ILP32: "-fuse-init-array"
// C-RV32-LINUX-MULTI-ILP32: "{{.*}}/Inputs/multilib_riscv_linux_sdk/lib/gcc/riscv64-unknown-linux-gnu/7.2.0/../../../../riscv64-unknown-linux-gnu/bin{{/|\\\\}}ld"
// C-RV32-LINUX-MULTI-ILP32: "--sysroot={{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot"
// C-RV32-LINUX-MULTI-ILP32: "-m" "elf32lriscv"
// C-RV32-LINUX-MULTI-ILP32: "-dynamic-linker" "/lib/ld-linux-riscv32-ilp32.so.1"
// C-RV32-LINUX-MULTI-ILP32: "{{.*}}/Inputs/multilib_riscv_linux_sdk/lib/gcc/riscv64-unknown-linux-gnu/7.2.0/lib32/ilp32{{/|\\\\}}crtbegin.o"
// C-RV32-LINUX-MULTI-ILP32: "-L{{.*}}/Inputs/multilib_riscv_linux_sdk/lib/gcc/riscv64-unknown-linux-gnu/7.2.0/lib32/ilp32"
// C-RV32-LINUX-MULTI-ILP32: "-L{{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot/lib32/ilp32"
// C-RV32-LINUX-MULTI-ILP32: "-L{{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot/usr/lib32/ilp32"
// RUN: %clang %s -### -no-canonical-prefixes -fuse-ld=ld \
// RUN: -target riscv32-unknown-linux-gnu -march=rv32imafd -mabi=ilp32d \
// RUN: --gcc-toolchain=%S/Inputs/multilib_riscv_linux_sdk \
// RUN: --sysroot=%S/Inputs/multilib_riscv_linux_sdk/sysroot 2>&1 \
// RUN: | FileCheck -check-prefix=C-RV32-LINUX-MULTI-ILP32D %s
// C-RV32-LINUX-MULTI-ILP32D: "-fuse-init-array"
// C-RV32-LINUX-MULTI-ILP32D: "{{.*}}/Inputs/multilib_riscv_linux_sdk/lib/gcc/riscv64-unknown-linux-gnu/7.2.0/../../../../riscv64-unknown-linux-gnu/bin{{/|\\\\}}ld"
// C-RV32-LINUX-MULTI-ILP32D: "--sysroot={{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot"
// C-RV32-LINUX-MULTI-ILP32D: "-m" "elf32lriscv"
// C-RV32-LINUX-MULTI-ILP32D: "-dynamic-linker" "/lib/ld-linux-riscv32-ilp32d.so.1"
// C-RV32-LINUX-MULTI-ILP32D: "{{.*}}/Inputs/multilib_riscv_linux_sdk/lib/gcc/riscv64-unknown-linux-gnu/7.2.0/lib32/ilp32d{{/|\\\\}}crtbegin.o"
// C-RV32-LINUX-MULTI-ILP32D: "-L{{.*}}/Inputs/multilib_riscv_linux_sdk/lib/gcc/riscv64-unknown-linux-gnu/7.2.0/lib32/ilp32d"
// C-RV32-LINUX-MULTI-ILP32D: "-L{{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot/lib32/ilp32d"
// C-RV32-LINUX-MULTI-ILP32D: "-L{{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot/usr/lib32/ilp32d"
// RUN: %clang -target riscv32 %s -emit-llvm -S -o - | FileCheck %s
typedef __builtin_va_list va_list;
typedef __SIZE_TYPE__ size_t;
typedef __PTRDIFF_TYPE__ ptrdiff_t;
typedef __WCHAR_TYPE__ wchar_t;
typedef __WINT_TYPE__ wint_t;
// Check Alignments
// CHECK: @align_c = dso_local global i32 1
int align_c = __alignof(char);
// CHECK: @align_s = dso_local global i32 2
int align_s = __alignof(short);
// CHECK: @align_i = dso_local global i32 4
int align_i = __alignof(int);
// CHECK: @align_wc = dso_local global i32 4
int align_wc = __alignof(wchar_t);
// CHECK: @align_wi = dso_local global i32 4
int align_wi = __alignof(wint_t);
// CHECK: @align_l = dso_local global i32 4
int align_l = __alignof(long);
// CHECK: @align_ll = dso_local global i32 8
int align_ll = __alignof(long long);
// CHECK: @align_p = dso_local global i32 4
int align_p = __alignof(void*);
// CHECK: @align_f = dso_local global i32 4
int align_f = __alignof(float);
// CHECK: @align_d = dso_local global i32 8
int align_d = __alignof(double);
// CHECK: @align_ld = dso_local global i32 16
int align_ld = __alignof(long double);
// CHECK: @align_vl = dso_local global i32 4
int align_vl = __alignof(va_list);
// CHECK: @align_a_c = dso_local global i32 1
int align_a_c = __alignof(_Atomic(char));
// CHECK: @align_a_s = dso_local global i32 2
int align_a_s = __alignof(_Atomic(short));
// CHECK: @align_a_i = dso_local global i32 4
int align_a_i = __alignof(_Atomic(int));
// CHECK: @align_a_wc = dso_local global i32 4
int align_a_wc = __alignof(_Atomic(wchar_t));
// CHECK: @align_a_wi = dso_local global i32 4
int align_a_wi = __alignof(_Atomic(wint_t));
// CHECK: @align_a_l = dso_local global i32 4
int align_a_l = __alignof(_Atomic(long));
// CHECK: @align_a_ll = dso_local global i32 8
int align_a_ll = __alignof(_Atomic(long long));
// CHECK: @align_a_p = dso_local global i32 4
int align_a_p = __alignof(_Atomic(void*));
// CHECK: @align_a_f = dso_local global i32 4
int align_a_f = __alignof(_Atomic(float));
// CHECK: @align_a_d = dso_local global i32 8
int align_a_d = __alignof(_Atomic(double));
// CHECK: @align_a_ld = dso_local global i32 16
int align_a_ld = __alignof(_Atomic(long double));
// CHECK: @align_a_s4 = dso_local global i32 4
int align_a_s4 = __alignof(_Atomic(struct { char s[4]; }));
// CHECK: @align_a_s8 = dso_local global i32 8
int align_a_s8 = __alignof(_Atomic(struct { char s[8]; }));
// CHECK: @align_a_s16 = dso_local global i32 16
int align_a_s16 = __alignof(_Atomic(struct { char s[16]; }));
// CHECK: @align_a_s32 = dso_local global i32 1
int align_a_s32 = __alignof(_Atomic(struct { char s[32]; }));
// Check Sizes
// CHECK: @size_a_c = dso_local global i32 1
int size_a_c = sizeof(_Atomic(char));
// CHECK: @size_a_s = dso_local global i32 2
int size_a_s = sizeof(_Atomic(short));
// CHECK: @size_a_i = dso_local global i32 4
int size_a_i = sizeof(_Atomic(int));
// CHECK: @size_a_wc = dso_local global i32 4
int size_a_wc = sizeof(_Atomic(wchar_t));
// CHECK: @size_a_wi = dso_local global i32 4
int size_a_wi = sizeof(_Atomic(wint_t));
// CHECK: @size_a_l = dso_local global i32 4
int size_a_l = sizeof(_Atomic(long));
// CHECK: @size_a_ll = dso_local global i32 8
int size_a_ll = sizeof(_Atomic(long long));
// CHECK: @size_a_p = dso_local global i32 4
int size_a_p = sizeof(_Atomic(void*));
// CHECK: @size_a_f = dso_local global i32 4
int size_a_f = sizeof(_Atomic(float));
// CHECK: @size_a_d = dso_local global i32 8
int size_a_d = sizeof(_Atomic(double));
// CHECK: @size_a_ld = dso_local global i32 16
int size_a_ld = sizeof(_Atomic(long double));
// Check types
// CHECK: zeroext i8 @check_char()
char check_char() { return 0; }
// CHECK: define dso_local signext i16 @check_short()
short check_short() { return 0; }
// CHECK: define dso_local i32 @check_int()
int check_int() { return 0; }
// CHECK: define dso_local i32 @check_wchar_t()
int check_wchar_t() { return 0; }
// CHECK: define dso_local i32 @check_long()
long check_long() { return 0; }
// CHECK: define dso_local i64 @check_longlong()
long long check_longlong() { return 0; }
// CHECK: define dso_local zeroext i8 @check_uchar()
unsigned char check_uchar() { return 0; }
// CHECK: define dso_local zeroext i16 @check_ushort()
unsigned short check_ushort() { return 0; }
// CHECK: define dso_local i32 @check_uint()
unsigned int check_uint() { return 0; }
// CHECK: define dso_local i32 @check_ulong()
unsigned long check_ulong() { return 0; }
// CHECK: define dso_local i64 @check_ulonglong()
unsigned long long check_ulonglong() { return 0; }
// CHECK: define dso_local i32 @check_size_t()
size_t check_size_t() { return 0; }
// CHECK: define dso_local float @check_float()
float check_float() { return 0; }
// CHECK: define dso_local double @check_double()
double check_double() { return 0; }
// CHECK: define dso_local fp128 @check_longdouble()
long double check_longdouble() { return 0; }
|
the_stack_data/905926.c | n, i, j, k = 500;
f(x) { return x > n ? x - k : x; }
main() {
scanf("%d", &n);
if (n <= k) {
printf("%d", n);
for (i = n + 1; puts(""), --i;)
for (j = n; j--;) printf("%d ", i);
return 0;
}
puts("500");
for (i--; ++i < k; puts(""))
for (j = 0; j < k; j++) printf("%d ", f((i + j) % k + 1 + j % 2 * k));
} |
the_stack_data/97013835.c | /*Exercise 3 - Repetition
Write a C program to calculate the sum of the numbers from 1 to n.
Where n is a keyboard input.
e.g.
n -> 100
sum = 1+2+3+....+ 99+100 = 5050
n -> 1-
sum = 1+2+3+...+10 = 55 */
#include <stdio.h>
int main()
{
//creating variables
int i, n, sum = 0;
//input a number from keyboard
printf("Enter a number : ");
scanf("%d", &n);
//calculate the sum
for(i = 1; i <= n; i++)
{
sum += i;
}
//printing the output
printf("\nSum = %d\n", sum);
return 0;
}
|
the_stack_data/243893786.c | #include <stdio.h>
int main() {
int *pc;
int c;
c = 22;
printf("Address of c:%d\n", &c);
printf("Value of c:%d\n\n", c);
pc = &c;
printf("Address of pointer pc:%d\n", pc);
printf("Content of pointer pc:%d\n\n", *pc);
c = 11;
printf("Address of pointer pc:%d\n", pc);
printf("Content of pointer pc:%d\n\n", *pc);
*pc = 2;
printf("Address of c:%d\n", &c);
printf("Value of c:%d\n\n", c);
return 0;
} |
the_stack_data/864311.c | /*
调试启动带参程序
$ gdb test
(gdb)run 'para'
------------------
$ gdb test
(gdb) set args 'para'
(gdb) run
*/
#include<stdio.h>
int main(int argc,char *argv[]) {
if(1 >= argc) {
printf("usage:hello name\n");
return 0;
}
printf("Hello World %s!\n",argv[1]);
return 0 ;
}
|
the_stack_data/154829520.c | #include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#endif
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimagf(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static integer c_n1 = -1;
/* > \brief <b> ZHESV_AA computes the solution to system of linear equations A * X = B for HE matrices</b> */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download ZHESV_AA + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zhesv_a
a.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zhesv_a
a.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zhesv_a
a.f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE ZHESV_AA( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, */
/* LWORK, INFO ) */
/* CHARACTER UPLO */
/* INTEGER INFO, LDA, LDB, LWORK, N, NRHS */
/* INTEGER IPIV( * ) */
/* COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > ZHESV_AA computes the solution to a complex system of linear equations */
/* > A * X = B, */
/* > where A is an N-by-N Hermitian matrix and X and B are N-by-NRHS */
/* > matrices. */
/* > */
/* > Aasen's algorithm is used to factor A as */
/* > A = U**H * T * U, if UPLO = 'U', or */
/* > A = L * T * L**H, if UPLO = 'L', */
/* > where U (or L) is a product of permutation and unit upper (lower) */
/* > triangular matrices, and T is Hermitian and tridiagonal. The factored form */
/* > of A is then used to solve the system of equations A * X = B. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] UPLO */
/* > \verbatim */
/* > UPLO is CHARACTER*1 */
/* > = 'U': Upper triangle of A is stored; */
/* > = 'L': Lower triangle of A is stored. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of linear equations, i.e., the order of the */
/* > matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] NRHS */
/* > \verbatim */
/* > NRHS is INTEGER */
/* > The number of right hand sides, i.e., the number of columns */
/* > of the matrix B. NRHS >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is COMPLEX*16 array, dimension (LDA,N) */
/* > On entry, the Hermitian matrix A. If UPLO = 'U', the leading */
/* > N-by-N upper triangular part of A contains the upper */
/* > triangular part of the matrix A, and the strictly lower */
/* > triangular part of A is not referenced. If UPLO = 'L', the */
/* > leading N-by-N lower triangular part of A contains the lower */
/* > triangular part of the matrix A, and the strictly upper */
/* > triangular part of A is not referenced. */
/* > */
/* > On exit, if INFO = 0, the tridiagonal matrix T and the */
/* > multipliers used to obtain the factor U or L from the */
/* > factorization A = U**H*T*U or A = L*T*L**H as computed by */
/* > ZHETRF_AA. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] IPIV */
/* > \verbatim */
/* > IPIV is INTEGER array, dimension (N) */
/* > On exit, it contains the details of the interchanges, i.e., */
/* > the row and column k of A were interchanged with the */
/* > row and column IPIV(k). */
/* > \endverbatim */
/* > */
/* > \param[in,out] B */
/* > \verbatim */
/* > B is COMPLEX*16 array, dimension (LDB,NRHS) */
/* > On entry, the N-by-NRHS right hand side matrix B. */
/* > On exit, if INFO = 0, the N-by-NRHS solution matrix X. */
/* > \endverbatim */
/* > */
/* > \param[in] LDB */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array B. LDB >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is COMPLEX*16 array, dimension (MAX(1,LWORK)) */
/* > On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */
/* > \endverbatim */
/* > */
/* > \param[in] LWORK */
/* > \verbatim */
/* > LWORK is INTEGER */
/* > The length of WORK. LWORK >= MAX(1,2*N,3*N-2), and for best */
/* > performance LWORK >= f2cmax(1,N*NB), where NB is the optimal */
/* > blocksize for ZHETRF. */
/* > */
/* > If LWORK = -1, then a workspace query is assumed; the routine */
/* > only calculates the optimal size of the WORK array, returns */
/* > this value as the first entry of the WORK array, and no error */
/* > message related to LWORK is issued by XERBLA. */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value */
/* > > 0: if INFO = i, D(i,i) is exactly zero. The factorization */
/* > has been completed, but the block diagonal matrix D is */
/* > exactly singular, so the solution could not be computed. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date November 2017 */
/* > \ingroup complex16HEsolve */
/* ===================================================================== */
/* Subroutine */ int zhesv_aa_(char *uplo, integer *n, integer *nrhs,
doublecomplex *a, integer *lda, integer *ipiv, doublecomplex *b,
integer *ldb, doublecomplex *work, integer *lwork, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2;
/* Local variables */
integer lwkopt_hetrf__, lwkopt_hetrs__;
extern logical lsame_(char *, char *);
extern /* Subroutine */ int zhetrf_aa_(char *, integer *, doublecomplex *
, integer *, integer *, doublecomplex *, integer *, integer *), zhetrs_aa_(char *, integer *, integer *, doublecomplex *
, integer *, integer *, doublecomplex *, integer *, doublecomplex
*, integer *, integer *), xerbla_(char *, integer *, ftnlen);
integer lwkopt;
logical lquery;
/* -- LAPACK driver routine (version 3.8.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* November 2017 */
/* ===================================================================== */
/* Test the input parameters. */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
--ipiv;
b_dim1 = *ldb;
b_offset = 1 + b_dim1 * 1;
b -= b_offset;
--work;
/* Function Body */
*info = 0;
lquery = *lwork == -1;
if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*nrhs < 0) {
*info = -3;
} else if (*lda < f2cmax(1,*n)) {
*info = -5;
} else if (*ldb < f2cmax(1,*n)) {
*info = -8;
} else /* if(complicated condition) */ {
/* Computing MAX */
i__1 = *n << 1, i__2 = *n * 3 - 2;
if (*lwork < f2cmax(i__1,i__2) && ! lquery) {
*info = -10;
}
}
if (*info == 0) {
zhetrf_aa_(uplo, n, &a[a_offset], lda, &ipiv[1], &work[1], &c_n1,
info);
lwkopt_hetrf__ = (integer) work[1].r;
zhetrs_aa_(uplo, n, nrhs, &a[a_offset], lda, &ipiv[1], &b[b_offset],
ldb, &work[1], &c_n1, info);
lwkopt_hetrs__ = (integer) work[1].r;
lwkopt = f2cmax(lwkopt_hetrf__,lwkopt_hetrs__);
work[1].r = (doublereal) lwkopt, work[1].i = 0.;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("ZHESV_AA ", &i__1, (ftnlen)9);
return 0;
} else if (lquery) {
return 0;
}
/* Compute the factorization A = U**H*T*U or A = L*T*L**H. */
zhetrf_aa_(uplo, n, &a[a_offset], lda, &ipiv[1], &work[1], lwork, info);
if (*info == 0) {
/* Solve the system A*X = B, overwriting B with X. */
zhetrs_aa_(uplo, n, nrhs, &a[a_offset], lda, &ipiv[1], &b[b_offset],
ldb, &work[1], lwork, info);
}
work[1].r = (doublereal) lwkopt, work[1].i = 0.;
return 0;
/* End of ZHESV_AA */
} /* zhesv_aa__ */
|
the_stack_data/54823931.c | #include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// Make life a little easier.
typedef struct TreeNode node;
// Use some global state because I'm too bored to create
// a separate queue for this. Note, they could also
// be passed as pointers, alternatively.
static long *counts = NULL, *values = NULL, SIZE = 3;
void breadth(node *n, int level) {
if (!n)
return;
if (level == SIZE) {
SIZE++;
counts = realloc(counts, SIZE * sizeof(*counts));
values = realloc(values, SIZE * sizeof(*values));
counts[SIZE - 1] = 0;
values[SIZE - 1] = 0;
}
node *left = n->left, *right = n->right;
values[level] += n->val;
counts[level] += 1;
if (left) {
breadth(left, level + 1);
}
if (right) {
breadth(right, level + 1);
}
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
double *averageOfLevels(node *root, int *returnSize) {
counts = calloc(SIZE, sizeof(*counts));
values = calloc(SIZE, sizeof(*values));
breadth(root, 0);
double *result = malloc(SIZE * sizeof(*result));
int length = 0;
for (int i = 0; i < SIZE; i++) {
if (counts[i] != 0)
result[length++] = (double)values[i] / counts[i];
}
free(counts);
free(values);
*returnSize = length;
return result;
}
|
the_stack_data/159515680.c | /**
* Use the Crypto API user-interface provided by the kernel
*
* Documentation:
* * https://www.kernel.org/doc/htmldocs/crypto-API/index.html
* * https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/DocBook/crypto-API.tmpl
* * https://github.com/smuellerDD/libkcapi/
*/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE /* for accept4, snprintf */
#endif
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <linux/if_alg.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#ifndef AF_ALG
# define AF_ALG 38
#endif
#ifndef SOL_ALG
# define SOL_ALG 279
#endif
/* Copy definitions from include/uapi/linux/cryptouser.h (not provided by linux-api-headers:
* https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/uapi/linux/cryptouser.h
*/
enum {
CRYPTO_MSG_BASE = 0x10,
CRYPTO_MSG_NEWALG = 0x10,
CRYPTO_MSG_DELALG,
CRYPTO_MSG_UPDATEALG,
CRYPTO_MSG_GETALG,
CRYPTO_MSG_DELRNG,
__CRYPTO_MSG_MAX
};
#define CRYPTO_MAX_ALG_NAME 64
struct crypto_user_alg {
char cru_name[CRYPTO_MAX_ALG_NAME];
char cru_driver_name[CRYPTO_MAX_ALG_NAME];
char cru_module_name[CRYPTO_MAX_ALG_NAME];
__u32 cru_type;
__u32 cru_mask;
__u32 cru_refcnt;
__u32 cru_flags;
};
#define CR_RTA(x) ((struct rtattr*)(((char*)(x)) + NLMSG_ALIGN(sizeof(struct crypto_user_alg))))
enum crypto_attr_type_t {
CRYPTOCFGA_UNSPEC,
CRYPTOCFGA_PRIORITY_VAL,
CRYPTOCFGA_REPORT_LARVAL,
CRYPTOCFGA_REPORT_HASH,
CRYPTOCFGA_REPORT_BLKCIPHER,
CRYPTOCFGA_REPORT_AEAD,
CRYPTOCFGA_REPORT_COMPRESS,
CRYPTOCFGA_REPORT_RNG,
CRYPTOCFGA_REPORT_CIPHER,
CRYPTOCFGA_REPORT_AKCIPHER,
CRYPTOCFGA_REPORT_KPP,
__CRYPTOCFGA_MAX
#define CRYPTOCFGA_MAX (__CRYPTOCFGA_MAX - 1)
};
#define CRYPTO_MAX_NAME CRYPTO_MAX_ALG_NAME
struct crypto_report_larval {
char type[CRYPTO_MAX_NAME];
};
struct crypto_report_hash {
char type[CRYPTO_MAX_NAME];
unsigned int blocksize;
unsigned int digestsize;
};
struct crypto_report_cipher {
char type[CRYPTO_MAX_ALG_NAME];
unsigned int blocksize;
unsigned int min_keysize;
unsigned int max_keysize;
};
struct crypto_report_blkcipher {
char type[CRYPTO_MAX_NAME];
char geniv[CRYPTO_MAX_NAME];
unsigned int blocksize;
unsigned int min_keysize;
unsigned int max_keysize;
unsigned int ivsize;
};
struct crypto_report_aead {
char type[CRYPTO_MAX_NAME];
char geniv[CRYPTO_MAX_NAME];
unsigned int blocksize;
unsigned int maxauthsize;
unsigned int ivsize;
};
struct crypto_report_comp {
char type[CRYPTO_MAX_NAME];
};
struct crypto_report_rng {
char type[CRYPTO_MAX_NAME];
unsigned int seedsize;
};
struct crypto_report_akcipher {
char type[CRYPTO_MAX_NAME];
};
struct crypto_report_kpp {
char type[CRYPTO_MAX_NAME];
};
/* Casts of CMSG_DATA change the required alignment */
#pragma GCC diagnostic ignored "-Wcast-align"
/**
* Use sha256 through the crypto interface
*/
static bool test_sha256(void)
{
const char message[] = "Hello, world!";
const uint8_t expected_digest[32] = {
0x31, 0x5f, 0x5b, 0xdb, 0x76, 0xd0, 0x78, 0xc4,
0x3b, 0x8a, 0xc0, 0x06, 0x4e, 0x4a, 0x01, 0x64,
0x61, 0x2b, 0x1f, 0xce, 0x77, 0xc8, 0x69, 0x34,
0x5b, 0xfc, 0x94, 0xc7, 0x58, 0x94, 0xed, 0xd3
};
uint8_t digest[32];
struct sockaddr_alg sa;
int tfmfd, opfd;
ssize_t bytes;
size_t i;
/* Load algif_hash module */
memset(&sa, 0, sizeof(sa));
sa.salg_family = AF_ALG;
snprintf((char *)sa.salg_type, sizeof(sa.salg_type), "hash");
snprintf((char *)sa.salg_name, sizeof(sa.salg_name), "sha256");
tfmfd = socket(AF_ALG, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (tfmfd == -1) {
if (errno == EAFNOSUPPORT) {
/* AF_ALG is not supported by the kernel
* (missing CONFIG_CRYPTO_USER_API)
*/
printf("Family AF_ALG not supported by the kernel, continuing.\n");
return true;
} else if (errno == EPERM) {
/* Docker default seccomp policy forbids socket(AF_ALG) */
printf("Connection to algorithm socket is denied, continuing.\n");
return true;
}
perror("socket");
return false;
}
if (bind(tfmfd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
if (errno == ENOENT) {
/* Module auto-loading has been denied, e.g. by grsecurity
* GRKERNSEC_MODHARDEN option
*/
printf("Module algif_hash not found, continuing.\n");
close(tfmfd);
return true;
}
perror("bind");
close(tfmfd);
return false;
}
/* Get the operation socket */
opfd = accept4(tfmfd, NULL, 0, SOCK_CLOEXEC);
if (opfd == -1) {
perror("accept");
close(tfmfd);
return false;
}
/* Hash the message */
bytes = write(opfd, message, strlen(message));
if ((size_t)bytes != strlen(message)) {
if (bytes == -1) {
perror("write");
} else {
fprintf(
stderr, "Not enough bytes sent: %" PRIuPTR "/%" PRIuPTR "\n",
bytes, strlen(message));
}
close(opfd);
close(tfmfd);
return false;
}
bytes = read(opfd, digest, sizeof(digest));
if (bytes != sizeof(digest)) {
if (bytes == -1) {
perror("read");
} else {
fprintf(
stderr, "Not enough bytes read: %" PRIuPTR "/%" PRIuPTR "\n",
bytes, sizeof(digest));
}
close(opfd);
close(tfmfd);
return false;
}
close(opfd);
close(tfmfd);
/* Test the result */
printf("SHA256(%s) = ", message);
for (i = 0; i < sizeof(digest); i++) {
printf("%02x", digest[i]);
if (digest[i] != expected_digest[i]) {
printf("... invalid!\n");
return false;
}
}
printf("\n");
return true;
}
/* clang with Musl warns about a -Wsign-compare warning in CMSG_NXTHDR:
* error: comparison of integers of different signs: 'unsigned long' and 'long' [-Werror,-Wsign-compare]
* /usr/include/sys/socket.h:286:44: note: expanded from macro 'CMSG_NXTHDR'
* __CMSG_LEN(cmsg) + sizeof(struct cmsghdr) >= __MHDR_END(mhdr) - (unsigned char *)(cmsg) */
#if defined(__GNUC__)
# define HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH ((__GNUC__ << 16) + __GNUC_MINOR__ >= 0x40005)
#else
# define HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH 1
#endif
#if HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH
# pragma GCC diagnostic push
#endif
#pragma GCC diagnostic ignored "-Wsign-compare"
/**
* Use AES-XTS encryption through the crypto interface
*/
static bool test_aes_xts_enc(void)
{
char message[16] = "Hello, world!!!";
const uint8_t key[32] = {
'M', 'y', 'S', 'u', 'p', '3', 'r', 'S',
'3', 'c', 'r', '3', 't', 'K', '3', 'y',
'0', 'n', 'T', 'h', '1', 'r', 't', 'y',
'2', 'B', 'y', 't', '3', 's', '!', '!'
};
const uint8_t ivdata[16] = {
'W', 'h', 'a', 't', 'A', 'B', 'e', 'a',
'u', 't', 'i', 'f', 'u', 'l', 'I', 'V'
};
const uint8_t expected_encrypted[16] = {
0x69, 0x6d, 0x8f, 0xf2, 0xd7, 0xd2, 0xc8, 0x8b,
0x08, 0x10, 0xa1, 0x2b, 0x9e, 0xda, 0xb9, 0x38
};
uint8_t encrypted[16];
struct sockaddr_alg sa;
int tfmfd, opfd;
struct msghdr msg;
struct cmsghdr *cmsg;
struct af_alg_iv *ivmsg;
struct iovec iov;
uint8_t cbuf[CMSG_SPACE(4) + CMSG_SPACE(20)]; /* OP and IV headers */
ssize_t bytes;
size_t i;
/* Sanity check */
assert(sizeof(*ivmsg) + sizeof(ivdata) == 20);
/* Select encryption cipher */
memset(&sa, 0, sizeof(sa));
sa.salg_family = AF_ALG;
snprintf((char *)sa.salg_type, sizeof(sa.salg_type), "skcipher");
snprintf((char *)sa.salg_name, sizeof(sa.salg_name), "xts(aes)");
tfmfd = socket(AF_ALG, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (tfmfd == -1) {
if (errno == EAFNOSUPPORT) {
printf("Family AF_ALG not supported by the kernel, continuing.\n");
return true;
} else if (errno == EPERM) {
/* Docker default seccomp policy forbids socket(AF_ALG) */
printf("Connection to algorithm socket is denied, continuing.\n");
return true;
}
perror("socket");
return false;
}
if (bind(tfmfd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
perror("bind");
close(tfmfd);
return false;
}
if (setsockopt(tfmfd, SOL_ALG, ALG_SET_KEY, key, sizeof(key)) == -1) {
int err = errno;
perror("setsockopt(ALG_SET_KEY)");
close(tfmfd);
/* Qemu-user requires a build-time option to use AF_ALG:
* https://github.com/qemu/qemu/blob/0266c739abbed804deabb4ccde2aa449466ac3b4/configure#L452
*/
if (err == ENOPROTOOPT) {
return true;
}
return false;
}
/* Get the operation socket */
opfd = accept4(tfmfd, NULL, 0, SOCK_CLOEXEC);
if (opfd == -1) {
perror("accept");
close(tfmfd);
return false;
}
/* Build a message to send to the operation socket */
memset(&msg, 0, sizeof(msg));
memset(&cbuf, 0, sizeof(cbuf));
msg.msg_control = cbuf;
msg.msg_controllen = sizeof(cbuf);
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_ALG;
cmsg->cmsg_type = ALG_SET_OP;
cmsg->cmsg_len = CMSG_LEN(4);
*(uint32_t *)CMSG_DATA(cmsg) = ALG_OP_ENCRYPT;
cmsg = CMSG_NXTHDR(&msg, cmsg);
cmsg->cmsg_level = SOL_ALG;
cmsg->cmsg_type = ALG_SET_IV;
cmsg->cmsg_len = CMSG_LEN(20);
assert(sizeof(ivdata) == 16);
ivmsg = (struct af_alg_iv *)CMSG_DATA(cmsg);
ivmsg->ivlen = sizeof(ivdata);
memcpy(ivmsg->iv, ivdata, sizeof(ivdata));
memset(&iov, 0, sizeof(iov));
iov.iov_base = message;
iov.iov_len = sizeof(message);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
/* Encrypt data */
bytes = sendmsg(opfd, &msg, 0);
if ((size_t)bytes != sizeof(message)) {
if (bytes == -1) {
perror("sendmsg");
} else {
fprintf(
stderr, "Not enough bytes sent: %" PRIuPTR "/%" PRIuPTR "\n",
bytes, sizeof(message));
}
close(opfd);
close(tfmfd);
return false;
}
bytes = read(opfd, encrypted, sizeof(encrypted));
if (bytes != sizeof(encrypted)) {
if (bytes == -1) {
perror("read");
} else {
fprintf(
stderr, "Not enough bytes read: %" PRIuPTR "/%" PRIuPTR "\n",
bytes, sizeof(encrypted));
}
close(opfd);
close(tfmfd);
return false;
}
close(opfd);
close(tfmfd);
/* Test the result */
printf("AES-XTS-enc(%s\\0, key=%.32s, IV=%.16s) = ", message, key, ivdata);
for (i = 0; i < sizeof(encrypted); i++) {
printf("%02x", encrypted[i]);
if (encrypted[i] != expected_encrypted[i]) {
printf("... invalid!\n");
return false;
}
}
printf("\n");
return true;
}
/**
* Use AES-CBC decryption through the crypto interface
* Decrypt the result of:
* echo 'Hello, world!' |openssl enc -aes-256-cbc -nosalt -K 4d7953757033725333637233744b3379 -iv ''
*/
static bool test_aes_cbc_dec(void)
{
uint8_t encrypted[16] = {
0x43, 0x43, 0xec, 0x7d, 0x76, 0x99, 0x49, 0x61,
0xd9, 0x0e, 0x3f, 0x2e, 0xfe, 0xc9, 0x2c, 0xb3
};
const uint8_t key[32] = {
'M', 'y', 'S', 'u', 'p', '3', 'r', 'S',
'3', 'c', 'r', '3', 't', 'K', '3', 'y',
};
const uint8_t expected_decrypted[16] = {
'H', 'e', 'l', 'l', 'o', ',', ' ', 'w',
'o', 'r', 'l', 'd', '!', '\n', 2, 2
};
uint8_t decrypted[16];
struct sockaddr_alg sa;
int tfmfd, opfd;
struct msghdr msg;
struct cmsghdr *cmsg;
struct af_alg_iv *ivmsg;
struct iovec iov;
uint8_t cbuf[CMSG_SPACE(4) + CMSG_SPACE(20)]; /* OP and IV headers */
ssize_t bytes;
size_t i;
/* Select encryption cipher */
memset(&sa, 0, sizeof(sa));
sa.salg_family = AF_ALG;
snprintf((char *)sa.salg_type, sizeof(sa.salg_type), "skcipher");
snprintf((char *)sa.salg_name, sizeof(sa.salg_name), "cbc(aes)");
tfmfd = socket(AF_ALG, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (tfmfd == -1) {
if (errno == EAFNOSUPPORT) {
printf("Family AF_ALG not supported by the kernel, continuing.\n");
return true;
} else if (errno == EPERM) {
/* Docker default seccomp policy forbids socket(AF_ALG) */
printf("Connection to algorithm socket is denied, continuing.\n");
return true;
}
perror("socket");
return false;
}
if (bind(tfmfd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
perror("bind");
close(tfmfd);
return false;
}
if (setsockopt(tfmfd, SOL_ALG, ALG_SET_KEY, key, sizeof(key)) == -1) {
int err = errno;
perror("setsockopt(ALG_SET_KEY)");
close(tfmfd);
/* Qemu-user requires a build-time option to use AF_ALG */
if (err == ENOPROTOOPT) {
return true;
}
return false;
}
/* Get the operation socket */
opfd = accept4(tfmfd, NULL, 0, SOCK_CLOEXEC);
if (opfd == -1) {
perror("accept");
close(tfmfd);
return false;
}
/* Build a message to send to the operation socket */
memset(&msg, 0, sizeof(msg));
memset(&cbuf, 0, sizeof(cbuf));
msg.msg_control = cbuf;
msg.msg_controllen = sizeof(cbuf);
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_ALG;
cmsg->cmsg_type = ALG_SET_OP;
cmsg->cmsg_len = CMSG_LEN(4);
*(uint32_t *)CMSG_DATA(cmsg) = ALG_OP_DECRYPT;
cmsg = CMSG_NXTHDR(&msg, cmsg);
cmsg->cmsg_level = SOL_ALG;
cmsg->cmsg_type = ALG_SET_IV;
cmsg->cmsg_len = CMSG_LEN(20);
ivmsg = (struct af_alg_iv *)CMSG_DATA(cmsg);
ivmsg->ivlen = 16;
/* IV is left empty */
memset(&iov, 0, sizeof(iov));
iov.iov_base = encrypted;
iov.iov_len = sizeof(encrypted);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
/* Decrypt data */
bytes = sendmsg(opfd, &msg, 0);
if ((size_t)bytes != sizeof(encrypted)) {
if (bytes == -1) {
perror("sendmsg");
} else {
fprintf(
stderr, "Not enough bytes sent: %" PRIuPTR "/%" PRIuPTR "\n",
bytes, sizeof(encrypted));
}
close(opfd);
close(tfmfd);
return false;
}
bytes = read(opfd, decrypted, sizeof(decrypted));
if (bytes != sizeof(decrypted)) {
if (bytes == -1) {
perror("read");
} else {
fprintf(
stderr, "Not enough bytes read: %" PRIuPTR "/%" PRIuPTR "\n",
bytes, sizeof(decrypted));
}
close(opfd);
close(tfmfd);
return false;
}
close(opfd);
close(tfmfd);
/* Test the result */
printf("AES-CBC-dec(..., key=%.16s, IV=0) = ", key);
for (i = 0; i < sizeof(decrypted); i++) {
if (decrypted[i] >= 32 && decrypted[i] < 127) {
printf("%c", decrypted[i]);
} else {
printf("\\x%02x", decrypted[i]);
}
if (decrypted[i] != expected_decrypted[i]) {
printf("... invalid!\n");
return false;
}
}
printf("\n");
return true;
}
#if HAVE_PRAGMA_GCC_DIAGNOSTIC_PUSH
# pragma GCC diagnostic pop
#endif
/**
* Retrieve information about algorithms from the kernel using a netlink crypto socket.
* Such information may also be available through /proc/crypto.
*/
static bool show_cipher_info(const char *ciphername)
{
int nlsock;
struct sockaddr_nl sanl;
socklen_t addr_len;
struct {
struct nlmsghdr hdr;
struct crypto_user_alg cru;
} request;
struct iovec iov;
struct msghdr msg;
ssize_t bytes;
uint8_t buffer[4096];
struct nlmsghdr *reply_hdr;
struct nlmsgerr *reply_err;
struct crypto_user_alg *reply_cru;
struct rtattr *rta;
/* Open a netlink crypto socket */
nlsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_CRYPTO);
if (nlsock < 0) {
if (errno == EPROTONOSUPPORT) {
/* Module auto-loading has been denied, e.g. by grsecurity
* GRKERNSEC_MODHARDEN option
*/
printf("Module crypto_user not found, continuing.\n");
return true;
}
if (errno == EPFNOSUPPORT) {
/* Qemu-user does not support the protocol family */
printf("Protocol family not supported, continuing.\n");
return true;
}
perror("socket");
return false;
}
memset(&sanl, 0, sizeof(sanl));
sanl.nl_family = AF_NETLINK;
if (bind(nlsock, (struct sockaddr *)&sanl, sizeof(sanl)) < 0) {
perror("bind");
close(nlsock);
return false;
}
/* Sanity check */
addr_len = sizeof(sanl);
if (getsockname(nlsock, (struct sockaddr *)&sanl, &addr_len) < 0) {
perror("getsockname");
close(nlsock);
return false;
}
assert(addr_len == sizeof(sanl));
assert(sanl.nl_family == AF_NETLINK);
/* Build and send request */
memset(&request, 0, sizeof(request));
request.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(request.cru));
request.hdr.nlmsg_flags = NLM_F_REQUEST;
request.hdr.nlmsg_type = CRYPTO_MSG_GETALG;
request.hdr.nlmsg_seq = (uint32_t)time(NULL);
assert(strlen(ciphername) < sizeof(request.cru.cru_name));
strncpy(request.cru.cru_name, ciphername, sizeof(request.cru.cru_name));
memset(&iov, 0, sizeof(iov));
iov.iov_base = (void *)&request;
iov.iov_len = request.hdr.nlmsg_len;
memset(&sanl, 0, sizeof(sanl));
sanl.nl_family = AF_NETLINK;
memset(&msg, 0, sizeof(msg));
msg.msg_name = &sanl;
msg.msg_namelen = sizeof(sanl);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
bytes = sendmsg(nlsock, &msg, 0);
if ((size_t)bytes != request.hdr.nlmsg_len) {
if (bytes == -1) {
if (errno == ECONNREFUSED) {
/* This happens in containers */
printf("Connection to crypto Netlink socket refused, continuing.\n");
close(nlsock);
return true;
} else {
perror("sendmsg");
}
} else {
fprintf(
stderr, "Not enough bytes sent: %" PRIuPTR "/%u\n",
bytes, request.hdr.nlmsg_len);
}
close(nlsock);
return false;
}
/* FIXME: this generates the following warning on Linux 4.5:
* netlink: 208 bytes leftover after parsing attributes in process `crypto_socket.b'.
* (https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/lib/nlattr.c?h=v4.5#n205)
* ... and strace states:
* sendmsg(3, {
* msg_name={sa_family=AF_NETLINK, nl_pid=0, nl_groups=00000000},
* msg_namelen=12,
* msg_iov=[{
* iov_base={
* {len=224, type=0x13, flags=NLM_F_REQUEST, seq=1470763108, pid=0},
* "ccm(aes)\0\0\0\0\0\0\0[...]\0\0"},
* iov_len=224}],
* msg_iovlen=1,
* msg_controllen=0,
* msg_flags=0}, 0) = 224
*
* 224 - 208 = 16 bytes have been processed by nla_parse(). Why?
*/
/* Read reply */
memset(buffer, 0, sizeof(buffer));
bytes = read(nlsock, buffer, sizeof(buffer));
if (bytes == -1) {
perror("read");
close(nlsock);
return false;
} else if (bytes < (ssize_t)sizeof(struct nlmsghdr)) {
fprintf(
stderr, "Not enough bytes read: %" PRIuPTR "/%" PRIuPTR "\n",
bytes, sizeof(buffer));
close(nlsock);
return false;
} else if (bytes > (ssize_t)sizeof(buffer)) {
fprintf(
stderr, "Too many bytes read: %" PRIuPTR "/%" PRIuPTR "\n",
bytes, sizeof(buffer));
close(nlsock);
return false;
}
/* Close the socket now that it is no longer needed */
close(nlsock);
/* Decode the received data */
reply_hdr = (struct nlmsghdr *)buffer;
if (reply_hdr->nlmsg_type == NLMSG_ERROR) {
/* Try to decode the error code if there is enough space for a nlmsgerr structure */
if (reply_hdr->nlmsg_len != (size_t)bytes || (size_t)bytes < NLMSG_SPACE(sizeof(*reply_err))) {
fprintf(stderr, "Netlink returned an invalid NLMSG_ERROR reply.\n");
return false;
}
reply_err = NLMSG_DATA(reply_hdr);
/* Skip ciphers which are not available */
if (reply_err->error == -ENOENT) {
/* stdrng may not be available */
if (!strcmp(ciphername, "stdrng")) {
printf("No crypto-stdrng loaded (ansi_cprng or drbg), continuing.\n");
return true;
}
printf("Module crypto-%s not found, continuing.\n", ciphername);
return true;
}
fprintf(
stderr, "Netlink returned NLMSG_ERROR with code %d: %s.\n",
reply_err->error, strerror(-reply_err->error));
return false;
}
if (reply_hdr->nlmsg_type != CRYPTO_MSG_GETALG) {
fprintf(
stderr, "Unexpected Netlink message type: %d instead of %d\n",
reply_hdr->nlmsg_type, CRYPTO_MSG_GETALG);
return false;
}
if (reply_hdr->nlmsg_len != (size_t)bytes) {
fprintf(
stderr, "Unexpected Netlink message size: %u advertized but %" PRIuPTR " received\n",
reply_hdr->nlmsg_len, bytes);
return false;
}
reply_cru = NLMSG_DATA(reply_hdr);
bytes -= NLMSG_SPACE(sizeof(*reply_cru));
if (bytes < 0) {
fprintf(stderr, "Not enough bytes received from Netlink socket\n");
return false;
}
printf("Information about %s:\n", ciphername);
printf(" * Name: %.*s\n", (int)sizeof(reply_cru->cru_name), reply_cru->cru_name);
printf(" * Driver name: %.*s\n", (int)sizeof(reply_cru->cru_driver_name), reply_cru->cru_driver_name);
printf(" * Module name: %.*s\n", (int)sizeof(reply_cru->cru_module_name), reply_cru->cru_module_name);
if (reply_cru->cru_type)
printf(" * Type: %u\n", reply_cru->cru_type);
if (reply_cru->cru_mask)
printf(" * Mask: %#x\n", reply_cru->cru_mask);
printf(" * Reference count: %u\n", reply_cru->cru_refcnt);
/* Flags are CRYPTO_ALG_... constants from include/linux/crypto.h in Linux source tree */
printf(" * Flags: %#x\n", reply_cru->cru_flags);
for (rta = CR_RTA(reply_cru); RTA_OK(rta, bytes); rta = RTA_NEXT(rta, bytes)) {
switch (rta->rta_type) {
case CRYPTOCFGA_UNSPEC:
printf(" * Unspecified data of size %lu bytes\n", (unsigned long)RTA_PAYLOAD(rta));
break;
case CRYPTOCFGA_PRIORITY_VAL:
if (RTA_PAYLOAD(rta) != 4) {
fprintf(stderr, "Unexpected size for CRYPTOCFGA_PRIORITY_VAL payload\n");
return false;
}
printf(" * Priority %" PRIu32 "\n", *(uint32_t *)RTA_DATA(rta));
break;
case CRYPTOCFGA_REPORT_LARVAL:
printf(" * Larval (%lu bytes)\n", (unsigned long)RTA_PAYLOAD(rta));
break;
case CRYPTOCFGA_REPORT_HASH:
printf(" * Hash (%lu bytes)\n", (unsigned long)RTA_PAYLOAD(rta));
if (RTA_PAYLOAD(rta) == sizeof(struct crypto_report_hash)) {
struct crypto_report_hash *rhash = (struct crypto_report_hash *)RTA_DATA(rta);
printf(" - type: %.*s\n", (int)sizeof(rhash->type), rhash->type);
printf(" - block size: %u\n", rhash->blocksize);
printf(" - digest size: %u\n", rhash->digestsize);
}
break;
case CRYPTOCFGA_REPORT_BLKCIPHER:
printf(" * BlkCipher (%lu bytes)\n", (unsigned long)RTA_PAYLOAD(rta));
if (RTA_PAYLOAD(rta) == sizeof(struct crypto_report_blkcipher)) {
struct crypto_report_blkcipher *rblk = (struct crypto_report_blkcipher *)RTA_DATA(rta);
printf(" - type: %.*s\n", (int)sizeof(rblk->type), rblk->type);
printf(" - geniv: %.*s\n", (int)sizeof(rblk->geniv), rblk->geniv);
printf(" - block size: %u\n", rblk->blocksize);
printf(" - minimum key size: %u\n", rblk->min_keysize);
printf(" - maximum key size: %u\n", rblk->max_keysize);
printf(" - iv size: %u\n", rblk->ivsize);
}
break;
case CRYPTOCFGA_REPORT_AEAD:
printf(" * AEAD (%lu bytes)\n", (unsigned long)RTA_PAYLOAD(rta));
if (RTA_PAYLOAD(rta) == sizeof(struct crypto_report_aead)) {
struct crypto_report_aead *raead = (struct crypto_report_aead *)RTA_DATA(rta);
printf(" - type: %.*s\n", (int)sizeof(raead->type), raead->type);
printf(" - geniv: %.*s\n", (int)sizeof(raead->geniv), raead->geniv);
printf(" - block size: %u\n", raead->blocksize);
printf(" - maximum authentication size: %u\n", raead->maxauthsize);
printf(" - iv size: %u\n", raead->ivsize);
}
break;
case CRYPTOCFGA_REPORT_COMPRESS:
printf(" * Compress (%lu bytes)\n", (unsigned long)RTA_PAYLOAD(rta));
break;
case CRYPTOCFGA_REPORT_RNG:
printf(" * RNG (%lu bytes)\n", (unsigned long)RTA_PAYLOAD(rta));
if (RTA_PAYLOAD(rta) == sizeof(struct crypto_report_rng)) {
struct crypto_report_rng *rrng = (struct crypto_report_rng *)RTA_DATA(rta);
printf(" - type: %.*s\n", (int)sizeof(rrng->type), rrng->type);
printf(" - seed size: %u\n", rrng->seedsize);
}
break;
case CRYPTOCFGA_REPORT_CIPHER:
printf(" * Cipher (%lu bytes)\n", (unsigned long)RTA_PAYLOAD(rta));
break;
case CRYPTOCFGA_REPORT_AKCIPHER:
printf(" * AkCipher (%lu bytes)\n", (unsigned long)RTA_PAYLOAD(rta));
break;
case CRYPTOCFGA_REPORT_KPP:
printf(" * KPP (%lu bytes)\n", (unsigned long)RTA_PAYLOAD(rta));
break;
default:
printf(" * Unhandled type %u (%lu bytes)\n", rta->rta_type,
(unsigned long)RTA_PAYLOAD(rta));
}
}
if (bytes) {
fprintf(stderr, "Unprocessed %" PRIuPTR " bytes after attributes\n", bytes);
return false;
}
return true;
}
int main(void)
{
if (!test_sha256()) {
fprintf(stderr, "SHA256 test failed.\n");
return 1;
}
if (!test_aes_xts_enc()) {
fprintf(stderr, "AES-XTS encryption test failed.\n");
return 1;
}
if (!test_aes_cbc_dec()) {
fprintf(stderr, "AES-CBC decryption test failed.\n");
return 1;
}
if (!show_cipher_info("sha256")) {
fprintf(stderr, "Failed to show information about sha256.\n");
return 1;
}
if (!show_cipher_info("xts(aes)")) {
fprintf(stderr, "Failed to show information about xts(aes).\n");
return 1;
}
if (!show_cipher_info("ccm(aes)")) {
fprintf(stderr, "Failed to show information about ccm(aes).\n");
return 1;
}
if (!show_cipher_info("stdrng")) {
fprintf(stderr, "Failed to show information about stdrng.\n");
return 1;
}
return 0;
}
|
the_stack_data/920333.c | /*
* Welcome to your second program in C.
*
* In this program you will modify the code from your first program
* to accept a parameter or argument as input from the Shell.
*
*/
/*
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
*/
#include <unistd.h>
int main ( int argc, const char* argv[] ) {
// argc is the number of arguments passed into the program
// argv is the array (think a list) of arguments
// We access the items in the array by putting a number between
// the square brackets. In C, we call this number an index.
// This is very important because indexes will always start
// with 0. You can think of this in terms of number types.
// In math, the natural numbers start with 1 and increase.
// Indexes start at 0 and will increase until the number of
// items in the array minus 1.
int exit_value;
// ensure the correct number of parameters are used.
if ( argc == 2 )
{
int i = 0; // declare a variable to count the length
// of the text passed in as an argument
// In C, all text ends with the character '\0'.
// To get the length of the text, or string, we
// start at the first index
while( argv[1][i] != '\0' ) {
i = i + 1;
}
write( 1, argv[1], i );
// What do you think the zeroth item or element
// in argv is?
// i = 0; // reset i to be 0
// while(argv[0][i] != '\0') {
// i = i+1;
// }
// write(1, argv[0], i);
exit_value = 0;
} else {
// if the incorrect number of parameters are used
// then report that there was an error
exit_value = 1;
}
return exit_value;
}
|
the_stack_data/97011566.c | // REQUIRES: x86-registered-target
// RUN: %clang -target x86_64 -g -S -emit-llvm -o - %s | FileCheck %s
#define __tag1 __attribute__((btf_decl_tag("tag1")))
#define __tag2 __attribute__((btf_decl_tag("tag2")))
struct __tag1 __tag2 t1;
struct t1 {
int a;
};
int foo(struct t1 *arg) {
return arg->a;
}
// CHECK: distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t1", file: ![[#]], line: [[#]], size: 32, elements: ![[#]], annotations: ![[ANNOT:[0-9]+]])
// CHECK: ![[ANNOT]] = !{![[TAG1:[0-9]+]], ![[TAG2:[0-9]+]]}
// CHECK: ![[TAG1]] = !{!"btf_decl_tag", !"tag1"}
// CHECK: ![[TAG2]] = !{!"btf_decl_tag", !"tag2"}
struct __tag1 t2;
struct __tag2 t2 {
int a;
};
int foo2(struct t2 *arg) {
return arg->a;
}
// CHECK: distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t2", file: ![[#]], line: [[#]], size: 32, elements: ![[#]], annotations: ![[ANNOT]])
struct __tag1 t3;
struct t3 {
int a;
} __tag2;
int foo3(struct t3 *arg) {
return arg->a;
}
// CHECK: distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t3", file: ![[#]], line: [[#]], size: 32, elements: ![[#]], annotations: ![[ANNOT]])
struct t4;
struct t4 {
int a;
} __tag1 __tag2;
int foo4(struct t4 *arg) {
return arg->a;
}
// CHECK: distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t4", file: ![[#]], line: [[#]], size: 32, elements: ![[#]], annotations: ![[ANNOT]])
|
the_stack_data/159514508.c | /*** includes ***/
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
/*** defines ***/
#define KILO_VERSION "0.0.1"
#define CTRL_KEY(k) ((k)&0x1f)
/*** data ***/
struct editorConfig {
int cx, cy;
int screenrows;
int screencols;
struct termios orig_termios;
};
struct editorConfig E;
/*** terminal ***/
void die(const char *s) {
perror(s);
exit(1);
}
void disableRawMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1)
die("tcsetattr");
}
void enableRawMode() {
if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1)
die("tcgetattr");
atexit(disableRawMode);
struct termios raw = E.orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
die("tcsetattr");
}
char editorReadKey() {
int nread;
char c;
while ((nread = read(STDIN_FILENO, &c, 1)) != 1) {
if (nread == -1 && errno != EAGAIN)
die("read");
}
return c;
}
int getCursorPosition(int *rows, int *cols) {
char buf[32];
unsigned int i = 0;
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4)
return -1;
while (i < sizeof(buf) - 1) {
if (read(STDIN_FILENO, &buf[i], 1) != 1)
break;
if (buf[i] == 'R')
break;
i++;
}
buf[i] = '\0';
if (buf[0] != '\x1b' || buf[1] != '[')
return -1;
if (sscanf(&buf[2], "%d;%d", rows, cols) != 2)
return -1;
return 0;
}
int getWindowSize(int *rows, int *cols) {
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
if (write(STDOUT_FILENO, "\x1b[999/c\x1b[999B", 12) != 12)
return -1;
return getCursorPosition(rows, cols);
} else {
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
}
/*** append buffer ***/
struct abuf {
char *b;
int len;
};
#define ABUF_INIT \
{ NULL, 0 }
void abAppend(struct abuf *ab, const char *s, int len) {
char *new = realloc(ab->b, ab->len + len);
if (new == NULL)
return;
memcpy(&new[ab->len], s, len);
ab->b = new;
ab->len += len;
}
void abFree(struct abuf *ab) { free(ab->b); }
/*** output ***/
void editorDrawRows(struct abuf *ab) {
int y;
for (y = 0; y < E.screenrows; y++) {
if (y == E.screenrows / 3) {
char welcome[80];
int welcomelen = snprintf(welcome, sizeof(welcome),
"Kilo Editor -- Version %s", KILO_VERSION);
if (welcomelen > E.screencols)
welcomelen = E.screencols;
int padding = (E.screencols - welcomelen) / 2;
if (padding) {
abAppend(ab, "~", 1);
padding--;
}
while (padding--)
abAppend(ab, " ", 1);
abAppend(ab, welcome, welcomelen);
} else {
abAppend(ab, "~", 1);
}
abAppend(ab, "\x1b[K", 3);
if (y < E.screenrows - 1) {
abAppend(ab, "\r\n", 2);
}
}
}
void editorRefreshScreen() {
struct abuf ab = ABUF_INIT;
abAppend(&ab, "\x1b[?25l", 6);
abAppend(&ab, "\x1b[H", 3);
editorDrawRows(&ab);
char buf[32];
snprintf(buf, sizeof(buf), "\x1b[%d;%dH", E.cy + 1, E.cx + 1);
abAppend(&ab, buf, strlen(buf));
abAppend(&ab, "\x1b[?25h", 6);
write(STDOUT_FILENO, ab.b, ab.len);
abFree(&ab);
}
/*** input ***/
void editorMoveCursor(char key) {
/* Make vim movement */
switch (key) {
case 'h':
E.cx--;
break;
case 'l':
E.cx++;
break;
case 'j':
E.cy++;
break;
case 'k':
E.cy--;
break;
}
}
void editorProcessKeypress() {
char c = editorReadKey();
switch (c) {
case CTRL_KEY('q'):
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
exit(0);
break;
case 'h':
case 'l':
case 'j':
case 'k':
editorMoveCursor(c);
break;
}
}
/*** init ***/
void initEditor() {
E.cx = 0;
E.cy = 0;
if (getWindowSize(&E.screenrows, &E.screencols) == -1)
die("getWindowSize");
}
int main() {
enableRawMode();
initEditor();
while (1) {
editorRefreshScreen();
editorProcessKeypress();
}
return 0;
}
|
the_stack_data/231393780.c | //PROJECT2
#define SCHRAND_MAX ((1U << 31) - 1)
#define SCHRAND_MULT 214013
#define SCHRAND_CONST 2531011
//Pseudo-random number generator made from a linear congruential generator.
//Based on code and constants found at:
//https://rosettacode.org/wiki/Linear_congruential_generator
int rseed = 707606505;
int rand(void)
{
return rseed = (rseed * SCHRAND_MULT + SCHRAND_CONST) % SCHRAND_MAX;
} |
the_stack_data/104590.c | /* builtin_return_address(n) with n>0 has always been troublesome ...
especially when the S/390 packed stack layout comes into play. */
/* { dg-do run } */
/* { dg-options "-O3 -fno-optimize-sibling-calls -mbackchain -mpacked-stack -msoft-float" } */
void *addr1;
extern void abort (void);
void * __attribute__((noinline))
foo1 ()
{
addr1 = __builtin_return_address (2);
}
void * __attribute__((noinline))
foo2 ()
{
foo1 ();
}
void * __attribute__((noinline))
foo3 ()
{
foo2 ();
}
void __attribute__((noinline))
bar ()
{
void *addr2;
foo3 ();
asm volatile ("basr %0,0\n\t" : "=d" (addr2));
/* basr is two bytes in length. */
if (addr2 - addr1 != 2)
abort ();
}
int
main ()
{
bar();
return 0;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.