file
stringlengths 18
26
| data
stringlengths 2
1.05M
|
---|---|
the_stack_data/150645.c | #include <stdio.h>
void print(int x) {
printf("%d\n", x);
} |
the_stack_data/902860.c | /***********************************************************************/
/* */
/* Objective Caml */
/* */
/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
/* */
/* Copyright 1996 Institut National de Recherche en Informatique et */
/* en Automatique. All rights reserved. This file is distributed */
/* under the terms of the GNU Library General Public License, with */
/* the special exception on linking described in file ../../LICENSE. */
/* */
/***********************************************************************/
/* $Id: longlong.c,v 1.4 2002/05/25 08:33:26 xleroy Exp $ */
#include <stdio.h>
#include <string.h>
/* Check for the availability of "long long" type as per ISO C9X */
/* Meaning of return code:
0 long long OK, printf with %ll
1 long long OK, printf with %q
2 long long OK, no printf
3 long long not suitable */
int main(int argc, char **argv)
{
long long l;
unsigned long long u;
char buffer[64];
if (sizeof(long long) != 8) return 3;
l = 123456789123456789LL;
buffer[0] = '\0';
sprintf(buffer, "%lld", l);
if (strcmp(buffer, "123456789123456789") == 0) return 0;
/* the MacOS X library uses qd to format long longs */
buffer[0] = '\0';
sprintf (buffer, "%qd", l);
if (strcmp (buffer, "123456789123456789") == 0) return 1;
return 2;
}
|
the_stack_data/1026669.c | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
void heapify(int a[],int n,int i)
{ int s,left,right,t;
s=i;
left=2*i+1;
right=2*i+2;
if(left<n && a[left]<a[s])
{ s=left;
}
if(right<n && a[right]<a[s])
{ s=right;
}
if(s!=i)
{ t=a[i];
a[i]=a[s];
a[s]=t;
heapify(a,n,s);
}
}
void build_min_heap(int a[],int n)
{ int s=(n/2)-1;
for(int i=s;i>=0;--i)
{ heapify(a,n,i);
}
}
int main()
{ int n,i;
clock_t t;
t=clock();
printf("enter the size of array\n");
scanf("%d",&n);
int a[n];
printf("enter the elements of array\n");
for(i=0;i<n;++i)
{ scanf("%d",&a[i]);
}
build_min_heap(a,n);
printf("Min Heap is as Follows....\n");
for(i=0;i<n;++i)
{ printf("%d\t",a[i]);
}
int p;
printf("\nenter the position you want to delete\n");
scanf("%d",&p);
if(p<=n)
{ for(i=p-1;i<n;++i)
{ a[i]=a[i+1];
}
n=n-1;
}
printf("\nDELETED\n");
for(i=0;i<n;++i)
{ printf("%d\t",a[i]);
}
t=clock()-t;
double time_taken=((double)t)/CLOCKS_PER_SEC;
printf("\nTime Taken: %f\n",time_taken);
return 0;
}
|
the_stack_data/76701540.c | /* C demo code */
#include <stdio.h>
int main(int argc, char **argv) {
printf("Hello, world!\n");
return 0;
} |
the_stack_data/54826524.c | #include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
/*
* $ gcc -o redirect_stdinout redirect_stdinput.c
* $ ./redirect_stdinout infile outfile
*/
int main(int argc, char **argv) {
int pid, status;
int infd, outfd;
if (argc != 3) {
fprintf(stderr, "usage: %s input_file output_file\n", argv[0]);
exit(1);
}
if ((infd = open(argv[1], O_RDONLY, 0644)) < 0) {
perror(argv[1]);
exit(1);
}
if ((outfd = open(argv[2], O_CREAT|O_TRUNC|O_WRONLY, 0644)) < 0) {
perror(argv[2]);
exit(1);
}
printf("After this message, stdout/stdin redirected to/from \"%s\" \"%s\".\n", argv[0], argv[1]);
/*
* stdin is fd 0, stdout is fd 1
* dup2 connects our file to fd 1 (stdout)
*/
dup2(infd, 0);
dup2(outfd, 1);
char line[100];
fgets(line, 100, stdin);
printf("outfile: %s: data from infile: %s\n", argv[1], line);
exit(0);
}
|
the_stack_data/187643417.c | #include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Returns 'true' if the character is a DELIMITER.
bool isDelimiter(char ch)
{
if (ch == ' ' || ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == ',' || ch == ';' || ch == '>' ||
ch == '<' || ch == '=' || ch == '(' || ch == ')' ||
ch == '[' || ch == ']' || ch == '{' || ch == '}')
return (true);
return (false);
}
// Returns 'true' if the character is an OPERATOR.
bool isOperator(char ch)
{
if (ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == '>' || ch == '<' ||
ch == '=')
return (true);
return (false);
}
// Returns 'true' if the string is a VALID IDENTIFIER.
bool validIdentifier(char* str)
{
if (str[0] == '0' || str[0] == '1' || str[0] == '2' ||
str[0] == '3' || str[0] == '4' || str[0] == '5' ||
str[0] == '6' || str[0] == '7' || str[0] == '8' ||
str[0] == '9' || isDelimiter(str[0]) == true)
return (false);
return (true);
}
// Returns 'true' if the string is a KEYWORD.
bool isKeyword(char* str)
{
if (!strcmp(str, "if") || !strcmp(str, "else") ||
!strcmp(str, "while") || !strcmp(str, "do") ||
!strcmp(str, "break") ||
!strcmp(str, "continue") || !strcmp(str, "int")
|| !strcmp(str, "double") || !strcmp(str, "float")
|| !strcmp(str, "return") || !strcmp(str, "char")
|| !strcmp(str, "case") || !strcmp(str, "char")
|| !strcmp(str, "sizeof") || !strcmp(str, "long")
|| !strcmp(str, "short") || !strcmp(str, "typedef")
|| !strcmp(str, "switch") || !strcmp(str, "unsigned")
|| !strcmp(str, "void") || !strcmp(str, "static")
|| !strcmp(str, "struct") || !strcmp(str, "goto"))
return (true);
return (false);
}
bool isHeader(char* str)
{
if (!strcmp(str, "stdio.h")||!strcmp(str, "stdlib.h")||!strcmp(str, "string.h"))
return (true);
return (false);
}
bool isDirective(char* str)
{
if (!strcmp(str, "#include")||!strcmp(str, "#define"))
return (true);
return (false);
}
bool isEOL(char* str)
{
if (!strcmp(str, "\n")||!strcmp(str, "\0"))
return (true);
return (false);
}
// Returns 'true' if the string is an INTEGER.
bool isInteger(char* str)
{
int i, len = strlen(str);
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' || (str[i] == '-' && i > 0))
return (false);
}
return (true);
}
// Returns 'true' if the string is a REAL NUMBER.
bool isRealNumber(char* str)
{
int i, len = strlen(str);
bool hasDecimal = false;
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' && str[i] != '.' ||
(str[i] == '-' && i > 0))
return (false);
if (str[i] == '.')
hasDecimal = true;
}
return (hasDecimal);
}
// Extracts the SUBSTRING.
char* subString(char* str, int left, int right)
{
int i;
char* subStr = (char*)malloc(
sizeof(char) * (right - left + 2));
for (i = left; i <= right; i++)
subStr[i - left] = str[i];
subStr[right - left + 1] = '\0';
return (subStr);
}
// Parsing the input STRING.
void parse(char* str)
{
int left = 0, right = 0;
int len = strlen(str);
while (right <= len && left <= right) {
if (isDelimiter(str[right]) == false)
right++;
if (isDelimiter(str[right]) == true && left == right) {
if (isOperator(str[right]) == true)
printf("%c IS AN OPERATOR\n", str[right]);
right++;
left = right;
} else if (isDelimiter(str[right]) == true && left != right
|| (right == len && left != right)) {
char* subStr = subString(str, left, right - 1);
if (isKeyword(subStr) == true)
printf("%s IS A KEYWORD\n", subStr);
else if (isInteger(subStr) == true)
printf("%s IS AN INTEGER\n", subStr);
else if (isRealNumber(subStr) == true)
printf("%s IS A REAL NUMBER\n", subStr);
else if (isDirective(subStr) == true
&& isDelimiter(str[right - 1]) == false)
printf("%s IS A Preprocessor Directive\n", subStr);
else if (isHeader(subStr) == true
&& isDelimiter(str[right - 1]) == false)
printf("%s IS A HEADER FILE\n", subStr);
else if (isEOL(subStr) == true
&& isDelimiter(str[right - 1]) == false)
printf("\n");
else if (validIdentifier(subStr) == true
&& isDelimiter(str[right - 1]) == false)
printf("%s IS A VALID IDENTIFIER\n", subStr);
else if (validIdentifier(subStr) == false
&& isDelimiter(str[right - 1]) == false)
printf("%s IS NOT A VALID IDENTIFIER\n", subStr);
left = right;
}
}
return;
}
// DRIVER FUNCTION
int main()
{
char *str;
FILE *fptr;
size_t len = 0;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
while ((getline(&str, &len, fptr)) != -1) {
parse(str);
}
return (0);
}
|
the_stack_data/46130.c | /* platform-independent thread api, for composition with
platform-dependent code */
#include <stdint.h>
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#if EXPORT_INTERFACE
#include <stdint.h> /* api args uint32_t etc. */
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
/**
* Value used for the owner field of an oc_mutex that doesn't have an owner.
*/
#define OC_INVALID_THREAD_ID 0
typedef enum
{
OC_THREAD_SUCCESS = 0,
OC_THREAD_ALLOCATION_FAILURE = 1,
OC_THREAD_CREATE_FAILURE=2,
OC_THREAD_INVALID=3,
OC_THREAD_WAIT_FAILURE=4,
OC_THREAD_INVALID_PARAMETER=5
} OCThreadResult_t;
typedef struct oc_event_t *oc_event;
typedef struct oc_mutex_internal *oc_mutex;
typedef struct oc_cond_internal *oc_cond;
typedef struct oc_thread_internal *oc_thread;
#endif
|
the_stack_data/61676.c | #include <stdio.h>
int dg(int x)
{
int dg=0;
while(1)
{
if(x==0)
{
return dg;
}
dg++;
x=x/10;
}
return dg;
}
int main()
{
int n, i, j, k, x;
while(1)
{
scanf(" %d", &n);
int ara[n][n], t=0;
if(n==0)
{
break;
}
else{
for(i=0; i<2; i++)
{
x=1;
for(j=0; j<n; j++)
{
if(i==0)
{
ara[0][j] = x;
}
else
{
ara[j][0] = x;
}
x*=2;
}
}
x=x/2;
for(i=1; i<n; i++)
{
x*=2;
}
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
if(i==0 || j==0)
{
if(j==0)
{
for(k=dg(ara[i][j]); k<dg(x); k++)
{
printf(" ");
}
printf("%d", ara[i][j]);
}
else
{
for(k=dg(ara[i][j]); k<dg(x); k++)
{
printf(" ");
}
printf(" %d", ara[i][j]);
}
continue;
}
else
{
ara[i][j] = ara[i][j-1]*2;
if(j==0)
{
for(k=dg(ara[i][j]); k<dg(x); k++)
{
printf(" ");
}
printf("%d", ara[i][j]);
}
else
{
for(k=dg(ara[i][j]); k<dg(x); k++)
{
printf(" ");
}
printf(" %d", ara[i][j]);
}
}
}
printf("\n");
}
printf("\n");
}
}
return 0;
}
|
the_stack_data/640002.c | #ifdef CMP_VIA_MQTT_DIRECT
#include "iot_import.h"
#include "utils_list.h"
#include "lite-utils.h"
#include "lite-system.h"
#include "iot_export.h"
#include "iotx_cmp_common.h"
#include "iot_export_mqtt.h"
#include "mqtt_instance.h"
#include "iotx_cmp_mqtt_direct.h"
#ifdef ESP8266
#define MQTT_MSGLEN (1024)
#else
#define MQTT_MSGLEN (1024 * 40)
#endif
typedef struct iotx_cmp_mqtt_direct_topic_st {
void *next;
char *topic;
int packet_id;
} iotx_cmp_mqtt_direct_topic_t, *iotx_cmp_mqtt_direct_topic_pt;
typedef struct iotx_cmp_mqtt_direct_st {
char *msg_buf;
char *msg_readbuf;
int list_length;
iotx_cmp_mqtt_direct_topic_pt topic_list;
} iotx_cmp_mqtt_direct_t, *iotx_cmp_mqtt_direct_pt;
static iotx_cmp_mqtt_direct_pt mqtt_pt = NULL;
static int _add_topic(const char* topic, int packet_id)
{
iotx_cmp_mqtt_direct_topic_pt new_pt = NULL;
new_pt = CMP_malloc(sizeof(iotx_cmp_mqtt_direct_topic_t));
if (NULL == new_pt) {
CMP_ERR(cmp_log_error_memory);
return FAIL_RETURN;
}
memset(new_pt, 0x0, sizeof(iotx_cmp_mqtt_direct_topic_t));
new_pt->topic = CMP_malloc(strlen(topic) + 1);
if (NULL == new_pt->topic) {
CMP_ERR(cmp_log_error_memory);
LITE_free(new_pt);
return FAIL_RETURN;
}
memset(new_pt->topic, 0x0, strlen(topic) + 1);
strncpy(new_pt->topic, topic, strlen(topic));
new_pt->packet_id = packet_id;
new_pt->next = mqtt_pt->topic_list;
mqtt_pt->topic_list = new_pt;
mqtt_pt->list_length++;
return SUCCESS_RETURN;
}
static int _delete_topic(unsigned int packet_id)
{
iotx_cmp_mqtt_direct_topic_pt current = NULL;
iotx_cmp_mqtt_direct_topic_pt pre = NULL;
if (NULL == mqtt_pt->topic_list) {
CMP_WARNING(cmp_log_warning_no_list);
return FAIL_RETURN;
}
current = pre = mqtt_pt->topic_list;
if (current->packet_id == packet_id){
mqtt_pt->topic_list = mqtt_pt->topic_list->next;
LITE_free(current->topic);
LITE_free(current);
mqtt_pt->list_length--;
if (mqtt_pt->list_length == 0)
mqtt_pt->topic_list = NULL;
return SUCCESS_RETURN;
}
current = current->next;
while (current) {
if (current->packet_id == packet_id) {
pre->next = current->next;
LITE_free(current->topic);
LITE_free(current);
mqtt_pt->list_length--;
if (mqtt_pt->list_length == 0)
mqtt_pt = NULL;
return SUCCESS_RETURN;
}
pre = current;
current = current->next;
}
return FAIL_RETURN;
}
static char* _find_topic(unsigned int packet_id)
{
iotx_cmp_mqtt_direct_topic_pt current = NULL;
iotx_cmp_mqtt_direct_topic_pt pre = NULL;
if (NULL == mqtt_pt || NULL == mqtt_pt->topic_list) {
CMP_WARNING(cmp_log_warning_no_list);
return NULL;
}
current = pre = mqtt_pt->topic_list;
while (current) {
if (current->packet_id == packet_id) {
return current->topic;
}
pre = current;
current = current->next;
}
return NULL;
}
static int _find_topic_ex(char* URI)
{
iotx_cmp_mqtt_direct_topic_pt current = NULL;
iotx_cmp_mqtt_direct_topic_pt pre = NULL;
if (NULL == mqtt_pt->topic_list) {
CMP_WARNING(cmp_log_warning_no_list);
return FAIL_RETURN;
}
current = pre = mqtt_pt->topic_list;
while (current) {
if (0 == strncmp(current->topic, URI, strlen(URI))) {
return current->packet_id;
}
pre = current;
current = current->next;
}
return FAIL_RETURN;
}
static void _delete_all()
{
iotx_cmp_mqtt_direct_topic_pt current = NULL;
iotx_cmp_mqtt_direct_topic_pt next = NULL;
if (NULL == mqtt_pt->topic_list) {
CMP_WARNING(cmp_log_warning_no_list);
return;
}
current = next = mqtt_pt->topic_list;
while (current) {
next = current->next;
LITE_free(current->topic);
LITE_free(current);
current = next;
}
mqtt_pt->list_length = 0;
}
static void iotx_cmp_mqtt_direct_event_callback(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
{
uintptr_t packet_id = (uintptr_t)msg->msg;
iotx_cmp_conntext_pt cmp_pt = (iotx_cmp_conntext_pt)pcontext;
if (NULL == cmp_pt) {
CMP_ERR(cmp_log_error_parameter);
return;
}
CMP_INFO(cmp_log_info_event_type, msg->event_type);
switch (msg->event_type) {
case IOTX_MQTT_EVENT_UNDEF:
CMP_WARNING(cmp_log_warning_not_arrived);
break;
case IOTX_MQTT_EVENT_DISCONNECT: {
#ifdef CMP_SUPPORT_MULTI_THREAD
{
/* send message to itself thread */
int rc = 0;
iotx_cmp_process_list_node_pt node = iotx_cmp_get_list_node(IOTX_CMP_PROCESS_TYPE_CLOUD);
if (NULL == node) return;
node->type = IOTX_CMP_PROCESS_CLOUD_DISCONNECT;
node->msg = NULL;
rc = iotx_cmp_process_list_push(cmp_pt, IOTX_CMP_PROCESS_TYPE_CLOUD, node);
if (FAIL_RETURN == rc) iotx_cmp_free_list_node(node);
}
#else
iotx_cmp_mqtt_direct_disconnect_handler(cmp_pt);
#endif
}
break;
case IOTX_MQTT_EVENT_RECONNECT: {
#ifdef CMP_SUPPORT_MULTI_THREAD
{
/* send message to itself thread */
int rc = 0;
iotx_cmp_process_list_node_pt node = iotx_cmp_get_list_node(IOTX_CMP_PROCESS_TYPE_CLOUD);
if (NULL == node) return;
node->type = IOTX_CMP_PROCESS_CLOUD_RECONNECT;
node->msg = NULL;
rc = iotx_cmp_process_list_push(cmp_pt, IOTX_CMP_PROCESS_TYPE_CLOUD, node);
if (FAIL_RETURN == rc) iotx_cmp_free_list_node(node);
}
#else
iotx_cmp_mqtt_direct_reconnect_handler(cmp_pt);
#endif
}
break;
case IOTX_MQTT_EVENT_SUBCRIBE_SUCCESS: {
#ifdef CMP_SUPPORT_MULTI_THREAD
{
/* send message to itself thread */
int rc = 0;
iotx_cmp_process_list_node_pt node = NULL;
iotx_cmp_process_register_result_pt result_msg = NULL;
node = iotx_cmp_get_list_node(IOTX_CMP_PROCESS_TYPE_CLOUD);
if (NULL == node) return;
node->type = IOTX_CMP_PROCESS_CLOUD_REGISTER_RESULT;
node->msg = CMP_malloc(sizeof(iotx_cmp_process_register_result_t));
if (NULL == node->msg) {
CMP_ERR(cmp_log_error_memory);
iotx_cmp_free_list_node(node);
return;
}
result_msg = node->msg;
result_msg->URI = _find_topic(packet_id);
result_msg->result = 0;
result_msg->is_register = 1;
rc = iotx_cmp_process_list_push(cmp_pt, IOTX_CMP_PROCESS_TYPE_CLOUD, node);
if (FAIL_RETURN == rc) {
LITE_free(node->msg);
iotx_cmp_free_list_node(node);
}
}
#else
iotx_cmp_mqtt_direct_register_handler(cmp_pt, _find_topic(packet_id), 0, 1);
_delete_topic(packet_id);
#endif
}
break;
case IOTX_MQTT_EVENT_SUBCRIBE_TIMEOUT:
case IOTX_MQTT_EVENT_SUBCRIBE_NACK:{
#ifdef CMP_SUPPORT_MULTI_THREAD
{
/* send message to itself thread */
int rc = 0;
iotx_cmp_process_list_node_pt node = NULL;
iotx_cmp_process_register_result_pt result_msg = NULL;
node = iotx_cmp_get_list_node(IOTX_CMP_PROCESS_TYPE_CLOUD);
if (NULL == node) return;
node->type = IOTX_CMP_PROCESS_CLOUD_REGISTER_RESULT;
node->msg = CMP_malloc(sizeof(iotx_cmp_process_register_result_t));
if (NULL == node->msg) {
CMP_ERR(cmp_log_error_memory);
iotx_cmp_free_list_node(node);
return;
}
result_msg = node->msg;
result_msg->URI = _find_topic(packet_id);
result_msg->result = -1;
result_msg->is_register = 1;
rc = iotx_cmp_process_list_push(cmp_pt, IOTX_CMP_PROCESS_TYPE_CLOUD, node);
if (FAIL_RETURN == rc) {
LITE_free(node->msg);
iotx_cmp_free_list_node(node);
}
}
#else
iotx_cmp_mqtt_direct_register_handler(cmp_pt, _find_topic(packet_id), -1, 1);
_delete_topic(packet_id);
#endif
}
break;
case IOTX_MQTT_EVENT_UNSUBCRIBE_SUCCESS:{
#ifdef CMP_SUPPORT_MULTI_THREAD
{
/* send message to itself thread */
int rc = 0;
iotx_cmp_process_list_node_pt node = NULL;
iotx_cmp_process_register_result_pt result_msg = NULL;
node = iotx_cmp_get_list_node(IOTX_CMP_PROCESS_TYPE_CLOUD);
if (NULL == node) return;
node->type = IOTX_CMP_PROCESS_CLOUD_UNREGISTER_RESULT;
node->msg = CMP_malloc(sizeof(iotx_cmp_process_register_result_t));
if (NULL == node->msg) {
CMP_ERR(cmp_log_error_memory);
iotx_cmp_free_list_node(node);
return;
}
result_msg = node->msg;
result_msg->URI = _find_topic(packet_id);
result_msg->result = 0;
result_msg->is_register = 0;
rc = iotx_cmp_process_list_push(cmp_pt, IOTX_CMP_PROCESS_TYPE_CLOUD, node);
if (FAIL_RETURN == rc) {
LITE_free(node->msg);
iotx_cmp_free_list_node(node);
}
}
#else
iotx_cmp_mqtt_direct_register_handler(cmp_pt, _find_topic(packet_id), 0, 0);
_delete_topic(packet_id);
#endif
}
break;
case IOTX_MQTT_EVENT_UNSUBCRIBE_TIMEOUT:
case IOTX_MQTT_EVENT_UNSUBCRIBE_NACK:{
#ifdef CMP_SUPPORT_MULTI_THREAD
{
/* send message to itself thread */
int rc = 0;
iotx_cmp_process_list_node_pt node = NULL;
iotx_cmp_process_register_result_pt result_msg = NULL;
node = iotx_cmp_get_list_node(IOTX_CMP_PROCESS_TYPE_CLOUD);
if (NULL == node) return;
node->type = IOTX_CMP_PROCESS_CLOUD_UNREGISTER_RESULT;
node->msg = CMP_malloc(sizeof(iotx_cmp_process_register_result_t));
if (NULL == node->msg) {
CMP_ERR(cmp_log_error_memory);
iotx_cmp_free_list_node(node);
return;
}
result_msg = node->msg;
result_msg->URI = _find_topic(packet_id);
result_msg->result = -1;
result_msg->is_register = 0;
rc = iotx_cmp_process_list_push(cmp_pt, IOTX_CMP_PROCESS_TYPE_CLOUD, node);
if (FAIL_RETURN == rc) {
LITE_free(node->msg);
iotx_cmp_free_list_node(node);
}
}
#else
iotx_cmp_mqtt_direct_register_handler(cmp_pt, _find_topic(packet_id), -1, 0);
_delete_topic(packet_id);
#endif
}
break;
case IOTX_MQTT_EVENT_PUBLISH_SUCCESS:
break;
case IOTX_MQTT_EVENT_PUBLISH_TIMEOUT:
case IOTX_MQTT_EVENT_PUBLISH_NACK:
break;
case IOTX_MQTT_EVENT_PUBLISH_RECVEIVED:{
#ifdef CMP_SUPPORT_MULTI_THREAD
{
/* send message to itself thread */
int rc = 0;
iotx_mqtt_topic_info_pt mqtt_info = (iotx_mqtt_topic_info_pt)msg->msg;
iotx_cmp_process_list_node_pt node = NULL;
iotx_cmp_message_info_pt msg_info = NULL;
#ifdef CMP_SUPPORT_TOPIC_DISPATCH
iotx_cmp_mapping_pt mapping = NULL;
#endif
node = iotx_cmp_get_list_node(IOTX_CMP_PROCESS_TYPE_CLOUD);
if (NULL == node) return;
node->type = IOTX_CMP_PROCESS_CLOUD_NEW_DATA;
node->msg = CMP_malloc(sizeof(iotx_cmp_message_info_t));
if (NULL == node->msg) {
CMP_ERR(cmp_log_error_memory);
iotx_cmp_free_list_node(node);
return;
}
msg_info = node->msg;
msg_info->URI = CMP_malloc(mqtt_info->topic_len + 1);
if (NULL == msg_info->URI) {
CMP_ERR(cmp_log_error_memory);
LITE_free(node->msg);
iotx_cmp_free_list_node(node);
return;
}
if (FAIL_RETURN == iotx_cmp_parse_URI((char*)mqtt_info->ptopic, mqtt_info->topic_len, msg_info->URI, &msg_info->URI_type)) {
CMP_ERR(cmp_log_error_parse_URI);
iotx_cmp_free_message_info(msg_info);
LITE_free(node->msg);
iotx_cmp_free_list_node(node);
return;
}
#ifdef CMP_SUPPORT_TOPIC_DISPATCH
/* find mapping */
mapping = iotx_cmp_find_mapping(cmp_pt, (char*)mqtt_info->ptopic, mqtt_info->topic_len);
if (NULL == mapping) {
CMP_ERR(cmp_log_warning_not_mapping);
iotx_cmp_free_message_info(msg_info);
LITE_free(node->msg);
iotx_cmp_free_list_node(node);
return;
}
msg_info->message_type = mapping->type;
#endif
if (FAIL_RETURN == iotx_cmp_parse_payload((char*)mqtt_info->payload, mqtt_info->payload_len, msg_info)) {
CMP_ERR(cmp_log_error_parse_payload);
iotx_cmp_free_message_info(msg_info);
LITE_free(node->msg);
iotx_cmp_free_list_node(node);
return;
}
rc = iotx_cmp_process_list_push(cmp_pt, IOTX_CMP_PROCESS_TYPE_CLOUD, node);
if (FAIL_RETURN == rc) {
iotx_cmp_free_message_info(msg_info);
LITE_free(node->msg);
iotx_cmp_free_list_node(node);
break;
}
}
#else
iotx_mqtt_topic_info_pt mqtt_info = (iotx_mqtt_topic_info_pt)msg->msg;
iotx_cmp_message_info_t message_info;
#ifdef CMP_SUPPORT_TOPIC_DISPATCH
iotx_cmp_mapping_pt mapping = NULL;
#endif
memset(&message_info, 0x0, sizeof(iotx_cmp_message_info_t));
message_info.URI = CMP_malloc(mqtt_info->topic_len + 1);
if (NULL == message_info.URI) {
CMP_ERR(cmp_log_error_memory);
return;
}
memset(message_info.URI, 0x0, mqtt_info->topic_len + 1);
if (FAIL_RETURN == iotx_cmp_parse_URI((char*)mqtt_info->ptopic, mqtt_info->topic_len, message_info.URI, &message_info.URI_type)) {
CMP_ERR(cmp_log_error_parse_URI);
iotx_cmp_free_message_info(&message_info);
return;
}
#ifdef CMP_SUPPORT_TOPIC_DISPATCH
/* find mapping */
mapping = iotx_cmp_find_mapping(cmp_pt, (char*)mqtt_info->ptopic, mqtt_info->topic_len);
if (NULL == mapping) {
CMP_ERR(cmp_log_warning_not_mapping);
iotx_cmp_free_message_info(&message_info);
return;
}
message_info.message_type = mapping->type;
#endif
if (FAIL_RETURN == iotx_cmp_parse_payload((char*)mqtt_info->payload, mqtt_info->payload_len, &message_info)) {
CMP_ERR(cmp_log_error_parse_payload);
iotx_cmp_free_message_info(&message_info);
return;
}
iotx_cmp_mqtt_direct_response_handler(cmp_pt, &message_info);
#endif
}
break;
case IOTX_MQTT_EVENT_BUFFER_OVERFLOW:
CMP_WARNING(cmp_log_warning_buffer_overflow, msg->msg);
break;
default:
CMP_WARNING(cmp_log_warning_not_arrived);
break;
}
}
int iotx_cmp_mqtt_direct_disconnect_handler(iotx_cmp_conntext_pt cmp_pt)
{
iotx_cmp_event_msg_t event;
if (NULL == cmp_pt) {
CMP_ERR(cmp_log_error_parameter);
return FAIL_RETURN;
}
event.event_id = IOTX_CMP_EVENT_CLOUD_DISCONNECT;
event.msg = NULL;
CMP_INFO(cmp_log_info_MQTT_disconnect);
iotx_cmp_trigger_event_callback(cmp_pt, &event);
return SUCCESS_RETURN;
}
int iotx_cmp_mqtt_direct_reconnect_handler(iotx_cmp_conntext_pt cmp_pt)
{
iotx_cmp_event_msg_t event;
if (NULL == cmp_pt) {
CMP_ERR(cmp_log_error_parameter);
return FAIL_RETURN;
}
event.event_id = IOTX_CMP_EVENT_CLOUD_RECONNECT;
event.msg = NULL;
CMP_INFO(cmp_log_info_MQTT_reconnect);
iotx_cmp_trigger_event_callback(cmp_pt, &event);
return SUCCESS_RETURN;
}
int iotx_cmp_mqtt_direct_register_handler(iotx_cmp_conntext_pt cmp_pt, char* URI, int result, int is_register)
{
iotx_cmp_event_msg_t event;
iotx_cmp_event_result_t result_pt = {0};
if (NULL == cmp_pt) {
CMP_ERR(cmp_log_error_parameter);
return FAIL_RETURN;
}
result_pt.result = result;
result_pt.URI = CMP_malloc(CMP_TOPIC_LEN_MAX);
if (NULL == result_pt.URI) {
CMP_ERR(cmp_log_error_memory);
return FAIL_RETURN;
}
memset(result_pt.URI, 0x0, CMP_TOPIC_LEN_MAX);
if (FAIL_RETURN == iotx_cmp_parse_URI(URI, CMP_TOPIC_LEN_MAX, result_pt.URI, &result_pt.URI_type)) {
CMP_ERR(cmp_log_error_parse_URI);
LITE_free(result_pt.URI);
return FAIL_RETURN;
}
if (is_register)
event.event_id = IOTX_CMP_EVENT_REGISTER_RESULT;
else
event.event_id = IOTX_CMP_EVENT_UNREGISTER_RESULT;
event.msg = (void*)&result_pt;
iotx_cmp_trigger_event_callback(cmp_pt, &event);
_delete_topic(_find_topic_ex(result_pt.URI));
LITE_free(result_pt.URI);
return SUCCESS_RETURN;
}
int iotx_cmp_mqtt_direct_response_handler(iotx_cmp_conntext_pt cmp_pt, iotx_cmp_message_info_pt message_info)
{
if (NULL == cmp_pt || NULL == message_info) {
CMP_ERR(cmp_log_error_parameter);
return FAIL_RETURN;
}
CMP_INFO(cmp_log_info_URI, (char*)message_info->URI);
if (cmp_pt->response_func)
cmp_pt->response_func(cmp_pt, message_info);
iotx_cmp_free_message_info(message_info);
return SUCCESS_RETURN;
}
int iotx_cmp_mqtt_direct_connect(void* handler, void* connectivity_pt)
{
iotx_cmp_connectivity_pt connectivity = (iotx_cmp_connectivity_pt)connectivity_pt;
iotx_cmp_conntext_pt cmp_pt = (iotx_cmp_conntext_pt)handler;
iotx_mqtt_param_t mqtt_params;
iotx_conn_info_pt pconn_info = iotx_conn_info_get();
void *pclient = NULL;
if (NULL == cmp_pt || NULL == connectivity) {
CMP_ERR(cmp_log_error_parameter);
return FAIL_RETURN;
}
/* Initialize MQTT parameter */
memset(&mqtt_params, 0x0, sizeof(mqtt_params));
mqtt_params.port = pconn_info->port;
mqtt_params.host = pconn_info->host_name;
mqtt_params.client_id = pconn_info->client_id;
mqtt_params.username = pconn_info->username;
mqtt_params.password = pconn_info->password;
mqtt_params.pub_key = pconn_info->pub_key;
mqtt_params.request_timeout_ms = 2000;
mqtt_params.clean_session = 0;
mqtt_params.keepalive_interval_ms = 60000;
mqtt_params.pread_buf = mqtt_pt->msg_readbuf;
mqtt_params.read_buf_size = MQTT_MSGLEN;
mqtt_params.pwrite_buf = mqtt_pt->msg_buf;
mqtt_params.write_buf_size = MQTT_MSGLEN;
mqtt_params.handle_event.h_fp = iotx_cmp_mqtt_direct_event_callback;
mqtt_params.handle_event.pcontext = cmp_pt;
/* Construct a MQTT client with specify parameter */
#ifndef MQTT_ID2_AUTH
pclient = IOT_MQTT_Construct(&mqtt_params);
#else
pclient = IOT_MQTT_ConstructSecure(&mqtt_params);
#endif /**< MQTT_ID2_AUTH*/
if (NULL == pclient) {
CMP_ERR(cmp_log_error_fail);
connectivity->is_connected = 0;
return FAIL_RETURN;
}
mqtt_set_instance(pclient);
connectivity->context = pclient;
connectivity->is_connected = 1;
return SUCCESS_RETURN;
}
void* iotx_cmp_mqtt_direct_init(void* handler, iotx_cmp_init_param_pt pparam)
{
iotx_cmp_connectivity_pt connectivity = NULL;
iotx_cmp_conntext_pt cmp_pt = (iotx_cmp_conntext_pt)handler;
if (NULL == cmp_pt || NULL == pparam) {
CMP_ERR(cmp_log_error_parameter);
return NULL;
}
mqtt_pt = CMP_malloc(sizeof(iotx_cmp_mqtt_direct_t));
if (NULL == mqtt_pt){
CMP_ERR(cmp_log_error_memory);
mqtt_pt = NULL;
return NULL;
}
memset(mqtt_pt, 0x0, sizeof(iotx_cmp_mqtt_direct_t));
if (NULL == (mqtt_pt->msg_buf = (char *)CMP_malloc(MQTT_MSGLEN))) {
LITE_free(mqtt_pt);
CMP_ERR(cmp_log_error_memory);
mqtt_pt = NULL;
return NULL;
}
memset(mqtt_pt->msg_buf, 0x0, MQTT_MSGLEN);
if (NULL == (mqtt_pt->msg_readbuf = (char *)CMP_malloc(MQTT_MSGLEN))) {
CMP_ERR(cmp_log_error_memory);
LITE_free(mqtt_pt->msg_buf);
LITE_free(mqtt_pt);
mqtt_pt = NULL;
return NULL;
}
memset(mqtt_pt->msg_readbuf, 0x0, MQTT_MSGLEN);
connectivity = CMP_malloc(sizeof(iotx_cmp_connectivity_t));
if (NULL == connectivity) {
CMP_ERR(cmp_log_error_memory);
iotx_cmp_mqtt_direct_deinit(connectivity);
return NULL;
}
iotx_cmp_mqtt_direct_connect(cmp_pt, connectivity);
connectivity->init_func = iotx_cmp_mqtt_direct_init;
connectivity->connect_func = iotx_cmp_mqtt_direct_connect;
connectivity->register_func = iotx_cmp_mqtt_direct_register;
connectivity->unregister_func = iotx_cmp_mqtt_direct_unregister;
connectivity->send_func = iotx_cmp_mqtt_direct_send;
connectivity->send_sync_func = iotx_cmp_mqtt_direct_send_sync;
connectivity->yield_func = iotx_cmp_mqtt_direct_yield;
connectivity->deinit_func = iotx_cmp_mqtt_direct_deinit;
return connectivity;
}
int iotx_cmp_mqtt_direct_register(void* handler, void* connectivity_pt, const char* topic_filter)
{
int rc = 0;
iotx_cmp_conntext_pt cmp_pt = (iotx_cmp_conntext_pt)handler;
iotx_cmp_connectivity_pt connectivity = (iotx_cmp_connectivity_pt)connectivity_pt;
if (NULL == connectivity || NULL == topic_filter) {
CMP_ERR(cmp_log_error_parameter);
return FAIL_RETURN;
}
rc = IOT_MQTT_Subscribe(connectivity->context,
topic_filter,
IOTX_MQTT_QOS1,
iotx_cmp_mqtt_direct_event_callback,
(void*)cmp_pt);
if (rc > 0)
_add_topic(topic_filter, rc);
return rc;
}
int iotx_cmp_mqtt_direct_unregister(void* handler, void* connectivity_pt, const char* topic_filter)
{
int rc = 0;
iotx_cmp_connectivity_pt connectivity = (iotx_cmp_connectivity_pt)connectivity_pt;
if (NULL == connectivity || NULL == topic_filter) {
CMP_ERR(cmp_log_error_parameter);
return FAIL_RETURN;
}
rc = IOT_MQTT_Unsubscribe(connectivity->context, topic_filter);
if (rc > 0)
_add_topic(topic_filter, rc);
return rc;
}
static iotx_mqtt_qos_t _to_mqtt_qos(iotx_cmp_message_ack_types_t ack_type)
{
switch (ack_type) {
case IOTX_CMP_MESSAGE_NEED_ACK:
return IOTX_MQTT_QOS1;
case IOTX_CMP_MESSAGE_NO_ACK:
return IOTX_MQTT_QOS0;
default:
return IOTX_MQTT_QOS0;
}
}
int iotx_cmp_mqtt_direct_send(void* handler,
void* connectivity_pt,
const char* topic_filter,
iotx_cmp_message_ack_types_t ack_type,
const void* payload,
int payload_length)
{
int rc = 0;
iotx_mqtt_topic_info_t topic_msg;
iotx_cmp_connectivity_pt connectivity = (iotx_cmp_connectivity_pt)connectivity_pt;
if (NULL == connectivity || NULL == topic_filter || NULL == payload) {
CMP_ERR(cmp_log_error_parameter);
return FAIL_RETURN;
}
memset(&topic_msg, 0x0, sizeof(iotx_mqtt_topic_info_t));
topic_msg.dup = 0;
topic_msg.qos = _to_mqtt_qos(ack_type);
topic_msg.retain = 0;
topic_msg.payload_len = payload_length;
topic_msg.payload = payload;
topic_msg.ptopic = topic_filter;
topic_msg.topic_len = strlen(topic_filter);
rc = IOT_MQTT_Publish(connectivity->context, topic_filter, &topic_msg);
return rc;
}
int iotx_cmp_mqtt_direct_send_sync(void* handler,
void* connectivity_pt,
const char* topic_filter,
iotx_cmp_message_ack_types_t ack_type,
const void* payload,
int payload_length)
{
return FAIL_RETURN;
}
int iotx_cmp_mqtt_direct_yield(void* connectivity_pt, int timeout_ms)
{
iotx_cmp_connectivity_pt connectivity = (iotx_cmp_connectivity_pt)connectivity_pt;
if (NULL == connectivity) {
CMP_ERR(cmp_log_error_parameter);
return FAIL_RETURN;
}
return IOT_MQTT_Yield(connectivity->context, timeout_ms);
}
int iotx_cmp_mqtt_direct_deinit(void* connectivity_pt)
{
iotx_cmp_connectivity_pt connectivity = (iotx_cmp_connectivity_pt)connectivity_pt;
int rc = 0;
if (NULL == connectivity)
return FAIL_RETURN;
rc = IOT_MQTT_Destroy(&(connectivity->context));
if (mqtt_pt->list_length != 0)
_delete_all();
if (mqtt_pt->msg_buf)
LITE_free(mqtt_pt->msg_buf);
if (mqtt_pt->msg_readbuf)
LITE_free(mqtt_pt->msg_readbuf);
if (mqtt_pt)
LITE_free(mqtt_pt);
mqtt_pt = NULL;
LITE_free(connectivity);
return rc;
}
#endif /* CMP_VIA_MQTT_DIRECT */
|
the_stack_data/427516.c | #define _DEFAULT_SOURCE
#define _BSD_SOURCE
#define _GNU_SOURCE
/*** includes ***/
#include<ctype.h>
#include<stdio.h>
#include<errno.h>
#include<termios.h>
#include<sys/types.h>
#include<sys/ioctl.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#define STEX_VERSION "0.0.1"
// 0x1F - decimal 27 escape sequence
#define CTRL_KEY(k) ((k) & 0x1F)
/*** DATA STRUCTURES ***/
// datatype for storing a row of a text-editor
typedef struct erow {
int size;
char* chars;
} erow;
struct editorConfiguration {
int cx, cy;
/* row of the file the user is currently scrolled */
int rowOffset;
int screencols;
int screenrows;
int numRows;
erow *row; // array for each row
/* stores original terminal attributes */
struct termios original_termios;
};
struct editorConfiguration E;
enum editorKeys{
ARROW_LEFT = 1000,
ARROW_RIGHT,
ARROW_UP,
ARROW_DOWN,
DEL_KEY,
HOME_KEY,
END_KEY,
PAGE_UP,
PAGE_DOWN
} ;
/*** TERMINAL ***/
struct abuf {
char *b;
int len;
};
#define ABUF_INIT {NULL, 0}
/* error logging function */
void die(const char *s) {
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
perror(s);
exit(1);
}
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);
}
int keyRead(){
int nread;
char c;
while ((nread = read(STDIN_FILENO, &c, 1)) != 1) {
if (nread == -1 && errno != EAGAIN) die("read");
}
// handle escape sequences
if (c == '\x1b') {
char seq[3];
if(read(STDIN_FILENO, &seq[0], 1) != 1)
return '\x1b';
if(read(STDIN_FILENO, &seq[1], 1) != 1)
return '\x1b';
if(seq[0] == '['){
if(seq[1] >= '0' && seq[1] <= '9'){
if(read(STDIN_FILENO, &seq[2], 1) != 1)
return '\x1b';
if(seq[2] == '~'){
switch(seq[1]){
case '1': return HOME_KEY;
case '3': return DEL_KEY;
case '4': return END_KEY;
case '5': return PAGE_UP;
case '6': return PAGE_DOWN;
case '7': return HOME_KEY;
case '8': return END_KEY;
}
}
}else{
// escape sequences for arrow keys
switch(seq[1]){
case 'A' : return ARROW_UP;
case 'B' : return ARROW_DOWN;
case 'C' : return ARROW_RIGHT;
case 'D' : return ARROW_LEFT;
case 'H' : return HOME_KEY;
case 'F' : return END_KEY;
}
}
}else if(seq[0] == 'O'){
switch (seq[1]) {
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
}
return '\x1b';
} else {
return c;
}
}
void exitRawMode(){
/* leave the terminal attributes as they were when exiting */
if(tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.original_termios) == -1) die("tcsetattr");
}
void enterRawMode(){
if (tcgetattr(STDIN_FILENO, &E.original_termios) == -1) die("tcgetattr");
/* whenever exiting the program, restore terminal attribute states */
atexit(exitRawMode);
struct termios raw = E.original_termios;
// flag - IXON turns ctrl+s && ctrl+q software signals off
// flag - ICRNL turns ctrl+m carriage return off
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
// flag - OPOST turns post-processing of output off
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
// flag - ICANON turns canonical mode off
// flag - ISIG turns ctrl+c && ctrl+z signals off
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* adding timeouts for read */
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
}
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){
// moving to the bottom-rightmost pixel to get rows and columns
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12) return -1;
return getCursorPosition(rows, cols);
}else{
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
}
/*** ROW OPERATIONS ***/
void editorAppendRow(char *s, size_t linelen){
E.row = realloc(E.row, sizeof(erow) * (E.numRows + 1));
int at = E.numRows;
E.row[at].size = linelen;
E.row[at].chars = malloc(linelen + 1);
memcpy(E.row[at].chars, s, linelen);
E.row[at].chars[linelen] = '\0';
E.numRows++;
}
/*** FILE I/O ***/
void editorFileOpen(char *filename){
FILE *f = fopen(filename, "r");
if(!f) die("fopen");
char *line = NULL;
size_t linecap = 0;
ssize_t linelen ;
while ((linelen = getline(&line, &linecap, f)) != -1) {
while(linelen > 0 && (line[linelen - 1] == '\n' ||
line[linelen - 1] == '\r'))
linelen--;
editorAppendRow(line, linelen);
}
// release memory
free(line);
fclose(f);
}
/*** INPUT ***/
void editorMoveCursor(int key){
switch(key){
case ARROW_UP :
if(E.cy != 0)
E.cy--;
break;
case ARROW_DOWN :
if(E.cy != E.numRows)
E.cy++;
break;
case ARROW_RIGHT :
if (E.cx != E.screencols - 1)
E.cx++;
break;
case ARROW_LEFT :
if(E.cx != 0)
E.cx--;
break;
default : break;
}
}
void editorKeyPress(){
int c = keyRead();
switch(c){
case CTRL_KEY('q'):
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
exit(0);
break;
case HOME_KEY :
E.cx = 0;
break;
case END_KEY :
E.cx = E.screencols - 1;
break;
case DEL_KEY :
break; // TODO : add logic here
case PAGE_UP:
case PAGE_DOWN :
{
int times = E.screenrows;
while (times--)
editorMoveCursor(c == PAGE_UP ? ARROW_UP : ARROW_DOWN);
}
break;
case ARROW_UP :
case ARROW_DOWN :
case ARROW_RIGHT:
case ARROW_LEFT :
editorMoveCursor(c);
break;
}
}
/*** OUTPUT ***/
void verticalScroll() {
if (E.cy < E.rowOffset) {
// if the cursor is above the visible window
E.rowOffset = E.cy;
}
if (E.cy >= E.rowOffset + E.screenrows) {
// if cursor is below the bottom of visible window
E.rowOffset = E.cy - E.screenrows + 1;
}
}
/**
* @brief adds '~' character at the start of each row
*/
void editorDrawRows(struct abuf *ab) {
for (int y = 0; y < E.screenrows; y++) {
int filerow = y + E.rowOffset;
if(filerow >= E.numRows){
if (E.numRows == 0 && y == E.screenrows / 3) {
// display the text message only if no text file to read
char welcome[80];
int welcomelen = snprintf(welcome, sizeof(welcome),
"Stex editor -- version %s", STEX_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);
}
} else{
// display file
int len = E.row[filerow].size;
if(len > E.screencols) len = E.screencols;
abAppend(ab, E.row[filerow].chars, len);
}
// write(STDOUT_FILENO, "~", 1);
// erasing the right part of each line before drawing
abAppend(ab, "\x1b[K", 3);
if (y < E.screenrows - 1) {
abAppend(ab, "\r\n", 2);
// TODO : terminal status bar display
// write(STDOUT_FILENO, "\r\n", 2);
}
}
}
void editorRefreshScreen() {
// write(STDOUT_FILENO, "\x1b[2J", 4);
// write(STDOUT_FILENO, "\x1b[H", 3);
verticalScroll();
struct abuf ab = ABUF_INIT;
// hide the cursor before drawing screen
abAppend(&ab, "\x1b[?25l", 6);
// the below commented line clears the whole screen
// abAppend(&ab, "\x1b[2J", 4);
abAppend(&ab, "\x1b[H", 3);
// drawing screen
editorDrawRows(&ab);
// postions the cursor at current cx, cy
char buf[32];
snprintf(buf, sizeof(buf), "\x1b[%d;%dH", E.cy+1, E.cx+1);
abAppend(&ab, buf, strlen(buf));
// show the cursor after drawing screen
abAppend(&ab, "\x1b[?25h", 6);
write(STDOUT_FILENO, ab.b, ab.len);
abFree(&ab);
}
/*** INIT ***/
void initEditor() {
E.cx = E.cy = 0;
E.row = NULL;
E.rowOffset = 0;
E.numRows = 0; // TODO : make this dynamic; increment as per lines
if (getWindowSize(&E.screenrows, &E.screencols) == -1)
die("getWindowSize");
}
int main(int argc, char *argv[]){
enterRawMode();
initEditor();
if(argc >= 2){
editorFileOpen(argv[1]);
}
while (1) {
editorRefreshScreen();
editorKeyPress();
}
return 0;
}
|
the_stack_data/190768917.c | /* Verify that the scheduler does not discard the lexical block. */
/* { dg-do compile } */
/* { dg-options "-dA" } */
/* See the comment in debug-1.c. */
/* { dg-options "-dA -fno-if-conversion" { target mips*-*-* } } */
/* { dg-final { scan-assembler "xyzzy" } } */
long p;
long foo(void)
{
if (1)
{
long xyzzy = 0;
if (p)
xyzzy = 2;
return xyzzy;
}
else
{
int x = 0;
return x;
}
}
|
the_stack_data/81330.c | /*
* $Id$
*
* Copyright (C) 2003 Pascal Brisset, Antoine Drouin
*
* This file is part of paparazzi.
*
* paparazzi is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* paparazzi 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 paparazzi; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
/** \file main.c
* \brief Regroup main functions
*
*/
/* --- stuff pulled in from other files ---- sanjit */
// timer.h mostly
#define TCCR1A 0x00 /* sanjit guess from other files */
#define TCCR1B 0x01 /* sanjit guess from other files */
#define TCCR2 0x05 /* sanjit guess from other files */
#define TCNT1 0x1 /* sanjit BIG guess */
#define TCNT1L 0x1 /* sanjit BIG guess */
#define TIFR 0x1 /* sanjit BIG guess */
#define TOV2 0x1 /* sanjit BIG guess */
/*--------------------------------------------- sanjit */
/*
#include "link_autopilot.h"
//sanjit #include "timer.h"
#include "adc.h"
#include "pid.h"
#include "gps.h"
#include "infrared.h"
// sanjit #include "downlink.h"
#include "nav.h"
#include "autopilot.h"
#include "estimator.h"
#include "if_calib.h"
*/
/**** similar stuff as for cctask below ------------- */
#define PPRZ_MODE_MANUAL 0
#define PPRZ_MODE_AUTO1 1
#define PPRZ_MODE_AUTO2 2
#define PPRZ_MODE_HOME 3
#define PPRZ_MODE_NB 4
#define TRIM_PPRZ(pprz) (pprz < MIN_PPRZ ? MIN_PPRZ : \
(pprz > MAX_PPRZ ? MAX_PPRZ : \
pprz))
#define TRIM_UPPRZ(pprz) (pprz < 0 ? 0 : \
(pprz > MAX_PPRZ ? MAX_PPRZ : \
pprz))
/* from autopilot.h ends */
/* from include/std.h */
#define FALSE 0
#define TRUE (!FALSE)
/* include/std.h */
#define NAV_PITCH 0 /* from var/....h */
/* added by sanjit */
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef unsigned char bool_t;
/* sanjit add ends */
/* from sw/var/include/airframe.h */
#define ROLL_PGAIN 10000.
#define PITCH_OF_ROLL 0.0
#define PITCH_PGAIN 15000.
#define MAX_ROLL 0.35
#define MAX_PITCH 0.35
#define MIN_PITCH -0.35
#define CLIMB_PITCH_PGAIN -0.1
#define CLIMB_PITCH_IGAIN 0.025
#define CLIMB_PGAIN -0.03
#define CLIMB_IGAIN 0.1
#define CLIMB_MAX 1.
#define CLIMB_LEVEL_GAZ 0.31
#define CLIMB_PITCH_OF_VZ_PGAIN 0.05
#define CLIMB_GAZ_OF_CLIMB 0.2
/* airframe.h */
#define VERTICAL_MODE_MANUAL 0
#define VERTICAL_MODE_AUTO_GAZ 1
#define VERTICAL_MODE_AUTO_CLIMB 2
#define VERTICAL_MODE_AUTO_ALT 3
#define VERTICAL_MODE_NB 4
#define MAX_CLIMB_SUM_ERR 100
#define MAX_PITCH_CLIMB_SUM_ERR 100
/*---- from fly_by_wire/link_autopilot.h */
/*
* System clock in MHz.
*/
#define CLOCK 16
/* !!!!!!!!!!!!!!!!!!! Value used in gen_airframe.ml !!!!!!!!!!!!!!!!! */
#define MAX_PPRZ (600 * CLOCK)
#define MIN_PPRZ -MAX_PPRZ
/* --- fly_by_wire/link_autopilot.h */
/* from main.c */
// defined below uint8_t pprz_mode;
// defined below uint8_t vertical_mode = VERTICAL_MODE_MANUAL;
// static bool_t low_battery = FALSE;
/* end of stuff from main.c */
#define ALTITUDE_PGAIN -0.025
#define LATERAL_MODE_MANUAL 0
uint16_t nav_desired_gaz;
uint16_t estimator_flight_time;
//bool_t launch = FALSE;
float nav_pitch = NAV_PITCH;
float estimator_z_dot;
//bool_t auto_pitch = FALSE;
/* below vars from pid.c (mostly) */
//float desired_roll = 0.;
//float desired_pitch = 0.;
int16_t desired_gaz, desired_aileron, desired_elevator;
//float roll_pgain = ROLL_PGAIN;
//float pitch_pgain = PITCH_PGAIN;
//float pitch_of_roll = PITCH_OF_ROLL;
//float pitch_of_vz_pgain = CLIMB_PITCH_OF_VZ_PGAIN;
//float pitch_of_vz = 0.;
const float climb_pgain = CLIMB_PGAIN;
const float climb_igain = CLIMB_IGAIN;
// defined below float desired_climb = 0., pre_climb = 0.;
static const float level_gaz = CLIMB_LEVEL_GAZ;
float climb_sum_err = 0;
float climb_pitch_pgain = CLIMB_PITCH_PGAIN;
float climb_pitch_igain = CLIMB_PITCH_IGAIN;
float climb_pitch_sum_err = 0.;
float max_pitch = MAX_PITCH;
float min_pitch = MIN_PITCH;
/**** similar stuff as for cctask above ------------- */
#define IR_ESTIM_MODE_ON 1
#define IR_ROLL_NEUTRAL_DEFAULT -915
#define IR_PITCH_NEUTRAL_DEFAULT 110
#define AV_NB_SAMPLE 0x20
// from radio.h, airframe.h
#define RADIO_CTL_NB 9
#define RADIO_CTL_D 0
#define RADIO_THROTTLE RADIO_CTL_D
#define RADIO_CTL_C 1
#define RADIO_ROLL RADIO_CTL_C
#define RADIO_CTL_B 2
#define RADIO_PITCH RADIO_CTL_B
#define RADIO_CTL_E 5
#define RADIO_GAIN1 RADIO_CTL_E
#define IR_RollOfIrs(x1,x2) (-1*(x1)+ -1*(x2))
#define IR_PitchOfIrs(x1,x2) (-1*(x1)+ 1*(x2))
struct inter_mcu_msg {
int16_t channels[RADIO_CTL_NB];
uint8_t ppm_cpt;
uint8_t status;
uint8_t nb_err;
uint8_t vsupply; /* 1e-1 V */
};
//
//
// FIXME estimator_flight_time should not be manipuled here anymore
//
/** Define minimal speed for takeoff in m/s */
#define MIN_SPEED_FOR_TAKEOFF 5.
uint8_t fatal_error_nb = 0;
static const uint16_t version = 1;
/** in seconds */
static uint16_t cputime = 0;
uint8_t pprz_mode = PPRZ_MODE_MANUAL;
uint8_t vertical_mode = VERTICAL_MODE_MANUAL;
uint8_t lateral_mode = LATERAL_MODE_MANUAL;
uint8_t ir_estim_mode = IR_ESTIM_MODE_ON;
bool_t auto_pitch = FALSE;
bool_t rc_event_1, rc_event_2;
uint8_t vsupply;
static uint8_t mcu1_status, mcu1_ppm_cpt;
static bool_t low_battery = FALSE;
float slider_1_val, slider_2_val;
bool_t launch = FALSE;
#define Min(x, y) (x < y ? x : y)
#define Max(x, y) (x > y ? x : y)
#define NO_CALIB 0 /**< \enum No calibration state */
#define WAITING_CALIB_CONTRAST 1 /**< \enum Waiting calibration contrast state */
#define CALIB_DONE 2 /**< \enum Calibration done state */
/** Maximal delay for calibration */
#define MAX_DELAY_FOR_CALIBRATION 10
#ifdef EST_TEST
float est_pos_x;
float est_pos_y;
float est_fcourse;
uint8_t ticks_last_est; // 20Hz
#endif /* EST_TEST */
/*
called at 20Hz.
sends a serie of initialisation messages followed by a stream of periodic ones
*/
/** Define number of message at initialisation */
#define INIT_MSG_NB 2
/** @@@@@ A FIXER @@@@ */
#define HI_FREQ_PHASE_NB 5
//static char signature[16] = MESSAGES_MD5SUM;
/** \def PERIODIC_SEND_BAT()
* @@@@@ A FIXER @@@@@
*/
#define PERIODIC_SEND_BAT() DOWNLINK_SEND_BAT(&vsupply, &estimator_flight_time, &low_battery, &block_time, &stage_time)
/** \def EventPos(_cpt, _channel, _event)
* @@@@@ A FIXER @@@@@
*/
#define PERIODIC_SEND_DEBUG() DOWNLINK_SEND_DEBUG(&link_fbw_nb_err, &link_fbw_fbw_nb_err, &modem_nb_ovrn, &gps_nb_ovrn, &mcu1_ppm_cpt);
/** \def EventPos(_cpt, _channel, _event)
* @@@@@ A FIXER @@@@@
*/
#define PERIODIC_SEND_ATTITUDE() DOWNLINK_SEND_ATTITUDE(&estimator_phi, &estimator_psi, &estimator_theta);
/** \def EventPos(_cpt, _channel, _event)
* @@@@@ A FIXER @@@@@
*/
#define PERIODIC_SEND_ADC() DOWNLINK_SEND_ADC(&ir_roll, &ir_pitch);
/** \def EventPos(_cpt, _channel, _event)
* @@@@@ A FIXER @@@@@
*/
#define PERIODIC_SEND_STABILISATION() DOWNLINK_SEND_STABILISATION(&roll_pgain, &pitch_pgain);
#define PERIODIC_SEND_CLIMB_PID() DOWNLINK_SEND_CLIMB_PID(&desired_gaz, &desired_climb, &climb_sum_err, &climb_pgain);
#define PERIODIC_SEND_PPRZ_MODE() DOWNLINK_SEND_PPRZ_MODE(&pprz_mode, &vertical_mode, &inflight_calib_mode, &mcu1_status, &ir_estim_mode);
#define PERIODIC_SEND_DESIRED() DOWNLINK_SEND_DESIRED(&desired_roll, &desired_pitch, &desired_x, &desired_y, &desired_altitude);
#define PERIODIC_SEND_PITCH() DOWNLINK_SEND_PITCH(&ir_pitch, &ir_pitch_neutral, &ir_gain);
#define PERIODIC_SEND_NAVIGATION_REF() DOWNLINK_SEND_NAVIGATION_REF(&utm_east0, &utm_north0);
#ifdef RADIO_CALIB
#define PERIODIC_SEND_SETTINGS() if (inflight_calib_mode != IF_CALIB_MODE_NONE) DOWNLINK_SEND_SETTINGS(&inflight_calib_mode, &slider_1_val, &slider_2_val);
#else
#define PERIODIC_SEND_SETTINGS()
#endif
#define PERIOD (256. * 1024. / CLOCK / 1000000.)
/** Maximum time allowed for low battery level */
#define LOW_BATTERY_DELAY 5
/*====================================================================*/
struct adc_buf {
uint16_t sum;
uint16_t values[AV_NB_SAMPLE];
uint8_t head;
};
static struct adc_buf buf_ir1;
static struct adc_buf buf_ir2;
#define EstimatorIrGainIsCorrect() (TRUE)
float desired_roll = 0.;
float desired_pitch = 0.;
int16_t desired_gaz, desired_aileron, desired_elevator;
float roll_pgain = ROLL_PGAIN;
float pitch_pgain = PITCH_PGAIN;
float pitch_of_roll = PITCH_OF_ROLL;
float pitch_of_vz_pgain = CLIMB_PITCH_OF_VZ_PGAIN;
float pitch_of_vz = 0.;
/*--------------- variable defs pulled from other files -----------------------------------*/
/* infrared.c: */
int16_t ir_roll;
int16_t ir_roll_neutral = IR_ROLL_NEUTRAL_DEFAULT;
int16_t ir_pitch;
int16_t ir_pitch_neutral = IR_PITCH_NEUTRAL_DEFAULT;
/* estimator.c: */
float estimator_rad_of_ir, estimator_ir, estimator_rad;
float ir_rad_of_ir;
float rad_of_ir;
float estimator_phi, estimator_theta;
/* link_fbw.c: */
struct inter_mcu_msg to_fbw;
/*--------------- variable defs pulled from other files [above] --------------------------------*/
void stabilisation_task(void)
{
/* ---- inlined below: ir_update(); ---- */
// #ifndef SIMUL
int16_t x1_mean = buf_ir1.sum/AV_NB_SAMPLE;
int16_t x2_mean = buf_ir2.sum/AV_NB_SAMPLE;
/* simplesclar cannot have type decls in the middle of the func */
float rad_of_ir, err, tmp_sanjit;
ir_roll = IR_RollOfIrs(x1_mean, x2_mean) - ir_roll_neutral;
ir_pitch = IR_PitchOfIrs(x1_mean, x2_mean) - ir_pitch_neutral;
/*
#else
extern volatile int16_t simul_ir_roll, simul_ir_pitch;
ir_roll = simul_ir_roll - ir_roll_neutral;
ir_pitch = simul_ir_pitch - ir_pitch_neutral;
#endif
*/
/* ---- inlined below estimator_update_state_infrared(); ---- */
rad_of_ir = (ir_estim_mode == IR_ESTIM_MODE_ON && EstimatorIrGainIsCorrect()) ?
estimator_rad_of_ir : ir_rad_of_ir;
estimator_phi = rad_of_ir * ir_roll;
estimator_theta = rad_of_ir * ir_pitch;
/* --- inlined below roll_pitch_pid_run(); // Set desired_aileron & desired_elevator ---- */
err = estimator_phi - desired_roll;
desired_aileron = TRIM_PPRZ(roll_pgain * err);
if (pitch_of_roll <0.)
pitch_of_roll = 0.;
/* line below commented out by sanjit, to avoid use of fabs
err = -(estimator_theta - desired_pitch - pitch_of_roll * fabs(estimator_phi));
2 replacement lines are below
*/
tmp_sanjit = (estimator_phi < 0) ? -estimator_phi : estimator_phi;
err = -(estimator_theta - desired_pitch - pitch_of_roll * tmp_sanjit);
desired_elevator = TRIM_PPRZ(pitch_pgain * err);
/* --- end inline ---- */
to_fbw.channels[RADIO_THROTTLE] = desired_gaz; // desired_gaz is set upon GPS message reception
to_fbw.channels[RADIO_ROLL] = desired_aileron;
#ifndef ANTON_T7
to_fbw.channels[RADIO_PITCH] = desired_elevator;
#endif
// Code for camera stabilization, FIXME put that elsewhere
to_fbw.channels[RADIO_GAIN1] = TRIM_PPRZ(MAX_PPRZ/0.75*(-estimator_phi));
}
int main()
{
ir_estim_mode = 1;
roll_pgain = 0;
pitch_of_roll = 0;
estimator_rad_of_ir = 0; // estimator_phi = 0;
ir_rad_of_ir = 0; // estimator_phi = 0;
pitch_pgain = 0;
#ifdef PRET
asm(".word 0x22222222");
#endif
}
|
the_stack_data/1117016.c | #include<stdio.h>
#define N 3
int F=-1,R=-1;
void enqueue(int q[],int val){
if((R+1)%N==F){
printf("Queue is full %d is not inserted\n",val);
return;
}
R=(R+1)%N;
q[R]=val;
if(F==-1)
F=0;
}
int dequeue(int q[]){
int item;
if(F==-1){
printf("Queue is empty\n");
return 0;
}
item=q[F];
if(F==R)
F=R=-1;
else
F=(F+1)%N;
return item;
}
void display(int q[]){
int i;
i=F;
do{
printf("%d\t",q[i]);
i=(i+1)%N;
}while(i!=F);
printf("\n");
}
int main(){
int q[N];
int val,n,item;
printf("Enter 1 for insert\n");
printf("Enter 2 for delete\n");
printf("Enter 3 for display\n");
printf("Enter 4 for exit\n");
scanf("%d",&n);
while(n!=4){
switch(n){
case 1:
printf("Enter the value to enter\n");
scanf("%d",&val);
enqueue(q,val);
break;
case 2:
item = dequeue(q);
if(item !=0) printf("%d is deleted\n",item);
break;
case 3:
display(q);
break;
default:
printf("Enter perfect value\n");
}
printf("Enter number according to operation\n");
scanf("%d",&n);
}
}
|
the_stack_data/101985.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main(){
int num1, num2;
int opcao;
printf("Digite um numero:");
scanf("%d", &num1);
printf("Digite outro numero:");
scanf("%d", &num2);
printf("\n Para somar digite 1");
printf("\n Para diminuir digite 2");
printf("\n Para dividir digite 3");
printf("\n Para multiplicar digite 4 \n");
scanf("%d", &opcao);
switch(opcao) {
case 1:
printf("O resultado da soma eh: %d", num1 + num2);
break;
case 2:
printf("O resultado da subtracao eh: %d", num1 - num2);
break;
case 3:
printf("O resultado da divisao eh: %d", num1 / num2);
break;
case 4:
printf("O resultado da multiplicacao eh: %d", num1 * num2);
break;
}
}
|
the_stack_data/400250.c | #include <stdio.h>
int main(){
char a[40];
int i = 0;
while (1) {
while (1) {
scanf("%c", &a[i]);
if (a[i] == '\n') {
break;
}
else {
i++;
}
}
a[i] = '\0';
printf("%s",a);
}
}
|
the_stack_data/211080466.c | /**
* Guião 00 de Sistemmas Operativos.
*
* @author (PIRATA)
* @version (2018.02)
*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 65536
struct intv {
int priml;
int llivres;
struct intv* next;
};
/* Exercicios 3.1 e 4 */
/** @brief Reserva um determinado número de lugares
*
* Função que reserva um determinado número de lugares seguidos, indicando qual o
* primeiro lugar reservado, mesmo que essa área tenha sido previamente usada e
* libertada, tentando reservar numa sequência livre com o minimo de lugares
* excedentários. No caso de não conseguir reservar, devolve -1 em vez do primeiro
* lugar reservado.
*
* @param livres lista ligada com as informações sobre os lugares livres
* @param n número de lugares que pretendemos reservar
* @param reservado valor por onde indicar o primeiro lugar reservado
*
* @return a lista ligada com os lugares atualizados após a reserva
*/
struct intv* reserva (struct intv* livres, int n, int* reservado)
{
struct intv *curr = livres, *best = livres;
int extras = -1, melhor;
/* Procura o melhor sitio para alocar os espaços que obedeça a dois pontos:
- ter espaço suficiente para todos juntos;
- ter o minimo de espaços extras. */
melhor = livres->llivres - n;
while (curr != NULL) {
extras = curr->llivres - n;
if ((extras >= 0) && (extras < melhor)) {
best = curr;
melhor = extras;
}
curr = curr->next;
}
/* Se o melhor for menor que 0, então não existe um bloco disponivel.
Se existe, então o melhor sitio para alocar os espaços está no apontador best. */
if (melhor < 0) {
*reservado = (-1);
} else {
*reservado = best->priml;
best->priml += n;
best->llivres -= n;
}
/* Se os lugares livres for 0 no best, remove este pedaço. */
if (best->llivres == 0) {
curr = livres;
while (curr->next != best) {
curr = curr->next;
}
curr->next = best->next;
free(best);
}
return livres;
}
/* recebe a estrutura com o estádio, o primeiro lugar a libertar e o número de lugares a libertar.
* assumindo que nao se manda libertar lugares que estao livres. */
/** @brief Liberta um determinado número de lugares a partir de uma posição ocupada
*
* Função que liberta um determinado número de lugares seguidos, indicando qual o
* primeiro lugar reservado a libertar e o número de lugares a libertar.
*
* @param livres lista ligada com as informações sobre os lugares livres
* @param lugar primeiro lugar reservado que pretendemos libertar
* @param n número de lugares que pretendemos libertar
*
* @return a lista ligada com os lugares atualizados após a reserva
*/
struct intv* liberta (struct intv* livres, int lugar, int n)
{
struct intv *curr = livres, *prev = NULL, *novo;
/* se o número de lugares a reservar for nulo ou negativo, ou se se pretender libertar
lugares extra-estádio retorna o "estádio" tal como veio */
if ((n <= 0) || ((lugar + n) > MAX_SIZE)) {
return livres;
}
/* enquanto ainda existirem blocos de lugares e o último lugar livre do actual bloco de
* lugares for menor do que o primeiro lugar que se pretende libertar*/
while ((curr != NULL) && ((curr->priml + curr->llivres - 1) < lugar)) {
prev = curr; /* guardar o actual bloco de lugares */
curr = curr->next; /* percorrer a lista ligada */
}
/* Se o sitio que se quer libertar corresponde ao espaço ocupado entre dois blocos. */
if ((prev != NULL) && (prev->priml + prev->llivres == lugar) && (curr->priml == lugar + n)) {
prev->llivres = prev->llivres + n + curr->llivres;
prev->next = curr->next;
free(curr);
return livres;
}
/* Se o espaço a libertar se estende até espaços livres a seguir. */
if ((curr != NULL) && (curr->priml <= lugar + n)) {
curr->llivres = curr->llivres + n - (lugar + n - curr->priml);
curr->priml = lugar;
return livres;
}
/* Se o espaço a libertar se estende a partir dos espaços livres anteriores. */
if ((prev != NULL) && (prev->priml + prev->llivres == lugar)) {
prev->llivres += n;
return livres;
}
/* criar um novo bloco de lugares */
novo = (struct intv *) malloc(sizeof(struct intv));
novo->priml = lugar;
novo->llivres = n;
/* caso se trate de uma adição entre dois blocos, ou à cabeça. */
if (prev != NULL) {
prev->next = novo;
novo->next = curr;
} else {
novo->next = curr;
livres = novo;
}
return livres;
}
/* Exercicios 3.2 e 4 */
/* Quase a mesma coisa que nas versões anteriores mas com umas alterações na parte de retorno de dados.
* Agora usa dupla indireção. */
int reserva2(struct intv **livres, int n)
{
struct intv *curr = *livres, *best = *livres;
int extras = -1, melhor, reservado;
melhor = (*livres)->llivres - n;
while (curr != NULL) {
extras = curr->llivres - n;
if ((extras >= 0) && (extras < melhor)) {
best = curr;
melhor = extras;
}
curr = curr->next;
}
if (melhor < 0) {
reservado = (-1);
} else {
reservado = best->priml;
best->priml += n;
best->llivres -= n;
}
if (best->llivres == 0) {
curr = *livres;
while (curr->next != best) {
curr = curr->next;
}
curr->next = best->next;
free(best);
}
return reservado;
}
void liberta2(struct intv **livres, int lugar, int n)
{
struct intv *curr = *livres, *prev = NULL, *novo;
if (!((n <= 0) || ((lugar + n) > MAX_SIZE))) {
while ((curr != NULL) && ((curr->priml + curr->llivres - 1) < lugar)) {
prev = curr;
curr = curr->next;
}
if ((prev != NULL) && (prev->priml + prev->llivres == lugar) && (curr->priml == lugar + n)) {
prev->llivres = prev->llivres + n + curr->llivres;
prev->next = curr->next;
free(curr);
} else {
if ((curr != NULL) && (curr->priml <= lugar + n)) {
curr->llivres = curr->llivres + n - (lugar + n - curr->priml);
curr->priml = lugar;
} else {
if ((prev != NULL) && (prev->priml + prev->llivres == lugar)) {
prev->llivres += n;
} else {
novo = (struct intv *) malloc(sizeof(struct intv));
novo->priml = lugar;
novo->llivres = n;
if (prev != NULL) {
prev->next = novo;
novo->next = curr;
} else {
novo->next = curr;
(*livres) = novo;
}
}
}
}
}
}
/* Imprime a estrutura com o estádio */
/*
void print(struct intv *estadio)
{
struct intv *aux = estadio;
printf("------------------------------------\n");
while (aux!=NULL) {
printf("Lugares livres do %d até ao %d\n", aux->priml, aux->priml + aux->llivres - 1);
aux = aux->next;
}
printf("------------------------------------\n");
}
*/
/* Função Main de teste. */
/*
int main ()
{
struct intv *estadio = (struct intv *) malloc (sizeof(struct intv));
int rsv[10];
int i;
for (i = 0;i < 10; i++) {
rsv[i] = -1;
}
estadio->priml = 0;
estadio->llivres = MAX_SIZE;
estadio->next = NULL;
print(estadio);
rsv[0] = reserva2(&estadio,1500);
rsv[1] = reserva2(&estadio,1800);
rsv[2] = reserva2(&estadio,1500);
print(estadio);
liberta2(&estadio, 15, 700);
liberta2(&estadio, 900, 700);
print(estadio);
liberta2(&estadio,0,15);
print(estadio);
rsv[3] = reserva2(&estadio,695);
print(estadio);
printf("\n%d - %d - %d - %d\n",rsv[0],rsv[1],rsv[2],rsv[3]);
return 0;
}
*/
|
the_stack_data/122015332.c | // Ejercicio Guion 3 numero 14
#include <stdio.h>
int main()
{
unsigned int fecha;
int temp, tarotNumber, salidaScanf;
salidaScanf = scanf("%d", &fecha);
temp = fecha % 100 + fecha / 100 % 100 + fecha / 10000;
tarotNumber = temp % 10 + temp / 10 % 10 + temp / 100 % 10 + temp / 1000;
tarotNumber = (tarotNumber > 9) ? tarotNumber % 10 + tarotNumber / 10 : tarotNumber;
printf("%d", tarotNumber);
return 0;
}
|
the_stack_data/115766710.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define MaxSize 1000
typedef struct {
int* num;
int first;
int mid;
int last;
int* merge_num;
}paras;
int* dataFromFile(char *argv[]);
int* dataFromInput(void);
void getNum(char* str, int *num);
void QuickSort(int R[],int s,int t);
int partition(int R[],int s,int t);
void merge(int num[], int first, int mid, int last, int merge_num[]);
void *runnerL(void* arg);
void *runnerR(void* arg);
void multiThreading(paras* args);
int size = 0;
int main(int argc, char *argv[]) {
int* num;
paras args;
if(argc == 2) {
num = dataFromFile(argv);
} else {
num = dataFromInput();
}
printf("before(%d):", size);
for(int i = 0; i < size; i++) {
printf("%d ", num[i]);
}
int* merge_num;
merge_num = (int*)malloc(sizeof(int) * size);
args.num = num;
args.first = 0;
args.mid = size/2 - 1;
args.last = size-1;
args.merge_num = merge_num;
multiThreading(&args);
printf("\nafter(%d):", size);
for(int i = 0; i < size; i++) {
printf("%d ", args.merge_num[i]);
}
printf("\n");
free(num);
free(merge_num);
return 0;
}
int* dataFromFile(char *argv[]){
/*
从文件中读取数据
输入:文件名
输出:存放数据的int数组
*/
FILE *in;
int ch;
int i = 0;
int last;
char* str;
if((in = fopen(argv[1], "r")) == NULL) {
printf("Error! Couldn't open the file <%s>!\n", argv[1]);
exit(EXIT_FAILURE);
}
fseek(in, 0L, SEEK_END);
last = ftell(in);
str = (char*)malloc(sizeof(char) * last);
fseek(in, 0L, SEEK_SET);
while((ch = getc(in)) != EOF){
str[i] = ch;
i++;
}
if(fclose(in) != 0){
printf("Error in closing files:<%s>", argv[1]);
}
str[i-1] = '\n';
str[i] = '\0';
int j = 0;
char calc[strlen(str)];
strcpy(calc, str);
for(int i = 0; i < strlen(calc); i++) {
if ((calc[i] < '0' || calc[i] > '9') && calc[i] != '-') {
if (calc[i-1] < '0' || calc[i-1] > '9') {
calc[i] = ' ';
continue;
}
size++;
for(; j <= i; j++) {
calc[j] = ' ';
}
}
}
int *num = (int*)malloc(sizeof(int) * size);
getNum(str, num);
return num;
}
int* dataFromInput(void) {
/*
从用户输入中读取数据
输入:无
输出:存放数据的int数组
*/
printf("请输入一串数字,并用空格隔开,以回车结尾:\n");
char str[MaxSize];
fgets(str,MaxSize,stdin);
int j = 0;
char calc[strlen(str)];
strcpy(calc, str);
for(int i = 0; i < strlen(calc); i++) {
if ((calc[i] < '0' || calc[i] > '9') && calc[i] != '-') {
if (calc[i-1] < '0' || calc[i-1] > '9') {
calc[i] = ' ';
continue;
}
size++;
for(; j <= i; j++) {
calc[j] = ' ';
}
}
}
int *num = (int*)malloc(sizeof(int) * size);
getNum(str, num);
return num;
}
void getNum(char* str, int *num) {
/*
将字符串中数字部分转化为int型数据,剔除无关字符,
!仅在dataFromFile()函数和dataFromInput()函数中被调用
输入:一个字符串str,存储了用非数字字符分隔开的数据;
一个存储数字的int数组用于存放结果
输出:无
*/
int k = 0, j = 0;
for(int i = 0; i < strlen(str); i++) {
if ((str[i] < '0' || str[i] > '9') && str[i] != '-') {
if (str[i-1] < '0' || str[i-1] > '9') {
str[i] = ' ';
continue;
}
num[k] = atoi(str);
k++;
for(; j <= i; j++) {
str[j] = ' ';
}
}
}
}
int partition(int R[],int s,int t) {
/*
设定一个分界值,通过该分界值将数组分成左右两部分
parameter: R:待划分数组
s:数组中的起始位置
t:数组中的结束位置
输出:划分出的中点
*/
int i = s,j = t;
int tmp = R[i];
while (i<j) {
while (j>i && R[j] >= tmp)
j--;
R[i]=R[j];
while (i<j && R[i] <= tmp)
i++;
R[j]=R[i];
}
R[i]=tmp;
return i;
}
void QuickSort(int R[],int s,int t) {
/*
对R[s..t]的元素进行快速排序
parameter: R:待排序数组
s:数组中的起始位置
t:数组中的结束位置
输出:无
*/
int i;
int tmp;
if (s<t) {
i=partition(R,s,t);
QuickSort(R,s,i-1);
QuickSort(R,i+1,t);
}
}
void merge(int num[], int first, int mid, int last, int merge_num[]) {
/*
将排好序的数组合并
parameter: num:原数组,前一半和后一半已分别排好序
first:起始位置
mid:中间位置(与快排相一致)
last:结束位置
merge_num:存放结果的数组
输出:无
*/
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while (i <= m && j <= n)
{
if (num[i] <= num[j])
merge_num[k++] = num[i++];
else
merge_num[k++] = num[j++];
}
while (i <= m)
merge_num[k++] = num[i++];
while (j <= n)
merge_num[k++] = num[j++];
}
void *runnerL(void* arg) {
/*
子线程,将参数转换并传给快排函数
*/
paras* args = (paras*)arg;
QuickSort((*args).num, (*args).first, (*args).mid);
}
void *runnerR(void* arg) {
/*
子线程,将参数转换并传给快排函数
*/
paras* args = (paras*)arg;
QuickSort((*args).num, (*args).mid, (*args).last);
}
void multiThreading(paras* args) {
/*
创建子线程,用快排分别对数组的前一半和后一半进行排序
*/
pthread_t child_1;
pthread_t child_2;
pthread_create(&child_1,NULL,runnerL,args);
pthread_create(&child_2,NULL,runnerR,args);
pthread_join(child_1,NULL);
pthread_join(child_2,NULL);
merge((*args).num, (*args).first, (*args).mid, (*args).last, (*args).merge_num);
}
|
the_stack_data/187641944.c | /*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
int global = 3;
int main() { assert(global == 3); }
|
the_stack_data/126701886.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
#define N 25
int main( ) {
int src[N];
int dst[N];
int i = 0;
while ( src[i] != 0 ) {
dst[i] = src[i];
i = i + 1;
}
i = 0;
while ( src[i] != 0 ) {
__VERIFIER_assert( dst[i] == src[i] );
i = i + 1;
}
return 0;
}
|
the_stack_data/73574138.c | /*
Author : Arnob Mahmud
mail : [email protected]
*/
#include <stdio.h>
int main(int argc, char const *argv[])
{
int A[5], min;
printf("Enter five numbers : ");
for (int i = 0; i < 5; i++)
{
scanf("%d", &A[i]);
}
min = A[0];
for (int i = 0; i < 5; i++)
{
if (A[i] < min)
{
min = A[i];
}
}
printf("Min is : %d", min);
return 0;
}
|
the_stack_data/90762506.c | //
// empty.c
//
// The MIT License
// Copyright (c) 2015 - 2021 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
|
the_stack_data/162643018.c | #ifdef TEST
#include "io.h"
int bss_all_be(){
int *beg, *end;
#ifdef SHOW
println("SHOW ALL BSS VALUE");
#endif
__asm__ volatile ("adr %0, __bss_beg" : "=r"(beg));
__asm__ volatile ("adr %0, __bss_end" : "=r"(end));
for(int *p = beg; p != end; p++){
#ifdef SHOW
print("0x");
_print_ULL_as_number((unsigned long long)p, 16);
println(": ", (int)*p);
#endif
if(*p != 0) return 1;
}
return 0;
}
extern char __stack_top;
int *stack_pointer(){
int *sp;
__asm__ volatile ("mov %0, sp" : "=r"(sp));
#ifdef SHOW
print("sp @0x");
_print_ULL_as_number((unsigned long long)sp, 16);
puts("");
print("__stack_top @0x");
_print_ULL_as_number((unsigned long long)&__stack_top, 16);
puts("");
#endif
return sp;
}
#endif
|
the_stack_data/125018.c |
/*--------------------------------------------------------------------*/
/*--- Platform-specific syscalls stuff. syswrap-ppc64-linux.c ---*/
/*--------------------------------------------------------------------*/
/*
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2005-2015 Nicholas Nethercote <[email protected]>
Copyright (C) 2005-2015 Cerion Armour-Brown <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 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.
The GNU General Public License is contained in the file COPYING.
*/
#if defined(VGP_ppc64be_linux) || defined(VGP_ppc64le_linux)
#include "pub_core_basics.h"
#include "pub_core_vki.h"
#include "pub_core_vkiscnums.h"
#include "pub_core_threadstate.h"
#include "pub_core_aspacemgr.h"
#include "pub_core_debuglog.h"
#include "pub_core_libcbase.h"
#include "pub_core_libcassert.h"
#include "pub_core_libcprint.h"
#include "pub_core_libcproc.h"
#include "pub_core_libcsignal.h"
#include "pub_core_options.h"
#include "pub_core_scheduler.h"
#include "pub_core_sigframe.h" // For VG_(sigframe_destroy)()
#include "pub_core_signals.h"
#include "pub_core_syscall.h"
#include "pub_core_syswrap.h"
#include "pub_core_tooliface.h"
#include "priv_types_n_macros.h"
#include "priv_syswrap-generic.h" /* for decls of generic wrappers */
#include "priv_syswrap-linux.h" /* for decls of linux-ish wrappers */
#include "priv_syswrap-main.h"
/* ---------------------------------------------------------------------
clone() handling
------------------------------------------------------------------ */
/* Call f(arg1), but first switch stacks, using 'stack' as the new
stack, and use 'retaddr' as f's return-to address. Also, clear all
the integer registers before entering f.*/
__attribute__((noreturn))
void ML_(call_on_new_stack_0_1) ( Addr stack,
Addr retaddr,
void (*f_desc)(Word),
Word arg1 );
// r3 = stack
// r4 = retaddr
// r5 = function descriptor
// r6 = arg1
/* On PPC64, a func ptr is represented by a TOC entry ptr.
This TOC entry contains three words; the first word is the function
address, the second word is the TOC ptr (r2), and the third word is
the static chain value. */
asm(
#if defined(VGP_ppc64be_linux)
" .align 2\n"
" .globl vgModuleLocal_call_on_new_stack_0_1\n"
" .section \".opd\",\"aw\"\n"
" .align 3\n"
"vgModuleLocal_call_on_new_stack_0_1:\n"
" .quad .vgModuleLocal_call_on_new_stack_0_1,.TOC.@tocbase,0\n"
" .previous\n"
" .type .vgModuleLocal_call_on_new_stack_0_1,@function\n"
" .globl .vgModuleLocal_call_on_new_stack_0_1\n"
".vgModuleLocal_call_on_new_stack_0_1:\n"
" mr %r1,%r3\n\t" // stack to %sp
" mtlr %r4\n\t" // retaddr to %lr
" ld 5,0(5)\n\t" // load f_ptr from f_desc[0]
" mtctr %r5\n\t" // f_ptr to count reg
" mr %r3,%r6\n\t" // arg1 to %r3
" li 0,0\n\t" // zero all GP regs
" li 4,0\n\t"
" li 5,0\n\t"
" li 6,0\n\t"
" li 7,0\n\t"
" li 8,0\n\t"
" li 9,0\n\t"
" li 10,0\n\t"
" li 11,0\n\t"
" li 12,0\n\t"
" li 13,0\n\t"
" li 14,0\n\t"
" li 15,0\n\t"
" li 16,0\n\t"
" li 17,0\n\t"
" li 18,0\n\t"
" li 19,0\n\t"
" li 20,0\n\t"
" li 21,0\n\t"
" li 22,0\n\t"
" li 23,0\n\t"
" li 24,0\n\t"
" li 25,0\n\t"
" li 26,0\n\t"
" li 27,0\n\t"
" li 28,0\n\t"
" li 29,0\n\t"
" li 30,0\n\t"
" li 31,0\n\t"
" mtxer 0\n\t" // CAB: Need this?
" mtcr 0\n\t" // CAB: Need this?
" bctr\n\t" // jump to dst
" trap\n" // should never get here
#else
// ppc64le_linux
" .align 2\n"
" .globl vgModuleLocal_call_on_new_stack_0_1\n"
"vgModuleLocal_call_on_new_stack_0_1:\n"
" .type .vgModuleLocal_call_on_new_stack_0_1,@function\n"
"#if _CALL_ELF == 2 \n"
"0: addis 2,12,.TOC.-0b@ha\n"
" addi 2,2,.TOC.-0b@l\n"
"#endif\n"
".localentry vgModuleLocal_call_on_new_stack_0_1, .-vgModuleLocal_call_on_new_stack_0_1\n"
" mr %r1,%r3\n\t" // stack to %sp
" mtlr %r4\n\t" // retaddr to %lr
" mtctr %r5\n\t" // f_ptr to count reg
" mr %r3,%r6\n\t" // arg1 to %r3
" li 0,0\n\t" // zero all GP regs
" li 4,0\n\t"
" li 5,0\n\t"
" li 6,0\n\t"
" li 7,0\n\t"
" li 8,0\n\t"
" li 9,0\n\t"
" li 10,0\n\t"
" li 11,0\n\t"
" li 12,0\n\t"
" li 13,0\n\t"
" li 14,0\n\t"
" li 15,0\n\t"
" li 16,0\n\t"
" li 17,0\n\t"
" li 18,0\n\t"
" li 19,0\n\t"
" li 20,0\n\t"
" li 21,0\n\t"
" li 22,0\n\t"
" li 23,0\n\t"
" li 24,0\n\t"
" li 25,0\n\t"
" li 26,0\n\t"
" li 27,0\n\t"
" li 28,0\n\t"
" li 29,0\n\t"
" li 30,0\n\t"
" li 31,0\n\t"
" mtxer 0\n\t" // CAB: Need this?
" mtcr 0\n\t" // CAB: Need this?
" bctr\n\t" // jump to dst
" trap\n" // should never get here
#endif
);
/*
Perform a clone system call. clone is strange because it has
fork()-like return-twice semantics, so it needs special
handling here.
Upon entry, we have:
word (fn)(void*) in r3
void* child_stack in r4
word flags in r5
void* arg in r6
pid_t* child_tid in r7
pid_t* parent_tid in r8
void* ??? in r9
Note: r3 contains fn desc ptr, not fn ptr -- p_fn = p_fn_desc[0]
System call requires:
int $__NR_clone in r0 (sc number)
int flags in r3 (sc arg1)
void* child_stack in r4 (sc arg2)
pid_t* parent_tid in r5 (sc arg3)
?? child_tls in r6 (sc arg4)
pid_t* child_tid in r7 (sc arg5)
void* ??? in r8 (sc arg6)
Returns a ULong encoded as: top half is %cr following syscall,
low half is syscall return value (r3).
*/
#define __NR_CLONE VG_STRINGIFY(__NR_clone)
#define __NR_EXIT VG_STRINGIFY(__NR_exit)
extern
ULong do_syscall_clone_ppc64_linux ( Word (*fn)(void *),
void* stack,
Int flags,
void* arg,
Int* child_tid,
Int* parent_tid,
void/*vki_modify_ldt_t*/ * );
asm(
#if defined(VGP_ppc64be_linux)
" .align 2\n"
" .globl do_syscall_clone_ppc64_linux\n"
" .section \".opd\",\"aw\"\n"
" .align 3\n"
"do_syscall_clone_ppc64_linux:\n"
" .quad .do_syscall_clone_ppc64_linux,.TOC.@tocbase,0\n"
" .previous\n"
" .type .do_syscall_clone_ppc64_linux,@function\n"
" .globl .do_syscall_clone_ppc64_linux\n"
".do_syscall_clone_ppc64_linux:\n"
" stdu 1,-64(1)\n"
" std 29,40(1)\n"
" std 30,48(1)\n"
" std 31,56(1)\n"
" mr 30,3\n" // preserve fn
" mr 31,6\n" // preserve arg
// setup child stack
" rldicr 4,4, 0,59\n" // trim sp to multiple of 16 bytes
// (r4 &= ~0xF)
" li 0,0\n"
" stdu 0,-32(4)\n" // make initial stack frame
" mr 29,4\n" // preserve sp
// setup syscall
" li 0,"__NR_CLONE"\n" // syscall number
" mr 3,5\n" // syscall arg1: flags
// r4 already setup // syscall arg2: child_stack
" mr 5,8\n" // syscall arg3: parent_tid
" mr 6,13\n" // syscall arg4: REAL THREAD tls
" mr 7,7\n" // syscall arg5: child_tid
" mr 8,8\n" // syscall arg6: ????
" mr 9,9\n" // syscall arg7: ????
" sc\n" // clone()
" mfcr 4\n" // CR now in low half r4
" sldi 4,4,32\n" // CR now in hi half r4
" sldi 3,3,32\n"
" srdi 3,3,32\n" // zero out hi half r3
" or 3,3,4\n" // r3 = CR : syscall-retval
" cmpwi 3,0\n" // child if retval == 0 (note, cmpw)
" bne 1f\n" // jump if !child
/* CHILD - call thread function */
/* Note: 2.4 kernel doesn't set the child stack pointer,
so we do it here.
That does leave a small window for a signal to be delivered
on the wrong stack, unfortunately. */
" mr 1,29\n"
" ld 30, 0(30)\n" // convert fn desc ptr to fn ptr
" mtctr 30\n" // ctr reg = fn
" mr 3,31\n" // r3 = arg
" bctrl\n" // call fn()
// exit with result
" li 0,"__NR_EXIT"\n"
" sc\n"
// Exit returned?!
" .long 0\n"
// PARENT or ERROR - return
"1: ld 29,40(1)\n"
" ld 30,48(1)\n"
" ld 31,56(1)\n"
" addi 1,1,64\n"
" blr\n"
#else
" .align 2\n"
" .globl do_syscall_clone_ppc64_linux\n"
" .type do_syscall_clone_ppc64_linux,@function\n"
"do_syscall_clone_ppc64_linux:\n"
" .globl .do_syscall_clone_ppc64_linux\n"
".do_syscall_clone_ppc64_linux:\n"
"#if _CALL_ELF == 2 \n"
"0: addis 2,12,.TOC.-0b@ha \n"
" addi 2,2,.TOC.-0b@l \n"
"#endif \n"
" .localentry do_syscall_clone_ppc64_linux, .-do_syscall_clone_ppc64_linux \n"
" stdu 1,-64(1)\n"
" std 29,40(1)\n"
" std 30,48(1)\n"
" std 31,56(1)\n"
" mr 30,3\n" // preserve fn
" mr 31,6\n" // preserve arg
// setup child stack
" rldicr 4,4, 0,59\n" // trim sp to multiple of 16 bytes
// (r4 &= ~0xF)
" li 0,0\n"
" stdu 0,-32(4)\n" // make initial stack frame
" mr 29,4\n" // preserve sp
// setup syscall
" li 0,"__NR_CLONE"\n" // syscall number
" mr 3,5\n" // syscall arg1: flags
// r4 already setup // syscall arg2: child_stack
" mr 5,8\n" // syscall arg3: parent_tid
" mr 6,13\n" // syscall arg4: REAL THREAD tls
" mr 7,7\n" // syscall arg5: child_tid
" mr 8,8\n" // syscall arg6: ????
" mr 9,9\n" // syscall arg7: ????
" sc\n" // clone()
" mfcr 4\n" // CR now in low half r4
" sldi 4,4,32\n" // CR now in hi half r4
" sldi 3,3,32\n"
" srdi 3,3,32\n" // zero out hi half r3
" or 3,3,4\n" // r3 = CR : syscall-retval
" cmpwi 3,0\n" // child if retval == 0 (note, cmpw)
" bne 1f\n" // jump if !child
/* CHILD - call thread function */
/* Note: 2.4 kernel doesn't set the child stack pointer,
so we do it here.
That does leave a small window for a signal to be delivered
on the wrong stack, unfortunately. */
" mr 1,29\n"
" mtctr 30\n" // ctr reg = fn
" mr 3,31\n" // r3 = arg
" bctrl\n" // call fn()
// exit with result
" li 0,"__NR_EXIT"\n"
" sc\n"
// Exit returned?!
" .long 0\n"
// PARENT or ERROR - return
"1: ld 29,40(1)\n"
" ld 30,48(1)\n"
" ld 31,56(1)\n"
" addi 1,1,64\n"
" blr\n"
#endif
);
#undef __NR_CLONE
#undef __NR_EXIT
// forward declarations
static void setup_child ( ThreadArchState*, ThreadArchState* );
/*
When a client clones, we need to keep track of the new thread. This means:
1. allocate a ThreadId+ThreadState+stack for the thread
2. initialize the thread's new VCPU state
3. create the thread using the same args as the client requested,
but using the scheduler entrypoint for IP, and a separate stack
for SP.
*/
static SysRes do_clone ( ThreadId ptid,
UInt flags, Addr sp,
Int *parent_tidptr,
Int *child_tidptr,
Addr child_tls)
{
const Bool debug = False;
ThreadId ctid = VG_(alloc_ThreadState)();
ThreadState* ptst = VG_(get_ThreadState)(ptid);
ThreadState* ctst = VG_(get_ThreadState)(ctid);
ULong word64;
UWord* stack;
SysRes res;
vki_sigset_t blockall, savedmask;
VG_(sigfillset)(&blockall);
vg_assert(VG_(is_running_thread)(ptid));
vg_assert(VG_(is_valid_tid)(ctid));
stack = (UWord*)ML_(allocstack)(ctid);
if (stack == NULL) {
res = VG_(mk_SysRes_Error)( VKI_ENOMEM );
goto out;
}
//? /* make a stack frame */
//? stack -= 16;
//? *(UWord *)stack = 0;
/* Copy register state
Both parent and child return to the same place, and the code
following the clone syscall works out which is which, so we
don't need to worry about it.
The parent gets the child's new tid returned from clone, but the
child gets 0.
If the clone call specifies a NULL SP for the new thread, then
it actually gets a copy of the parent's SP.
The child's TLS register (r2) gets set to the tlsaddr argument
if the CLONE_SETTLS flag is set.
*/
setup_child( &ctst->arch, &ptst->arch );
/* Make sys_clone appear to have returned Success(0) in the
child. */
{ UInt old_cr = LibVEX_GuestPPC64_get_CR( &ctst->arch.vex );
/* %r3 = 0 */
ctst->arch.vex.guest_GPR3 = 0;
/* %cr0.so = 0 */
LibVEX_GuestPPC64_put_CR( old_cr & ~(1<<28), &ctst->arch.vex );
}
if (sp != 0)
ctst->arch.vex.guest_GPR1 = sp;
ctst->os_state.parent = ptid;
/* inherit signal mask */
ctst->sig_mask = ptst->sig_mask;
ctst->tmp_sig_mask = ptst->sig_mask;
/* Start the child with its threadgroup being the same as the
parent's. This is so that any exit_group calls that happen
after the child is created but before it sets its
os_state.threadgroup field for real (in thread_wrapper in
syswrap-linux.c), really kill the new thread. a.k.a this avoids
a race condition in which the thread is unkillable (via
exit_group) because its threadgroup is not set. The race window
is probably only a few hundred or a few thousand cycles long.
See #226116. */
ctst->os_state.threadgroup = ptst->os_state.threadgroup;
ML_(guess_and_register_stack) (sp, ctst);
/* Assume the clone will succeed, and tell any tool that wants to
know that this thread has come into existence. If the clone
fails, we'll send out a ll_exit notification for it at the out:
label below, to clean up. */
vg_assert(VG_(owns_BigLock_LL)(ptid));
VG_TRACK ( pre_thread_ll_create, ptid, ctid );
if (flags & VKI_CLONE_SETTLS) {
if (debug)
VG_(printf)("clone child has SETTLS: tls at %#lx\n", child_tls);
ctst->arch.vex.guest_GPR13 = child_tls;
}
flags &= ~VKI_CLONE_SETTLS;
/* start the thread with everything blocked */
VG_(sigprocmask)(VKI_SIG_SETMASK, &blockall, &savedmask);
/* Create the new thread */
word64 = do_syscall_clone_ppc64_linux(
ML_(start_thread_NORETURN),
stack, flags, &VG_(threads)[ctid],
child_tidptr, parent_tidptr, NULL
);
/* Low half word64 is syscall return value. Hi half is
the entire CR, from which we need to extract CR0.SO. */
/* VG_(printf)("word64 = 0x%llx\n", word64); */
res = VG_(mk_SysRes_ppc64_linux)(
/*val*/(UInt)(word64 & 0xFFFFFFFFULL),
/*errflag*/ (UInt)((word64 >> (32+28)) & 1)
);
VG_(sigprocmask)(VKI_SIG_SETMASK, &savedmask, NULL);
out:
if (sr_isError(res)) {
/* clone failed */
VG_(cleanup_thread)(&ctst->arch);
ctst->status = VgTs_Empty;
/* oops. Better tell the tool the thread exited in a hurry :-) */
VG_TRACK( pre_thread_ll_exit, ctid );
}
return res;
}
/* ---------------------------------------------------------------------
More thread stuff
------------------------------------------------------------------ */
void VG_(cleanup_thread) ( ThreadArchState* arch )
{
}
void setup_child ( /*OUT*/ ThreadArchState *child,
/*IN*/ ThreadArchState *parent )
{
/* We inherit our parent's guest state. */
child->vex = parent->vex;
child->vex_shadow1 = parent->vex_shadow1;
child->vex_shadow2 = parent->vex_shadow2;
}
/* ---------------------------------------------------------------------
PRE/POST wrappers for ppc64/Linux-specific syscalls
------------------------------------------------------------------ */
#define PRE(name) DEFN_PRE_TEMPLATE(ppc64_linux, name)
#define POST(name) DEFN_POST_TEMPLATE(ppc64_linux, name)
/* Add prototypes for the wrappers declared here, so that gcc doesn't
harass us for not having prototypes. Really this is a kludge --
the right thing to do is to make these wrappers 'static' since they
aren't visible outside this file, but that requires even more macro
magic. */
DECL_TEMPLATE(ppc64_linux, sys_mmap);
//zz DECL_TEMPLATE(ppc64_linux, sys_mmap2);
//zz DECL_TEMPLATE(ppc64_linux, sys_stat64);
//zz DECL_TEMPLATE(ppc64_linux, sys_lstat64);
//zz DECL_TEMPLATE(ppc64_linux, sys_fstat64);
DECL_TEMPLATE(ppc64_linux, sys_clone);
//zz DECL_TEMPLATE(ppc64_linux, sys_sigreturn);
DECL_TEMPLATE(ppc64_linux, sys_rt_sigreturn);
DECL_TEMPLATE(ppc64_linux, sys_fadvise64);
PRE(sys_mmap)
{
SysRes r;
PRINT("sys_mmap ( %#lx, %lu, %lu, %lu, %lu, %lu )",
ARG1, ARG2, ARG3, ARG4, ARG5, ARG6 );
PRE_REG_READ6(long, "mmap",
unsigned long, start, unsigned long, length,
unsigned long, prot, unsigned long, flags,
unsigned long, fd, unsigned long, offset);
r = ML_(generic_PRE_sys_mmap)( tid, ARG1, ARG2, ARG3, ARG4, ARG5,
(Off64T)ARG6 );
SET_STATUS_from_SysRes(r);
}
//zz PRE(sys_mmap2)
//zz {
//zz SysRes r;
//zz
//zz // Exactly like old_mmap() except:
//zz // - the file offset is specified in 4K units rather than bytes,
//zz // so that it can be used for files bigger than 2^32 bytes.
//zz PRINT("sys_mmap2 ( %p, %llu, %d, %d, %d, %d )",
//zz ARG1, (ULong)ARG2, ARG3, ARG4, ARG5, ARG6 );
//zz PRE_REG_READ6(long, "mmap2",
//zz unsigned long, start, unsigned long, length,
//zz unsigned long, prot, unsigned long, flags,
//zz unsigned long, fd, unsigned long, offset);
//zz
//zz r = ML_(generic_PRE_sys_mmap)( tid, ARG1, ARG2, ARG3, ARG4, ARG5,
//zz 4096 * (Off64T)ARG6 );
//zz SET_STATUS_from_SysRes(r);
//zz }
//zz
//zz // XXX: lstat64/fstat64/stat64 are generic, but not necessarily
//zz // applicable to every architecture -- I think only to 32-bit archs.
//zz // We're going to need something like linux/core_os32.h for such
//zz // things, eventually, I think. --njn
//zz PRE(sys_stat64)
//zz {
//zz PRINT("sys_stat64 ( %p, %p )",ARG1,ARG2);
//zz PRE_REG_READ2(long, "stat64", char *, file_name, struct stat64 *, buf);
//zz PRE_MEM_RASCIIZ( "stat64(file_name)", ARG1 );
//zz PRE_MEM_WRITE( "stat64(buf)", ARG2, sizeof(struct vki_stat64) );
//zz }
//zz
//zz POST(sys_stat64)
//zz {
//zz POST_MEM_WRITE( ARG2, sizeof(struct vki_stat64) );
//zz }
//zz
//zz PRE(sys_lstat64)
//zz {
//zz PRINT("sys_lstat64 ( %p(%s), %p )",ARG1,ARG1,ARG2);
//zz PRE_REG_READ2(long, "lstat64", char *, file_name, struct stat64 *, buf);
//zz PRE_MEM_RASCIIZ( "lstat64(file_name)", ARG1 );
//zz PRE_MEM_WRITE( "lstat64(buf)", ARG2, sizeof(struct vki_stat64) );
//zz }
//zz
//zz POST(sys_lstat64)
//zz {
//zz vg_assert(SUCCESS);
//zz if (RES == 0) {
//zz POST_MEM_WRITE( ARG2, sizeof(struct vki_stat64) );
//zz }
//zz }
//zz
//zz PRE(sys_fstat64)
//zz {
//zz PRINT("sys_fstat64 ( %d, %p )",ARG1,ARG2);
//zz PRE_REG_READ2(long, "fstat64", unsigned long, fd, struct stat64 *, buf);
//zz PRE_MEM_WRITE( "fstat64(buf)", ARG2, sizeof(struct vki_stat64) );
//zz }
//zz
//zz POST(sys_fstat64)
//zz {
//zz POST_MEM_WRITE( ARG2, sizeof(struct vki_stat64) );
//zz }
PRE(sys_clone)
{
UInt cloneflags;
PRINT("sys_clone ( %lx, %#lx, %#lx, %#lx, %#lx )",ARG1,ARG2,ARG3,ARG4,ARG5);
PRE_REG_READ5(int, "clone",
unsigned long, flags,
void *, child_stack,
int *, parent_tidptr,
void *, child_tls,
int *, child_tidptr);
if (ARG1 & VKI_CLONE_PARENT_SETTID) {
PRE_MEM_WRITE("clone(parent_tidptr)", ARG3, sizeof(Int));
if (!VG_(am_is_valid_for_client)(ARG3, sizeof(Int),
VKI_PROT_WRITE)) {
SET_STATUS_Failure( VKI_EFAULT );
return;
}
}
if (ARG1 & (VKI_CLONE_CHILD_SETTID | VKI_CLONE_CHILD_CLEARTID)) {
PRE_MEM_WRITE("clone(child_tidptr)", ARG5, sizeof(Int));
if (!VG_(am_is_valid_for_client)(ARG5, sizeof(Int),
VKI_PROT_WRITE)) {
SET_STATUS_Failure( VKI_EFAULT );
return;
}
}
cloneflags = ARG1;
if (!ML_(client_signal_OK)(ARG1 & VKI_CSIGNAL)) {
SET_STATUS_Failure( VKI_EINVAL );
return;
}
/* Only look at the flags we really care about */
switch (cloneflags & (VKI_CLONE_VM | VKI_CLONE_FS
| VKI_CLONE_FILES | VKI_CLONE_VFORK)) {
case VKI_CLONE_VM | VKI_CLONE_FS | VKI_CLONE_FILES:
/* thread creation */
SET_STATUS_from_SysRes(
do_clone(tid,
ARG1, /* flags */
(Addr)ARG2, /* child SP */
(Int *)ARG3, /* parent_tidptr */
(Int *)ARG5, /* child_tidptr */
(Addr)ARG4)); /* child_tls */
break;
case VKI_CLONE_VFORK | VKI_CLONE_VM: /* vfork */
/* FALLTHROUGH - assume vfork == fork */
cloneflags &= ~(VKI_CLONE_VFORK | VKI_CLONE_VM);
case 0: /* plain fork */
SET_STATUS_from_SysRes(
ML_(do_fork_clone)(tid,
cloneflags, /* flags */
(Int *)ARG3, /* parent_tidptr */
(Int *)ARG5)); /* child_tidptr */
break;
default:
/* should we just ENOSYS? */
VG_(message)(Vg_UserMsg, "Unsupported clone() flags: 0x%lx\n", ARG1);
VG_(message)(Vg_UserMsg, "\n");
VG_(message)(Vg_UserMsg, "The only supported clone() uses are:\n");
VG_(message)(Vg_UserMsg, " - via a threads library (LinuxThreads or NPTL)\n");
VG_(message)(Vg_UserMsg, " - via the implementation of fork or vfork\n");
VG_(unimplemented)
("Valgrind does not support general clone().");
}
if (SUCCESS) {
if (ARG1 & VKI_CLONE_PARENT_SETTID)
POST_MEM_WRITE(ARG3, sizeof(Int));
if (ARG1 & (VKI_CLONE_CHILD_SETTID | VKI_CLONE_CHILD_CLEARTID))
POST_MEM_WRITE(ARG5, sizeof(Int));
/* Thread creation was successful; let the child have the chance
to run */
*flags |= SfYieldAfter;
}
}
PRE(sys_fadvise64)
{
PRINT("sys_fadvise64 ( %ld, %ld, %lu, %ld )", SARG1, SARG2, SARG3, SARG4);
PRE_REG_READ4(long, "fadvise64",
int, fd, vki_loff_t, offset, vki_size_t, len, int, advice);
}
PRE(sys_rt_sigreturn)
{
/* See comments on PRE(sys_rt_sigreturn) in syswrap-amd64-linux.c for
an explanation of what follows. */
//ThreadState* tst;
PRINT("sys_rt_sigreturn ( )");
vg_assert(VG_(is_valid_tid)(tid));
vg_assert(tid >= 1 && tid < VG_N_THREADS);
vg_assert(VG_(is_running_thread)(tid));
///* Adjust esp to point to start of frame; skip back up over handler
// ret addr */
//tst = VG_(get_ThreadState)(tid);
//tst->arch.vex.guest_ESP -= sizeof(Addr);
// Should we do something equivalent on ppc64-linux? Who knows.
///* This is only so that the EIP is (might be) useful to report if
// something goes wrong in the sigreturn */
//ML_(fixup_guest_state_to_restart_syscall)(&tst->arch);
// Should we do something equivalent on ppc64? Who knows.
/* Restore register state from frame and remove it */
VG_(sigframe_destroy)(tid, True);
/* Tell the driver not to update the guest state with the "result",
and set a bogus result to keep it happy. */
*flags |= SfNoWriteResult;
SET_STATUS_Success(0);
/* Check to see if any signals arose as a result of this. */
*flags |= SfPollAfter;
}
#undef PRE
#undef POST
/* ---------------------------------------------------------------------
The ppc64/Linux syscall table
------------------------------------------------------------------ */
/* Add an ppc64-linux specific wrapper to a syscall table. */
#define PLAX_(sysno, name) WRAPPER_ENTRY_X_(ppc64_linux, sysno, name)
#define PLAXY(sysno, name) WRAPPER_ENTRY_XY(ppc64_linux, sysno, name)
// This table maps from __NR_xxx syscall numbers (from
// linux/include/asm-ppc/unistd.h) to the appropriate PRE/POST sys_foo()
// wrappers on ppc64 (as per sys_call_table in linux/arch/ppc/kernel/entry.S).
//
// For those syscalls not handled by Valgrind, the annotation indicate its
// arch/OS combination, eg. */* (generic), */Linux (Linux only), ?/?
// (unknown).
static SyscallTableEntry syscall_table[] = {
// _____(__NR_restart_syscall, sys_restart_syscall), // 0
GENX_(__NR_exit, sys_exit), // 1
GENX_(__NR_fork, sys_fork), // 2
GENXY(__NR_read, sys_read), // 3
GENX_(__NR_write, sys_write), // 4
GENXY(__NR_open, sys_open), // 5
GENXY(__NR_close, sys_close), // 6
GENXY(__NR_waitpid, sys_waitpid), // 7
GENXY(__NR_creat, sys_creat), // 8
GENX_(__NR_link, sys_link), // 9
GENX_(__NR_unlink, sys_unlink), // 10
GENX_(__NR_execve, sys_execve), // 11
GENX_(__NR_chdir, sys_chdir), // 12
GENXY(__NR_time, sys_time), // 13
GENX_(__NR_mknod, sys_mknod), // 14
GENX_(__NR_chmod, sys_chmod), // 15
GENX_(__NR_lchown, sys_lchown), // 16
// _____(__NR_break, sys_break), // 17
// _____(__NR_oldstat, sys_oldstat), // 18
LINX_(__NR_lseek, sys_lseek), // 19
GENX_(__NR_getpid, sys_getpid), // 20
LINX_(__NR_mount, sys_mount), // 21
// _____(__NR_umount, sys_umount), // 22
GENX_(__NR_setuid, sys_setuid), // 23
GENX_(__NR_getuid, sys_getuid), // 24
// _____(__NR_stime, sys_stime), // 25
// When ptrace is supported, memcheck/tests/linux/getregset should be enabled
// _____(__NR_ptrace, sys_ptrace), // 26
GENX_(__NR_alarm, sys_alarm), // 27
// _____(__NR_oldfstat, sys_oldfstat), // 28
GENX_(__NR_pause, sys_pause), // 29
LINX_(__NR_utime, sys_utime), // 30
// _____(__NR_stty, sys_stty), // 31
// _____(__NR_gtty, sys_gtty), // 32
GENX_(__NR_access, sys_access), // 33
// _____(__NR_nice, sys_nice), // 34
// _____(__NR_ftime, sys_ftime), // 35
// _____(__NR_sync, sys_sync), // 36
GENX_(__NR_kill, sys_kill), // 37
GENX_(__NR_rename, sys_rename), // 38
GENX_(__NR_mkdir, sys_mkdir), // 39
GENX_(__NR_rmdir, sys_rmdir), // 40
GENXY(__NR_dup, sys_dup), // 41
LINXY(__NR_pipe, sys_pipe), // 42
GENXY(__NR_times, sys_times), // 43
// _____(__NR_prof, sys_prof), // 44
GENX_(__NR_brk, sys_brk), // 45
GENX_(__NR_setgid, sys_setgid), // 46
GENX_(__NR_getgid, sys_getgid), // 47
// _____(__NR_signal, sys_signal), // 48
GENX_(__NR_geteuid, sys_geteuid), // 49
GENX_(__NR_getegid, sys_getegid), // 50
// _____(__NR_acct, sys_acct), // 51
LINX_(__NR_umount2, sys_umount), // 52
// _____(__NR_lock, sys_lock), // 53
LINXY(__NR_ioctl, sys_ioctl), // 54
LINXY(__NR_fcntl, sys_fcntl), // 55
// _____(__NR_mpx, sys_mpx), // 56
GENX_(__NR_setpgid, sys_setpgid), // 57
// _____(__NR_ulimit, sys_ulimit), // 58
// _____(__NR_oldolduname, sys_oldolduname), // 59
GENX_(__NR_umask, sys_umask), // 60
GENX_(__NR_chroot, sys_chroot), // 61
// _____(__NR_ustat, sys_ustat), // 62
GENXY(__NR_dup2, sys_dup2), // 63
GENX_(__NR_getppid, sys_getppid), // 64
GENX_(__NR_getpgrp, sys_getpgrp), // 65
GENX_(__NR_setsid, sys_setsid), // 66
// _____(__NR_sigaction, sys_sigaction), // 67
// _____(__NR_sgetmask, sys_sgetmask), // 68
// _____(__NR_ssetmask, sys_ssetmask), // 69
GENX_(__NR_setreuid, sys_setreuid), // 70
GENX_(__NR_setregid, sys_setregid), // 71
// _____(__NR_sigsuspend, sys_sigsuspend), // 72
// _____(__NR_sigpending, sys_sigpending), // 73
// _____(__NR_sethostname, sys_sethostname), // 74
GENX_(__NR_setrlimit, sys_setrlimit), // 75
// _____(__NR_getrlimit, sys_getrlimit), // 76
GENXY(__NR_getrusage, sys_getrusage), // 77
GENXY(__NR_gettimeofday, sys_gettimeofday), // 78
// _____(__NR_settimeofday, sys_settimeofday), // 79
GENXY(__NR_getgroups, sys_getgroups), // 80
GENX_(__NR_setgroups, sys_setgroups), // 81
// _____(__NR_select, sys_select), // 82
GENX_(__NR_symlink, sys_symlink), // 83
// _____(__NR_oldlstat, sys_oldlstat), // 84
GENX_(__NR_readlink, sys_readlink), // 85
// _____(__NR_uselib, sys_uselib), // 86
// _____(__NR_swapon, sys_swapon), // 87
// _____(__NR_reboot, sys_reboot), // 88
// _____(__NR_readdir, sys_readdir), // 89
PLAX_(__NR_mmap, sys_mmap), // 90
GENXY(__NR_munmap, sys_munmap), // 91
GENX_(__NR_truncate, sys_truncate), // 92
GENX_(__NR_ftruncate, sys_ftruncate), // 93
GENX_(__NR_fchmod, sys_fchmod), // 94
GENX_(__NR_fchown, sys_fchown), // 95
GENX_(__NR_getpriority, sys_getpriority), // 96
GENX_(__NR_setpriority, sys_setpriority), // 97
// _____(__NR_profil, sys_profil), // 98
GENXY(__NR_statfs, sys_statfs), // 99
GENXY(__NR_fstatfs, sys_fstatfs), // 100
// _____(__NR_ioperm, sys_ioperm), // 101
LINXY(__NR_socketcall, sys_socketcall), // 102
LINXY(__NR_syslog, sys_syslog), // 103
GENXY(__NR_setitimer, sys_setitimer), // 104
GENXY(__NR_getitimer, sys_getitimer), // 105
GENXY(__NR_stat, sys_newstat), // 106
GENXY(__NR_lstat, sys_newlstat), // 107
GENXY(__NR_fstat, sys_newfstat), // 108
// _____(__NR_olduname, sys_olduname), // 109
// _____(__NR_iopl, sys_iopl), // 110
LINX_(__NR_vhangup, sys_vhangup), // 111
// _____(__NR_idle, sys_idle), // 112
// _____(__NR_vm86, sys_vm86), // 113
GENXY(__NR_wait4, sys_wait4), // 114
// _____(__NR_swapoff, sys_swapoff), // 115
LINXY(__NR_sysinfo, sys_sysinfo), // 116
LINXY(__NR_ipc, sys_ipc), // 117
GENX_(__NR_fsync, sys_fsync), // 118
// _____(__NR_sigreturn, sys_sigreturn), // 119
PLAX_(__NR_clone, sys_clone), // 120
// _____(__NR_setdomainname, sys_setdomainname), // 121
GENXY(__NR_uname, sys_newuname), // 122
// _____(__NR_modify_ldt, sys_modify_ldt), // 123
LINXY(__NR_adjtimex, sys_adjtimex), // 124
GENXY(__NR_mprotect, sys_mprotect), // 125
// _____(__NR_sigprocmask, sys_sigprocmask), // 126
GENX_(__NR_create_module, sys_ni_syscall), // 127
LINX_(__NR_init_module, sys_init_module), // 128
LINX_(__NR_delete_module, sys_delete_module), // 129
// _____(__NR_get_kernel_syms, sys_get_kernel_syms), // 130
// _____(__NR_quotactl, sys_quotactl), // 131
GENX_(__NR_getpgid, sys_getpgid), // 132
GENX_(__NR_fchdir, sys_fchdir), // 133
// _____(__NR_bdflush, sys_bdflush), // 134
// _____(__NR_sysfs, sys_sysfs), // 135
LINX_(__NR_personality, sys_personality), // 136
// _____(__NR_afs_syscall, sys_afs_syscall), // 137
LINX_(__NR_setfsuid, sys_setfsuid), // 138
LINX_(__NR_setfsgid, sys_setfsgid), // 139
LINXY(__NR__llseek, sys_llseek), // 140
GENXY(__NR_getdents, sys_getdents), // 141
GENX_(__NR__newselect, sys_select), // 142
GENX_(__NR_flock, sys_flock), // 143
GENX_(__NR_msync, sys_msync), // 144
GENXY(__NR_readv, sys_readv), // 145
GENX_(__NR_writev, sys_writev), // 146
// _____(__NR_getsid, sys_getsid), // 147
GENX_(__NR_fdatasync, sys_fdatasync), // 148
LINXY(__NR__sysctl, sys_sysctl), // 149
GENX_(__NR_mlock, sys_mlock), // 150
GENX_(__NR_munlock, sys_munlock), // 151
GENX_(__NR_mlockall, sys_mlockall), // 152
LINX_(__NR_munlockall, sys_munlockall), // 153
LINXY(__NR_sched_setparam, sys_sched_setparam), // 154
LINXY(__NR_sched_getparam, sys_sched_getparam), // 155
LINX_(__NR_sched_setscheduler, sys_sched_setscheduler), // 156
LINX_(__NR_sched_getscheduler, sys_sched_getscheduler), // 157
LINX_(__NR_sched_yield, sys_sched_yield), // 158
LINX_(__NR_sched_get_priority_max, sys_sched_get_priority_max),// 159
LINX_(__NR_sched_get_priority_min, sys_sched_get_priority_min),// 160
LINXY(__NR_sched_rr_get_interval, sys_sched_rr_get_interval), // 161
GENXY(__NR_nanosleep, sys_nanosleep), // 162
GENX_(__NR_mremap, sys_mremap), // 163
LINX_(__NR_setresuid, sys_setresuid), // 164
LINXY(__NR_getresuid, sys_getresuid), // 165
// _____(__NR_query_module, sys_query_module), // 166
GENXY(__NR_poll, sys_poll), // 167
// _____(__NR_nfsservctl, sys_nfsservctl), // 168
LINX_(__NR_setresgid, sys_setresgid), // 169
LINXY(__NR_getresgid, sys_getresgid), // 170
LINXY(__NR_prctl, sys_prctl), // 171
PLAX_(__NR_rt_sigreturn, sys_rt_sigreturn), // 172
LINXY(__NR_rt_sigaction, sys_rt_sigaction), // 173
LINXY(__NR_rt_sigprocmask, sys_rt_sigprocmask), // 174
LINXY(__NR_rt_sigpending, sys_rt_sigpending), // 175
LINXY(__NR_rt_sigtimedwait, sys_rt_sigtimedwait), // 176
LINXY(__NR_rt_sigqueueinfo, sys_rt_sigqueueinfo), // 177
LINX_(__NR_rt_sigsuspend, sys_rt_sigsuspend), // 178
GENXY(__NR_pread64, sys_pread64), // 179
GENX_(__NR_pwrite64, sys_pwrite64), // 180
GENX_(__NR_chown, sys_chown), // 181
GENXY(__NR_getcwd, sys_getcwd), // 182
LINXY(__NR_capget, sys_capget), // 183
LINX_(__NR_capset, sys_capset), // 184
GENXY(__NR_sigaltstack, sys_sigaltstack), // 185
LINXY(__NR_sendfile, sys_sendfile), // 186
// _____(__NR_getpmsg, sys_getpmsg), // 187
// _____(__NR_putpmsg, sys_putpmsg), // 188
GENX_(__NR_vfork, sys_fork), // 189 treat as fork
GENXY(__NR_ugetrlimit, sys_getrlimit), // 190
LINX_(__NR_readahead, sys_readahead), // 191
// /* #define __NR_mmap2 192 32bit only */
// /* #define __NR_truncate64 193 32bit only */
// /* #define __NR_ftruncate64 194 32bit only */
// /* #define __NR_stat64 195 32bit only */
// /* #define __NR_lstat64 196 32bit only */
// /* #define __NR_fstat64 197 32bit only */
// _____(__NR_pciconfig_read, sys_pciconfig_read), // 198
// _____(__NR_pciconfig_write, sys_pciconfig_write), // 199
// _____(__NR_pciconfig_iobase, sys_pciconfig_iobase), // 200
// _____(__NR_multiplexer, sys_multiplexer), // 201
GENXY(__NR_getdents64, sys_getdents64), // 202
LINX_(__NR_pivot_root, sys_pivot_root), // 203
LINXY(__NR_fcntl64, sys_fcntl64), // 204 !!!!?? 32bit only */
GENX_(__NR_madvise, sys_madvise), // 205
// _____(__NR_mincore, sys_mincore), // 206
LINX_(__NR_gettid, sys_gettid), // 207
// _____(__NR_tkill, sys_tkill), // 208
LINX_(__NR_setxattr, sys_setxattr), // 209
LINX_(__NR_lsetxattr, sys_lsetxattr), // 210
LINX_(__NR_fsetxattr, sys_fsetxattr), // 211
LINXY(__NR_getxattr, sys_getxattr), // 212
LINXY(__NR_lgetxattr, sys_lgetxattr), // 213
LINXY(__NR_fgetxattr, sys_fgetxattr), // 214
LINXY(__NR_listxattr, sys_listxattr), // 215
LINXY(__NR_llistxattr, sys_llistxattr), // 216
LINXY(__NR_flistxattr, sys_flistxattr), // 217
LINX_(__NR_removexattr, sys_removexattr), // 218
LINX_(__NR_lremovexattr, sys_lremovexattr), // 219
LINX_(__NR_fremovexattr, sys_fremovexattr), // 220
LINXY(__NR_futex, sys_futex), // 221
LINX_(__NR_sched_setaffinity, sys_sched_setaffinity), // 222
LINXY(__NR_sched_getaffinity, sys_sched_getaffinity), // 223
// /* 224 currently unused */
// _____(__NR_tuxcall, sys_tuxcall), // 225
// /* #define __NR_sendfile64 226 32bit only */
LINX_(__NR_io_setup, sys_io_setup), // 227
LINX_(__NR_io_destroy, sys_io_destroy), // 228
LINXY(__NR_io_getevents, sys_io_getevents), // 229
LINX_(__NR_io_submit, sys_io_submit), // 230
LINXY(__NR_io_cancel, sys_io_cancel), // 231
LINX_(__NR_set_tid_address, sys_set_tid_address), // 232
PLAX_(__NR_fadvise64, sys_fadvise64), // 233
LINX_(__NR_exit_group, sys_exit_group), // 234
// _____(__NR_lookup_dcookie, sys_lookup_dcookie), // 235
LINXY(__NR_epoll_create, sys_epoll_create), // 236
LINX_(__NR_epoll_ctl, sys_epoll_ctl), // 237
LINXY(__NR_epoll_wait, sys_epoll_wait), // 238
// _____(__NR_remap_file_pages, sys_remap_file_pages), // 239
LINXY(__NR_timer_create, sys_timer_create), // 240
LINXY(__NR_timer_settime, sys_timer_settime), // 241
LINXY(__NR_timer_gettime, sys_timer_gettime), // 242
LINX_(__NR_timer_getoverrun, sys_timer_getoverrun), // 243
LINX_(__NR_timer_delete, sys_timer_delete), // 244
LINX_(__NR_clock_settime, sys_clock_settime), // 245
LINXY(__NR_clock_gettime, sys_clock_gettime), // 246
LINXY(__NR_clock_getres, sys_clock_getres), // 247
LINXY(__NR_clock_nanosleep, sys_clock_nanosleep), // 248
// _____(__NR_swapcontext, sys_swapcontext), // 249
LINXY(__NR_tgkill, sys_tgkill), // 250
// _____(__NR_utimes, sys_utimes), // 251
// _____(__NR_statfs64, sys_statfs64), // 252
// _____(__NR_fstatfs64, sys_fstatfs64), // 253
// /* #define __NR_fadvise64_64 254 32bit only */
// _____(__NR_rtas, sys_rtas), // 255
// /* Number 256 is reserved for sys_debug_setcontext */
// /* Number 257 is reserved for vserver */
// /* 258 currently unused */
LINX_(__NR_mbind, sys_mbind), // 259
LINXY(__NR_get_mempolicy, sys_get_mempolicy), // 260
LINX_(__NR_set_mempolicy, sys_set_mempolicy), // 261
LINXY(__NR_mq_open, sys_mq_open), // 262
LINX_(__NR_mq_unlink, sys_mq_unlink), // 263
LINX_(__NR_mq_timedsend, sys_mq_timedsend), // 264
LINXY(__NR_mq_timedreceive, sys_mq_timedreceive), // 265
LINX_(__NR_mq_notify, sys_mq_notify), // 266
LINXY(__NR_mq_getsetattr, sys_mq_getsetattr), // 267
// _____(__NR_kexec_load, sys_kexec_load), // 268
LINX_(__NR_add_key, sys_add_key), // 269
LINX_(__NR_request_key, sys_request_key), // 270
LINXY(__NR_keyctl, sys_keyctl), // 271
// _____(__NR_waitid, sys_waitid), // 272
LINX_(__NR_ioprio_set, sys_ioprio_set), // 273
LINX_(__NR_ioprio_get, sys_ioprio_get), // 274
LINX_(__NR_inotify_init, sys_inotify_init), // 275
LINX_(__NR_inotify_add_watch, sys_inotify_add_watch), // 276
LINX_(__NR_inotify_rm_watch, sys_inotify_rm_watch), // 277
LINX_(__NR_pselect6, sys_pselect6), // 280
LINXY(__NR_ppoll, sys_ppoll), // 281
LINXY(__NR_openat, sys_openat), // 286
LINX_(__NR_mkdirat, sys_mkdirat), // 287
LINX_(__NR_mknodat, sys_mknodat), // 288
LINX_(__NR_fchownat, sys_fchownat), // 289
LINX_(__NR_futimesat, sys_futimesat), // 290
LINXY(__NR_newfstatat, sys_newfstatat), // 291
LINX_(__NR_unlinkat, sys_unlinkat), // 292
LINX_(__NR_renameat, sys_renameat), // 293
LINX_(__NR_linkat, sys_linkat), // 294
LINX_(__NR_symlinkat, sys_symlinkat), // 295
LINX_(__NR_readlinkat, sys_readlinkat), // 296
LINX_(__NR_fchmodat, sys_fchmodat), // 297
LINX_(__NR_faccessat, sys_faccessat), // 298
LINX_(__NR_set_robust_list, sys_set_robust_list), // 299
LINXY(__NR_get_robust_list, sys_get_robust_list), // 300
LINXY(__NR_move_pages, sys_move_pages), // 301
LINXY(__NR_getcpu, sys_getcpu), // 302
LINXY(__NR_epoll_pwait, sys_epoll_pwait), // 303
LINX_(__NR_utimensat, sys_utimensat), // 304
LINXY(__NR_signalfd, sys_signalfd), // 305
LINXY(__NR_timerfd_create, sys_timerfd_create), // 306
LINXY(__NR_eventfd, sys_eventfd), // 307
LINX_(__NR_sync_file_range2, sys_sync_file_range2), // 308
LINX_(__NR_fallocate, sys_fallocate), // 309
// LINXY(__NR_subpage_prot, sys_ni_syscall), // 310
LINXY(__NR_timerfd_settime, sys_timerfd_settime), // 311
LINXY(__NR_timerfd_gettime, sys_timerfd_gettime), // 312
LINXY(__NR_signalfd4, sys_signalfd4), // 313
LINXY(__NR_eventfd2, sys_eventfd2), // 314
LINXY(__NR_epoll_create1, sys_epoll_create1), // 315
LINXY(__NR_dup3, sys_dup3), // 316
LINXY(__NR_pipe2, sys_pipe2), // 317
LINXY(__NR_inotify_init1, sys_inotify_init1), // 318
LINXY(__NR_perf_event_open, sys_perf_event_open), // 319
LINXY(__NR_preadv, sys_preadv), // 320
LINX_(__NR_pwritev, sys_pwritev), // 321
LINXY(__NR_rt_tgsigqueueinfo, sys_rt_tgsigqueueinfo),// 322
LINXY(__NR_recvmmsg, sys_recvmmsg), // 343
LINXY(__NR_accept4, sys_accept4), // 344
LINXY(__NR_clock_adjtime, sys_clock_adjtime), // 347
LINX_(__NR_syncfs, sys_syncfs), // 348
LINXY(__NR_sendmmsg, sys_sendmmsg), // 349
LINXY(__NR_process_vm_readv, sys_process_vm_readv), // 351
LINX_(__NR_process_vm_writev, sys_process_vm_writev),// 352
LINXY(__NR_getrandom, sys_getrandom), // 359
LINXY(__NR_memfd_create, sys_memfd_create) // 360
};
SyscallTableEntry* ML_(get_linux_syscall_entry) ( UInt sysno )
{
const UInt syscall_table_size
= sizeof(syscall_table) / sizeof(syscall_table[0]);
/* Is it in the contiguous initial section of the table? */
if (sysno < syscall_table_size) {
SyscallTableEntry* sys = &syscall_table[sysno];
if (sys->before == NULL)
return NULL; /* no entry */
else
return sys;
}
/* Can't find a wrapper */
return NULL;
}
#endif // defined(VGP_ppc64be_linux) || defined(VGP_ppc64le_linux)
/*--------------------------------------------------------------------*/
/*--- end ---*/
/*--------------------------------------------------------------------*/
|
the_stack_data/37638578.c | // This file was generated by bintoc utility
// Binary data from file "a_vga_font.fon"
#include <stdint.h>
uint8_t vgafnt[] =
{
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7E,
0x81,
0xA5,
0x81,
0x81,
0xBD,
0x99,
0x81,
0x81,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7E,
0xFF,
0xDB,
0xFF,
0xFF,
0xC3,
0xE7,
0xFF,
0xFF,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x6C,
0xFE,
0xFE,
0xFE,
0xFE,
0x7C,
0x38,
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x38,
0x7C,
0xFE,
0x7C,
0x38,
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x3C,
0x3C,
0xE7,
0xE7,
0xE7,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x3C,
0x7E,
0xFF,
0xFF,
0x7E,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x3C,
0x3C,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xE7,
0xC3,
0xC3,
0xE7,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x66,
0x42,
0x42,
0x66,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xC3,
0x99,
0xBD,
0xBD,
0x99,
0xC3,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0x00,
0x00,
0x1E,
0x0E,
0x1A,
0x32,
0x78,
0xCC,
0xCC,
0xCC,
0xCC,
0x78,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x66,
0x66,
0x66,
0x66,
0x3C,
0x18,
0x7E,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3F,
0x33,
0x3F,
0x30,
0x30,
0x30,
0x30,
0x70,
0xF0,
0xE0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7F,
0x63,
0x7F,
0x63,
0x63,
0x63,
0x63,
0x67,
0xE7,
0xE6,
0xC0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0xDB,
0x3C,
0xE7,
0x3C,
0xDB,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x80,
0xC0,
0xE0,
0xF0,
0xF8,
0xFE,
0xF8,
0xF0,
0xE0,
0xC0,
0x80,
0x00,
0x00,
0x00,
0x00,
0x00,
0x02,
0x06,
0x0E,
0x1E,
0x3E,
0xFE,
0x3E,
0x1E,
0x0E,
0x06,
0x02,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x3C,
0x7E,
0x18,
0x18,
0x18,
0x7E,
0x3C,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x66,
0x66,
0x66,
0x66,
0x66,
0x66,
0x66,
0x00,
0x66,
0x66,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7F,
0xDB,
0xDB,
0xDB,
0x7B,
0x1B,
0x1B,
0x1B,
0x1B,
0x1B,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0x60,
0x38,
0x6C,
0xC6,
0xC6,
0x6C,
0x38,
0x0C,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0xFE,
0xFE,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x3C,
0x7E,
0x18,
0x18,
0x18,
0x7E,
0x3C,
0x18,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x3C,
0x7E,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x7E,
0x3C,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x0C,
0xFE,
0x0C,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x30,
0x60,
0xFE,
0x60,
0x30,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC0,
0xC0,
0xC0,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x28,
0x6C,
0xFE,
0x6C,
0x28,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x38,
0x38,
0x7C,
0x7C,
0xFE,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0xFE,
0x7C,
0x7C,
0x38,
0x38,
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x3C,
0x3C,
0x3C,
0x18,
0x18,
0x18,
0x00,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x66,
0x66,
0x66,
0x24,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x6C,
0x6C,
0xFE,
0x6C,
0x6C,
0x6C,
0xFE,
0x6C,
0x6C,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x7C,
0xC6,
0xC2,
0xC0,
0x7C,
0x06,
0x06,
0x86,
0xC6,
0x7C,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC2,
0xC6,
0x0C,
0x18,
0x30,
0x60,
0xC6,
0x86,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x6C,
0x6C,
0x38,
0x76,
0xDC,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x30,
0x30,
0x30,
0x60,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0C,
0x18,
0x30,
0x30,
0x30,
0x30,
0x30,
0x30,
0x18,
0x0C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x30,
0x18,
0x0C,
0x0C,
0x0C,
0x0C,
0x0C,
0x0C,
0x18,
0x30,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x66,
0x3C,
0xFF,
0x3C,
0x66,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x7E,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x18,
0x30,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x02,
0x06,
0x0C,
0x18,
0x30,
0x60,
0xC0,
0x80,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x6C,
0xC6,
0xC6,
0xD6,
0xD6,
0xC6,
0xC6,
0x6C,
0x38,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x38,
0x78,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0x06,
0x0C,
0x18,
0x30,
0x60,
0xC0,
0xC6,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0x06,
0x06,
0x3C,
0x06,
0x06,
0x06,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0C,
0x1C,
0x3C,
0x6C,
0xCC,
0xFE,
0x0C,
0x0C,
0x0C,
0x1E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0xC0,
0xC0,
0xC0,
0xFC,
0x06,
0x06,
0x06,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x60,
0xC0,
0xC0,
0xFC,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0xC6,
0x06,
0x06,
0x0C,
0x18,
0x30,
0x30,
0x30,
0x30,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0x7E,
0x06,
0x06,
0x06,
0x0C,
0x78,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x00,
0x00,
0x00,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x00,
0x00,
0x00,
0x18,
0x18,
0x30,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x06,
0x0C,
0x18,
0x30,
0x60,
0x30,
0x18,
0x0C,
0x06,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7E,
0x00,
0x00,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x60,
0x30,
0x18,
0x0C,
0x06,
0x0C,
0x18,
0x30,
0x60,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0x0C,
0x18,
0x18,
0x18,
0x00,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0xDE,
0xDE,
0xDE,
0xDC,
0xC0,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x38,
0x6C,
0xC6,
0xC6,
0xFE,
0xC6,
0xC6,
0xC6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFC,
0x66,
0x66,
0x66,
0x7C,
0x66,
0x66,
0x66,
0x66,
0xFC,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x66,
0xC2,
0xC0,
0xC0,
0xC0,
0xC0,
0xC2,
0x66,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xF8,
0x6C,
0x66,
0x66,
0x66,
0x66,
0x66,
0x66,
0x6C,
0xF8,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0x66,
0x62,
0x68,
0x78,
0x68,
0x60,
0x62,
0x66,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0x66,
0x62,
0x68,
0x78,
0x68,
0x60,
0x60,
0x60,
0xF0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x66,
0xC2,
0xC0,
0xC0,
0xDE,
0xC6,
0xC6,
0x66,
0x3A,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xC6,
0xC6,
0xC6,
0xFE,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x1E,
0x0C,
0x0C,
0x0C,
0x0C,
0x0C,
0xCC,
0xCC,
0xCC,
0x78,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xE6,
0x66,
0x66,
0x6C,
0x78,
0x78,
0x6C,
0x66,
0x66,
0xE6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xF0,
0x60,
0x60,
0x60,
0x60,
0x60,
0x60,
0x62,
0x66,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xEE,
0xFE,
0xFE,
0xD6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xE6,
0xF6,
0xFE,
0xDE,
0xCE,
0xC6,
0xC6,
0xC6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFC,
0x66,
0x66,
0x66,
0x7C,
0x60,
0x60,
0x60,
0x60,
0xF0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xD6,
0xDE,
0x7C,
0x0C,
0x0E,
0x00,
0x00,
0x00,
0x00,
0xFC,
0x66,
0x66,
0x66,
0x7C,
0x6C,
0x66,
0x66,
0x66,
0xE6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0x60,
0x38,
0x0C,
0x06,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7E,
0x7E,
0x5A,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x6C,
0x38,
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xC6,
0xC6,
0xC6,
0xD6,
0xD6,
0xD6,
0xFE,
0xEE,
0x6C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xC6,
0x6C,
0x7C,
0x38,
0x38,
0x7C,
0x6C,
0xC6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x66,
0x66,
0x66,
0x66,
0x3C,
0x18,
0x18,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0xC6,
0x86,
0x0C,
0x18,
0x30,
0x60,
0xC2,
0xC6,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x30,
0x30,
0x30,
0x30,
0x30,
0x30,
0x30,
0x30,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x80,
0xC0,
0xE0,
0x70,
0x38,
0x1C,
0x0E,
0x06,
0x02,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x0C,
0x0C,
0x0C,
0x0C,
0x0C,
0x0C,
0x0C,
0x0C,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x10,
0x38,
0x6C,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0x00,
0x00,
0x00,
0x30,
0x18,
0x0C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x78,
0x0C,
0x7C,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xE0,
0x60,
0x60,
0x78,
0x6C,
0x66,
0x66,
0x66,
0x66,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC0,
0xC0,
0xC0,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x1C,
0x0C,
0x0C,
0x3C,
0x6C,
0xCC,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xFE,
0xC0,
0xC0,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x1C,
0x36,
0x32,
0x30,
0x78,
0x30,
0x30,
0x30,
0x30,
0x78,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x76,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0x7C,
0x0C,
0xCC,
0x78,
0x00,
0x00,
0x00,
0xE0,
0x60,
0x60,
0x6C,
0x76,
0x66,
0x66,
0x66,
0x66,
0xE6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x00,
0x38,
0x18,
0x18,
0x18,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x06,
0x06,
0x00,
0x0E,
0x06,
0x06,
0x06,
0x06,
0x06,
0x06,
0x66,
0x66,
0x3C,
0x00,
0x00,
0x00,
0xE0,
0x60,
0x60,
0x66,
0x6C,
0x78,
0x78,
0x6C,
0x66,
0xE6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xEC,
0xFE,
0xD6,
0xD6,
0xD6,
0xD6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xDC,
0x66,
0x66,
0x66,
0x66,
0x66,
0x66,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xDC,
0x66,
0x66,
0x66,
0x66,
0x66,
0x7C,
0x60,
0x60,
0xF0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x76,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0x7C,
0x0C,
0x0C,
0x1E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xDC,
0x76,
0x66,
0x60,
0x60,
0x60,
0xF0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0x60,
0x38,
0x0C,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x30,
0x30,
0xFC,
0x30,
0x30,
0x30,
0x30,
0x36,
0x1C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x6C,
0x38,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xC6,
0xD6,
0xD6,
0xD6,
0xFE,
0x6C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0x6C,
0x38,
0x38,
0x38,
0x6C,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7E,
0x06,
0x0C,
0xF8,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0xCC,
0x18,
0x30,
0x60,
0xC6,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0E,
0x18,
0x18,
0x18,
0x70,
0x18,
0x18,
0x18,
0x18,
0x0E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x70,
0x18,
0x18,
0x18,
0x0E,
0x18,
0x18,
0x18,
0x18,
0x70,
0x00,
0x00,
0x00,
0x00,
0x00,
0x76,
0xDC,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x38,
0x6C,
0xC6,
0xC6,
0xC6,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x66,
0xC2,
0xC0,
0xC0,
0xC0,
0xC0,
0xC2,
0x66,
0x3C,
0x18,
0x70,
0x00,
0x00,
0x00,
0x00,
0xCC,
0x00,
0x00,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0C,
0x18,
0x30,
0x00,
0x7C,
0xC6,
0xFE,
0xC0,
0xC0,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x38,
0x6C,
0x00,
0x78,
0x0C,
0x7C,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xCC,
0x00,
0x00,
0x78,
0x0C,
0x7C,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x60,
0x30,
0x18,
0x00,
0x78,
0x0C,
0x7C,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x6C,
0x38,
0x00,
0x78,
0x0C,
0x7C,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC0,
0xC0,
0xC0,
0xC6,
0x7C,
0x18,
0x70,
0x00,
0x00,
0x00,
0x10,
0x38,
0x6C,
0x00,
0x7C,
0xC6,
0xFE,
0xC0,
0xC0,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0x00,
0x00,
0x7C,
0xC6,
0xFE,
0xC0,
0xC0,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x60,
0x30,
0x18,
0x00,
0x7C,
0xC6,
0xFE,
0xC0,
0xC0,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x66,
0x00,
0x00,
0x38,
0x18,
0x18,
0x18,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x3C,
0x66,
0x00,
0x38,
0x18,
0x18,
0x18,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x60,
0x30,
0x18,
0x00,
0x38,
0x18,
0x18,
0x18,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0x00,
0x10,
0x38,
0x6C,
0xC6,
0xC6,
0xFE,
0xC6,
0xC6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x38,
0x6C,
0x38,
0x10,
0x38,
0x6C,
0xC6,
0xFE,
0xC6,
0xC6,
0xC6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x0C,
0x18,
0x00,
0xFE,
0x66,
0x62,
0x68,
0x78,
0x68,
0x62,
0x66,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xEC,
0x36,
0x36,
0x7E,
0xD8,
0xD8,
0x6E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3E,
0x6C,
0xCC,
0xCC,
0xFE,
0xCC,
0xCC,
0xCC,
0xCC,
0xCE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x38,
0x6C,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x60,
0x30,
0x18,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x30,
0x78,
0xCC,
0x00,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x60,
0x30,
0x18,
0x00,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0x00,
0x00,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7E,
0x06,
0x0C,
0x78,
0x00,
0x00,
0xC6,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0xC6,
0x00,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x7C,
0xC6,
0xC0,
0xC0,
0xC0,
0xC6,
0x7C,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x6C,
0x64,
0x60,
0xF0,
0x60,
0x60,
0x60,
0x60,
0xE6,
0xFC,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x66,
0x66,
0x3C,
0x18,
0x7E,
0x18,
0x7E,
0x18,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0xF8,
0xCC,
0xCC,
0xF8,
0xC4,
0xCC,
0xDE,
0xCC,
0xCC,
0xCC,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0E,
0x1B,
0x18,
0x18,
0x18,
0x7E,
0x18,
0x18,
0x18,
0xD8,
0x70,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x30,
0x60,
0x00,
0x78,
0x0C,
0x7C,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0C,
0x18,
0x30,
0x00,
0x38,
0x18,
0x18,
0x18,
0x18,
0x18,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x30,
0x60,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x30,
0x60,
0x00,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0xCC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x76,
0xDC,
0x00,
0xDC,
0x66,
0x66,
0x66,
0x66,
0x66,
0x66,
0x00,
0x00,
0x00,
0x00,
0x76,
0xDC,
0x00,
0xC6,
0xE6,
0xF6,
0xFE,
0xDE,
0xCE,
0xC6,
0xC6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x6C,
0x6C,
0x3E,
0x00,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x6C,
0x6C,
0x38,
0x00,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x30,
0x30,
0x00,
0x30,
0x30,
0x60,
0xC0,
0xC6,
0xC6,
0x7C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0xC0,
0xC0,
0xC0,
0xC0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0x06,
0x06,
0x06,
0x06,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x60,
0xE0,
0x62,
0x66,
0x6C,
0x18,
0x30,
0x60,
0xDC,
0x86,
0x0C,
0x18,
0x3E,
0x00,
0x00,
0x00,
0x60,
0xE0,
0x62,
0x66,
0x6C,
0x18,
0x30,
0x66,
0xCE,
0x9A,
0x3F,
0x06,
0x06,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x00,
0x18,
0x18,
0x18,
0x3C,
0x3C,
0x3C,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x36,
0x6C,
0xD8,
0x6C,
0x36,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xD8,
0x6C,
0x36,
0x6C,
0xD8,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x11,
0x44,
0x11,
0x44,
0x11,
0x44,
0x11,
0x44,
0x11,
0x44,
0x11,
0x44,
0x11,
0x44,
0x11,
0x44,
0x55,
0xAA,
0x55,
0xAA,
0x55,
0xAA,
0x55,
0xAA,
0x55,
0xAA,
0x55,
0xAA,
0x55,
0xAA,
0x55,
0xAA,
0xDD,
0x77,
0xDD,
0x77,
0xDD,
0x77,
0xDD,
0x77,
0xDD,
0x77,
0xDD,
0x77,
0xDD,
0x77,
0xDD,
0x77,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0xF8,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0xF8,
0x18,
0xF8,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0xF6,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x00,
0x00,
0x00,
0x00,
0x00,
0xF8,
0x18,
0xF8,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x36,
0x36,
0x36,
0x36,
0x36,
0xF6,
0x06,
0xF6,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0x06,
0xF6,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0xF6,
0x06,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x18,
0x18,
0x18,
0xF8,
0x18,
0xF8,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xF8,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x1F,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x1F,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0xFF,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x1F,
0x18,
0x1F,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x37,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x37,
0x30,
0x3F,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3F,
0x30,
0x37,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0xF7,
0x00,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0x00,
0xF7,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x37,
0x30,
0x37,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0x00,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x36,
0x36,
0x36,
0x36,
0x36,
0xF7,
0x00,
0xF7,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x18,
0x18,
0x18,
0x18,
0x18,
0xFF,
0x00,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0x00,
0xFF,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x3F,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x18,
0x18,
0x18,
0x1F,
0x18,
0x1F,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x1F,
0x18,
0x1F,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3F,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0xFF,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x36,
0x18,
0x18,
0x18,
0x18,
0x18,
0xFF,
0x18,
0xFF,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0xF8,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x1F,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x76,
0xDC,
0xD8,
0xD8,
0xD8,
0xDC,
0x76,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x78,
0xCC,
0xCC,
0xCC,
0xD8,
0xCC,
0xC6,
0xC6,
0xC6,
0xCC,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0xC6,
0xC6,
0xC0,
0xC0,
0xC0,
0xC0,
0xC0,
0xC0,
0xC0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0x6C,
0x6C,
0x6C,
0x6C,
0x6C,
0x6C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0xC6,
0x60,
0x30,
0x18,
0x18,
0x30,
0x60,
0xC6,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7E,
0xD8,
0xD8,
0xD8,
0xD8,
0xD8,
0x70,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x66,
0x66,
0x66,
0x66,
0x66,
0x66,
0x7C,
0x60,
0x60,
0xC0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x76,
0xDC,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7E,
0x18,
0x3C,
0x66,
0x66,
0x66,
0x66,
0x3C,
0x18,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x6C,
0xC6,
0xC6,
0xFE,
0xC6,
0xC6,
0xC6,
0x6C,
0x38,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x6C,
0xC6,
0xC6,
0xC6,
0x6C,
0x6C,
0x6C,
0x6C,
0xEE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x1E,
0x30,
0x18,
0x0C,
0x3E,
0x66,
0x66,
0x66,
0x66,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7E,
0xDB,
0xDB,
0xDB,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x03,
0x06,
0x7E,
0xDB,
0xDB,
0xF3,
0x7E,
0x60,
0xC0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x1C,
0x30,
0x60,
0x60,
0x7C,
0x60,
0x60,
0x60,
0x30,
0x1C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7C,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0xC6,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFE,
0x00,
0x00,
0xFE,
0x00,
0x00,
0xFE,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x7E,
0x18,
0x18,
0x00,
0x00,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x30,
0x18,
0x0C,
0x06,
0x0C,
0x18,
0x30,
0x00,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0C,
0x18,
0x30,
0x60,
0x30,
0x18,
0x0C,
0x00,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0E,
0x1B,
0x1B,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0x18,
0xD8,
0xD8,
0xD8,
0x70,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x00,
0x7E,
0x00,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x76,
0xDC,
0x00,
0x76,
0xDC,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x38,
0x6C,
0x6C,
0x38,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0F,
0x0C,
0x0C,
0x0C,
0x0C,
0x0C,
0xEC,
0x6C,
0x6C,
0x3C,
0x1C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x6C,
0x36,
0x36,
0x36,
0x36,
0x36,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C,
0x66,
0x0C,
0x18,
0x32,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7E,
0x7E,
0x7E,
0x7E,
0x7E,
0x7E,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
};
int vgafnt_size = 4096;
|
the_stack_data/583072.c | #include <stdio.h>
void swap(int *s1, int *s2);
void transpose_2d(int *arr, int len);
void stat_2d(int *arr, int len);
int main(void)
{
int arr[5][5] = {
{1,2,3,4,5},
{6,7,8,9,0},
{1,2,3,4,5},
{6,7,8,9,0},
{1,2,3,4,5}
};
stat_2d((int *)arr, 5);
transpose_2d((int *)arr, 5);
printf("\n");
stat_2d((int *)arr, 5);
return (0);
}
|
the_stack_data/124390.c | /* from gcc manual, extension not supported by -stc=c99 */
int foo asm ("myfoo") = 2;
|
the_stack_data/162642390.c | /* watch -- execute a program repeatedly, displaying output fullscreen
*
* Based on the original 1991 'watch' by Tony Rems <[email protected]>
* (with mods and corrections by Francois Pinard).
*
* Substantially reworked, new features (differences option, SIGWINCH
* handling, unlimited command length, long line handling) added Apr 1999 by
* Mike Coleman <[email protected]>.
*
* Changes by Albert Cahalan, 2002-2003.
*/
#define VERSION "0.2.0"
#include <ctype.h>
#include <getopt.h>
#include <signal.h>
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#include <locale.h>
/* #include "proc/procps.h" */
static struct option longopts[] = {
{"differences", optional_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{"interval", required_argument, 0, 'n'},
{"no-title", no_argument, 0, 't'},
{"version", no_argument, 0, 'v'},
{0, 0, 0, 0}
};
static char usage[] =
"Usage: %s [-dhntv] [--differences[=cumulative]] [--help] [--interval=<n>] [--no-title] [--version] <command>\n";
static char *progname;
static int curses_started = 0;
static int height = 24, width = 80;
static int screen_size_changed = 0;
static int first_screen = 1;
static int show_title = 2; // number of lines used, 2 or 0
#define min(x,y) ((x) > (y) ? (y) : (x))
//static void do_usage(void) NORETURN;
static void do_usage(void)
{
fprintf(stderr, usage, progname);
exit(1);
}
//static void do_exit(int status) NORETURN;
static void do_exit(int status)
{
if (curses_started)
endwin();
exit(status);
}
/* signal handler */
//static void die(int notused) NORETURN;
static void die(int notused)
{
(void) notused;
do_exit(0);
}
static void
winch_handler(int notused)
{
(void) notused;
screen_size_changed = 1;
}
static void
get_terminal_size(void)
{
struct winsize w;
if (ioctl(2, TIOCGWINSZ, &w) == 0) {
if (w.ws_row > 0)
height = w.ws_row;
if (w.ws_col > 0)
width = w.ws_col;
}
}
int
main(int argc, char *argv[])
{
int optc;
int option_differences = 0,
option_differences_cumulative = 0,
option_help = 0, option_version = 0;
int interval = 2;
char *command;
int command_length = 0; /* not including final \0 */
setlocale(LC_ALL, "");
progname = argv[0];
while ((optc = getopt_long(argc, argv, "+d::hn:vt", longopts, (int *) 0))
!= EOF) {
switch (optc) {
case 'd':
option_differences = 1;
if (optarg)
option_differences_cumulative = 1;
break;
case 'h':
option_help = 1;
break;
case 't':
show_title = 0;
break;
case 'n':
{
char *str;
interval = strtol(optarg, &str, 10);
if (!*optarg || *str)
do_usage();
}
break;
case 'v':
option_version = 1;
break;
default:
do_usage();
break;
}
}
if (option_version) {
fprintf(stderr, "%s\n", VERSION);
if (!option_help)
exit(0);
}
if (option_help) {
fprintf(stderr, usage, progname);
fputs(" -d, --differences[=cumulative]\thighlight changes between updates\n", stderr);
fputs("\t\t(cumulative means highlighting is cumulative)\n", stderr);
fputs(" -h, --help\t\t\t\tprint a summary of the options\n", stderr);
fputs(" -n, --interval=<seconds>\t\tseconds to wait between updates\n", stderr);
fputs(" -v, --version\t\t\t\tprint the version number\n", stderr);
fputs(" -t, --no-title\t\t\tturns off showing the header\n", stderr);
exit(0);
}
if (optind >= argc)
do_usage();
command = strdup(argv[optind++]);
command_length = strlen(command);
for (; optind < argc; optind++) {
char *endp;
int s = strlen(argv[optind]);
command = realloc(command, command_length + s + 2); /* space and \0 */
endp = command + command_length;
*endp = ' ';
memcpy(endp + 1, argv[optind], s);
command_length += 1 + s; /* space then string length */
command[command_length] = '\0';
}
get_terminal_size();
/* Catch keyboard interrupts so we can put tty back in a sane state. */
signal(SIGINT, die);
signal(SIGTERM, die);
signal(SIGHUP, die);
signal(SIGWINCH, winch_handler);
/* Set up tty for curses use. */
curses_started = 1;
initscr();
nonl();
noecho();
cbreak();
for (;;) {
time_t t = time(NULL);
char *ts = ctime(&t);
int tsl = strlen(ts);
char *header;
FILE *p;
int x, y;
int oldeolseen = 1;
if (screen_size_changed) {
get_terminal_size();
resizeterm(height, width);
clear();
/* redrawwin(stdscr); */
screen_size_changed = 0;
first_screen = 1;
}
if (show_title) {
// left justify interval and command,
// right justify time, clipping all to fit window width
asprintf(&header, "Every %ds: %.*s",
interval, min(width - 1, command_length), command);
mvaddstr(0, 0, header);
if (strlen(header) > (size_t) (width - tsl - 1))
mvaddstr(0, width - tsl - 4, "... ");
mvaddstr(0, width - tsl + 1, ts);
free(header);
}
if (!(p = popen(command, "r"))) {
perror("popen");
do_exit(2);
}
for (y = show_title; y < height; y++) {
int eolseen = 0, tabpending = 0;
for (x = 0; x < width; x++) {
int c = ' ';
int attr = 0;
if (!eolseen) {
/* if there is a tab pending, just spit spaces until the
next stop instead of reading characters */
if (!tabpending)
do
c = getc(p);
while (c != EOF && !isprint(c)
&& c != '\n'
&& c != '\t');
if (c == '\n')
if (!oldeolseen && x == 0) {
x = -1;
continue;
} else
eolseen = 1;
else if (c == '\t')
tabpending = 1;
if (c == EOF || c == '\n' || c == '\t')
c = ' ';
if (tabpending && (((x + 1) % 8) == 0))
tabpending = 0;
}
move(y, x);
if (option_differences) {
int oldch = inch();
char oldc = oldch & A_CHARTEXT;
attr = !first_screen
&& (c != oldc
||
(option_differences_cumulative
&& (oldch & A_ATTRIBUTES)));
}
if (attr)
standout();
addch(c);
if (attr)
standend();
}
oldeolseen = eolseen;
}
pclose(p);
first_screen = 0;
refresh();
sleep(interval);
}
endwin();
return 0;
}
|
the_stack_data/12638997.c | #include <stdio.h>
long long int fibo (long long int n){
if(n==0)
return 0;
else if(n==1)
return 1;
else
return fibo(n-1) + fibo(n-2);
}
int main () {
long long int n, total;
scanf ("%lld", &n);
total = fibo(n);
printf ("%d\n", total);
return 0;
}
|
the_stack_data/192330074.c | #include <stdio.h>
//将数字逆序
//通过%运算,将最低位数字取出
//通过/运算,将最低位数字剔除
//反复进行,拿到每一位数字
int main()
{
int x = 700;
// scanf("%d", &x);
int ret = 0;
while (x > 0)
{
//下面有两种结果
//打开1,关闭2:得到的结果是007。但结果不是int型
//打开2, 关闭1:得到的结果是7。结果是int型
int digit = x % 10;
//1
printf("%d", digit);
ret = ret * 10 + digit;
//2
//printf("x = %d, digit = %d, ret = %d\n", x, digit, ret);
x /= 10;
}
//2
//printf("%d", ret);
return 0;
} |
the_stack_data/54824877.c | /* printfact2.c */
/*
Fitzpatrick. Computational Physics. 329.pdf
2.9 Functions
Programming note from Fitzpatrick. pp.50
"Ideally, function definitions should always precede the corresponding function
calls in a C program.
Unfortunately, for the sake of logical clarity, most C programmers prefer to place
the main() function at the beginning of their programs.
...compilation errors can be avoided by using a construct known
as a function prototype"
*/
/*
Program to print factorials of all integers
between 0 and 20
*/
#include <stdio.h>
#include <stdlib.h>
/* Prototype for function factorial() */
double factorial(int);
int main()
{
int j;
/* Print factorials of all integers between 0 and 20 */
for (j = 0; j <= 20; ++j)
printf("j = %3d factorial(j) = %12.3e\n", j, factorial(j));
return 0;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double factorial(int n)
{
/*
Function to evaluate factorial (in floating-point form)
of non-negative integer n.
*/
int count;
double fact = 1.;
/* Abort if n is negative integer */
if (n < 0)
{
printf("\nError: factorial of negative integer not defined\n");
exit(1);
}
/* Calculate factorial */
for (; n > 0; --n) fact *= (double) count;
/* Return value of factorial */
return fact;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Programming note pp. 51 2.9 Functions 2 Scientific Programming in C
// When a single value is passed to a function as an argument then the
// value of that argument is simply copied to the function.
// Thus, argument's value can subsequently be altered within the function
// but this will not affect its value in the calling routine
// -> passing by value
|
the_stack_data/34512316.c | /* C Primer Plus Ch.2 - Problem 7 */
#include <stdio.h>
void one_three();
void two();
int main(void){
printf("starting now:\n");
one_three();
printf("done!\n");
return 0;
}
void one_three(){
printf("one\n");
two();
printf("three\n");
}
void two(){
printf("two\n");
}
|
the_stack_data/89201260.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* add_prime_sum.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: exam <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/14 12:33:14 by evgenkarlson #+# #+# */
/* Updated: 2020/02/15 10:51:23 by evgenkarlson ### ########.fr */
/* */
/* ************************************************************************** */
/* ************************************************************************** */
/* ************************************************************************** */
/* **************************************************************************
Assignment name : add_prime_sum
Expected files : add_prime_sum.c
Allowed functions: write, exit
--------------------------------------------------------------------------------
Напишите программу, которая принимает в качестве аргумента положительное целое число и отображает сумму всех простых чисел, меньших или равных ей, за которыми следует новая строка.
Если количество аргументов не равно 1 или аргумент не является положительным числом, просто отобразите 0, а затем новую строку.
Да, примеры верны.
Примеры:
$>./add_prime_sum 5
10
$>./add_prime_sum 7 | cat -e
17$
$>./add_prime_sum | cat -e
0$
$>
/* ************************************************************************** */
/* ************************************************************************** */
/* ************************************************************************** */
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
int ft_atoi(char *str) /* Принимаем адрес массива символов */
{
int i; /* обьявляем переменную для вычисления позиции ячейки массива от начала к концу */
int negativ; /* обьявляем переменную для хранения информации от знаке числа */
int number; /* обьявляем переменную для хранения самого числа полученного из строки */
i = 0; /* Инициализируем перменную чтобы начать просмотр массива с 0 позиции */
negativ = 0; /* Инициализируем перменную нулем предположив что число положителное */
number = 0; /* Инициализируем перменную нулем для прибавления в нее добытого числа*/
/* проверим не лежат ли в этой ячейке массива ненужные символы если они там лежат то пропустим их
* и перейдем к след позиции */
while ((str[i] == ' ') || (str[i] == '\t') || (str[i] == '\n')
|| (str[i] == '\v') || (str[i] == '\f') || (str[i] == '\r'))
i++;
/* проверим лежит ли в след ячейке массива знака числа, символ'-'
* если он там то в переменной negativ указываем то что это число
* отрицательное и переходим к след позиции*/
if (str[i] == '-')
negativ = 1;
if ((str[i] == '-') || (str[i] == '+'))
i++;
/* Наконец дойдя до места в массиве где начинается число мы можем его вывести его от туда
* и сохранить в целочисленную переменную number */
/* ВОТ ТАК */
while (str[i] >= '0' && str[i] <= '9')
{
number *= 10; /* умножая на 10 мы освобождаем место для след цифры */
number += ((int)str[i] - 48); /* туда где появился 0 прибавляем число которое мы вытащили из строки */
i++; /* и переходим к след позиции*/
}
/* Дальше перед тем как вернуть число которе мы добыли из строки
* нужно установить для него тот знак который мы нашли */
if (negativ == 1) /* Проверяем, узнали ли мы что число отрицательное */
return (-number); /* если число трицательное добавим к нему минус */
else
return (number); /* если чило положительное возвращаем как есть */
}
void ft_putnbr(int nb) /* Функция вывода числа */
{
int temp; /* создадим переменню для временного хранения данных в нее будем сохранять переменную nb */
int size; /* создадим переменню для хранения размера числа*/
size = 1; /* Установим ей начальный размер */
if (nb < 0) /* Проверяем яляется полученное нами число в nb отрицательным если число отрицательное то в начале выведем этот '-' символ. */
{ /* а содержимое переменной nb делаем положительным с помощью хитрости( nb = -nb) помня из математики что минус на минус дает плюс */
ft_putchar('-');
nb = -nb;
}
if (nb == -2147483648)
{
ft_putchar('2');
nb = 147483648;
}
temp = nb; /* сохраним в переменную temp наше число nb для вычисления размера этого числа */
while ((temp /= 10) > 0) /* Вычисляем размер числа c помощью накопления количества умноженых десяток друг на друга*/
size *= 10; /* Если результ деления нашего числа в temp на 10 больше нуля то увеличиваем переменную size умножив ее содержимое на 10 */
/* НУЖО ПОМНИТЬ что при делении целого числа на целое результат сохраняемый в переменной типа int будет без плавающей точки.
она автоматически отбрасывается */ /* ПРимер: делим 4 на 10 в итоге результат будет 0.4 а вот сохраниться в переменной
типа int только 0 по тому что все после точки отбрасывается и не записывается в целочисленную переменную. */
temp = nb; /* восстановим расстерзаноеделением число в переменную temp оно нам снова понадобится
для того чтобы отделить цифры нужного нам числа и напечатать по отдельности */
while (size) /* проверяем длинну числа если длинна еще не равна нулю (в результате уменьшения на 10 в цикле) то продолжаем работу цикла */
{
ft_putchar((char)((temp / size)) + 48); /* делим число на размер, который у нас получился */ /* тут тоже хитрость */
/* допустим размер полученогонами числа 345 получисля равным 100 */
/* деля 345 на 100 мы получим 3.45*/ /* 0.45 отбрасывается по тому что идет приведение к целому числу */ /* и остаеться 3 */
/* Так вот мы и отделяем 3 от 45 и уже можем ее напечатать тройку прибавив к ней 48, чтоб полуить код символа '3' */
temp %= size; /* Здесь с помощь деления числа temp (в примере у нас это 345) по модулю на size (в примере у нас это 100) мы получим
оставшуюся часть без первого символа temp ( т.е у нас получится 45. Тройка канула в лету. Так мы ее отбрасываем чтоб потом,
на новой итерации цикла напечатать 4 и 5 и т.д по мере отделения и печати чисел, и помере того как size уменьшается */
size /= 10; /* после то как отделили 3 от 45 в числе 345 и после того как оставили себе только 45 для дальнейшего отделения. число 100 нам больше не нужно.
Так что делим size на 10 чтобы в след итерации число 45 уже делилось на 10 отдавая 4 на печать, и еще 45 делилось по модулю на 10 сохраняя 5
на следующую итерацию, потом снова уменьшение size на 10 (чтобы можно было работать с temp, которое теперь уже хранит 5).
Теперь 5 делм на 1 получаем пять отдаем его на печать, 5 деленное по модулю на 1 сохраняет в переменную 0 но это нам уже не нужно.
Потому что дальше size делится на 10 снова и размер size становится равным нулю. А при след итерации цикл будет проверять размер size
и если он равен 0 то цикл завершается */
/* И жили они долго и счастливо, конец */
}
}
int is_prime(int nb)
{
int i;
i = 2;
if (nb <= 1)
return (0);
while (i <= (nb / 2))
{
if (!(nb % i))
return (0);
else
i++;
}
return (1);
}
int main(int argc, char *argv[])
{
int nb;
int sum;
if (argc == 2)
{
nb = ft_atoi(argv[1]);
sum = 0;
while (nb > 0)
if (is_prime(nb--))
sum += (nb + 1);
ft_putnbr(sum);
}
ft_putchar('\n');
return (0);
}
|
the_stack_data/821216.c | /*Fazer uma rotina que recebe um array do tipo double e o número de valores
que devem ser solicitados ao usuário e devolve o array preenchido com os
valores digitados.
*/
#include <stdio.h>
#include <stdlib.h>
void put_array(double *notes,int size);
void print_v(double *notes,int size);
int main()
{
int size = 10;
double notes[size];
printf("Dijite numeros\n");
put_array(notes,size);
print_v(notes,size);
}
void put_array(double *notes,int size)
{
int i;
for(i = 0;i < size; i++){
scanf("%lf", ¬es[i]);
printf("proximo\n");
}
}
void print_v(double *notes,int size){
int i=0;
for(i = 0;i < size; i++){
printf("os valores dijitados são: \n");
printf("%lf\n", notes[i]);
}
}
|
the_stack_data/200143195.c |
#ifdef MBED_CLOUD_CLIENT_USER_CONFIG_FILE
#include MBED_CLOUD_CLIENT_USER_CONFIG_FILE
#endif
#include <stdint.h>
#ifdef MBED_CLOUD_DEV_UPDATE_ID
const uint8_t arm_uc_vendor_id[] = {
0x74, 0x83, 0x1c, 0x15, 0x7d, 0x6a, 0x59, 0x20, 0xa1, 0x26, 0x6d, 0xc2, 0xc0, 0x4b, 0x37, 0xea
};
const uint16_t arm_uc_vendor_id_size = sizeof(arm_uc_vendor_id);
const uint8_t arm_uc_class_id[] = {
0x46, 0x18, 0x17, 0x1a, 0x00, 0x22, 0x5d, 0x2d, 0x83, 0x15, 0xa5, 0xd1, 0xe8, 0x2d, 0x28, 0x11
};
const uint16_t arm_uc_class_id_size = sizeof(arm_uc_class_id);
#endif
#ifdef MBED_CLOUD_DEV_UPDATE_CERT
const uint8_t arm_uc_default_fingerprint[] = {
0xc5, 0x59, 0xa0, 0x3a, 0x02, 0x14, 0xb7, 0x22, 0xf3, 0x73, 0xfc, 0x7f, 0xe5, 0x7b, 0x98, 0x39,
0x8a, 0x65, 0x7f, 0xa5, 0xba, 0x29, 0x68, 0x77, 0x2a, 0x32, 0x53, 0x84, 0xcc, 0xfd, 0xad, 0x17
};
const uint16_t arm_uc_default_fingerprint_size =
sizeof(arm_uc_default_fingerprint);
const uint8_t arm_uc_default_subject_key_identifier[] = {
};
const uint16_t arm_uc_default_subject_key_identifier_size =
sizeof(arm_uc_default_subject_key_identifier);
const uint8_t arm_uc_default_certificate[] = {
0x30, 0x82, 0x01, 0x4c, 0x30, 0x81, 0xf4, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x14, 0xbc, 0x05,
0x57, 0x63, 0xbd, 0x62, 0x66, 0xfc, 0x55, 0x62, 0x93, 0x09, 0x25, 0x2d, 0xf6, 0xe6, 0xc2, 0xf0,
0xc1, 0x25, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x14,
0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c,
0x68, 0x6f, 0x73, 0x74, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x31, 0x31, 0x30, 0x30, 0x35, 0x30, 0x31,
0x34, 0x36, 0x34, 0x35, 0x5a, 0x17, 0x0d, 0x32, 0x32, 0x31, 0x30, 0x30, 0x34, 0x31, 0x36, 0x30,
0x30, 0x30, 0x30, 0x5a, 0x30, 0x14, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c,
0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07,
0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01,
0x07, 0x03, 0x42, 0x00, 0x04, 0x32, 0x72, 0xf1, 0x46, 0x92, 0xb0, 0x63, 0x0f, 0x21, 0x3c, 0x75,
0x73, 0x24, 0xc6, 0x3f, 0xf7, 0x15, 0x57, 0x7a, 0x38, 0x12, 0x2c, 0x29, 0x10, 0x50, 0xe1, 0x2d,
0xb4, 0x76, 0x7b, 0x12, 0x5b, 0x9f, 0x19, 0xfa, 0x09, 0xa9, 0xfd, 0x20, 0x79, 0x39, 0xc7, 0xa3,
0x00, 0xbb, 0xd9, 0x5d, 0xc4, 0x3c, 0x78, 0xd8, 0x67, 0x9c, 0x7c, 0x9a, 0x0b, 0x56, 0x74, 0xdf,
0xbb, 0xdd, 0xac, 0xef, 0x80, 0xa3, 0x24, 0x30, 0x22, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f,
0x04, 0x04, 0x03, 0x02, 0x07, 0x80, 0x30, 0x13, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x0c, 0x30,
0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x03, 0x30, 0x0a, 0x06, 0x08, 0x2a,
0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x47, 0x00, 0x30, 0x44, 0x02, 0x20, 0x25, 0xd4,
0x70, 0x2d, 0xc6, 0x24, 0x2d, 0xba, 0x9c, 0x70, 0xd0, 0x66, 0xa2, 0x0c, 0x46, 0x34, 0x2d, 0x73,
0x99, 0x2c, 0xb0, 0xfc, 0x18, 0x78, 0x58, 0xd3, 0x16, 0x2e, 0x48, 0x8c, 0x9e, 0x31, 0x02, 0x20,
0x61, 0xc6, 0x92, 0xc6, 0x70, 0x2d, 0x83, 0x6a, 0x21, 0xe1, 0xbf, 0xa9, 0x47, 0xc3, 0x02, 0x72,
0xd8, 0x4f, 0xdb, 0xf3, 0xff, 0xf7, 0x6a, 0xf6, 0x16, 0xbf, 0x79, 0x4f, 0xe8, 0x47, 0x01, 0x67
};
const uint16_t arm_uc_default_certificate_size = sizeof(arm_uc_default_certificate);
#endif
#ifdef MBED_CLOUD_DEV_UPDATE_PSK
const uint8_t arm_uc_default_psk[] = {
};
const uint8_t arm_uc_default_psk_size = sizeof(arm_uc_default_psk);
const uint16_t arm_uc_default_psk_bits = sizeof(arm_uc_default_psk)*8;
const uint8_t arm_uc_default_psk_id[] = {
};
const uint8_t arm_uc_default_psk_id_size = sizeof(arm_uc_default_psk_id);
#endif
|
the_stack_data/26699467.c | /**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#include <fenv.h>
#if !(defined(_ARM_) || defined(__arm__) || defined(_ARM64_) || defined(__aarch64__))
extern int __mingw_has_sse (void);
#endif /* !(defined(_ARM_) || defined(__arm__) || defined(_ARM64_) || defined(__aarch64__)) */
/* 7.6.2.2
The fegetexceptflag function stores an implementation-defined
representation of the exception flags indicated by the argument
excepts in the object pointed to by the argument flagp. */
int fegetexceptflag (fexcept_t * flagp, int excepts)
{
#if defined(_ARM_) || defined(__arm__)
fenv_t _env;
__asm__ volatile ("fmrx %0, FPSCR" : "=r" (_env));
*flagp = _env.__cw & excepts & FE_ALL_EXCEPT;
#elif defined(_ARM64_) || defined(__aarch64__)
unsigned __int64 fpcr;
__asm__ volatile ("mrs %0, fpcr" : "=r" (fpcr));
*flagp = fpcr & excepts & FE_ALL_EXCEPT;
#else
int _mxcsr;
unsigned short _status;
__asm__ volatile ("fnstsw %0" : "=am" (_status));
_mxcsr = 0;
if (__mingw_has_sse ())
__asm__ volatile ("stmxcsr %0" : "=m" (_mxcsr));
*flagp = (_mxcsr | _status) & excepts & FE_ALL_EXCEPT;
#endif /* defined(_ARM_) || defined(__arm__) || defined(_ARM64_) || defined(__aarch64__) */
return 0;
}
|
the_stack_data/176704947.c | #include <stdio.h>
#include <stdlib.h>
#define PAGE_SIZE 512;
#define FREAK() printf("wow.")
typedef struct b_data_t {
int node_boot_start;
int node_low_pfn;
} bootmem_data_t;
typedef struct pg_d_t {
struct b_data_t* bdata;
} pg_data_t;
static void free_bootmem_core(bootmem_data_t *bdata, unsigned long addr, unsigned long size) {
unsigned long i;
unsigned long start;
unsigned long sidx;
unsigned long eidx, end;
eidx = (addr + size - bdata->node_boot_start)/PAGE_SIZE;
end = (addr + size)/PAGE_SIZE;
if (!size) FREAK();
if (end > bdata->node_low_pfn)
FREAK();
}
void free_bootmem_node(pg_data_t *pgdat, unsigned long physaddr, unsigned long size) {
return(free_bootmem_core(pgdat->bdata, physaddr, size));
}
int main(int charc, char ** argv) {
return 0;
}
|
the_stack_data/135142.c | /* Copyright (c) 1985-2012, B-Core (UK) Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
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.
*/
INI_Scalar_TYPE()
{
}
|
the_stack_data/112604.c | /*
Program test how C stdlib handles directories opened
with function fopen.
Compilation:
$ gcc -Wall fopen_directory.c -o your_favorite_name
Usage:
$ ./your_favorite_name directory_path
Author : Wojciech Muła
Date : 2013-12-25
License : public domain
*/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h> // for strerror
void fopen_directory(const char* path);
void print_errno(const char* prefix);
int main(int argc, char* argv[]) {
int i;
if (argc > 1) {
for (i=1; i < argc; i++)
fopen_directory(argv[i]);
return EXIT_SUCCESS;
} else {
printf("usage: %s directory\n", argv[0]);
return EXIT_FAILURE;
}
}
void fopen_directory(const char* path) {
FILE* f;
printf("testing '%s'...\n", path);
print_errno("fopen");
f = fopen(path, "rb");
if (f == NULL) {
return;
}
int seek_res = fseek(f, 0, SEEK_END);
print_errno("fseek");
printf("fseek result: %d\n", seek_res);
long tell_res = ftell(f);
print_errno("ftell");
printf("ftell result: %ld\n", tell_res);
int feof_res = feof(f);
print_errno("feof");
printf("feof result: %d (EOF=%s)\n", feof_res, feof_res == EOF ? "yes" : "no");
int fgetc_res = fgetc(f);
print_errno("fgetc");
printf("fgetc result: %d (EOF=%s)\n", fgetc_res, fgetc_res == EOF ? "yes" : "no");
char fread_buffer[1024];
int fread_result = fread(fread_buffer, 1024, 1, f);
print_errno("fread");
printf("fread result: %d\n", fread_result);
}
void print_errno(const char* prefix) {
printf("%s: %s [errno=%d]\n", prefix, strerror(errno), errno);
}
|
the_stack_data/103266660.c | #include<stdio.h>
int main()
{
//Q9.WAP input a no find out reverse of that no.
int a=0,rev=0;
printf("Enter a number: ");
scanf("%d",&a);
while(a>0)
{
rev = (rev*10)+(a%10);
a /= 10;
}
printf("The reversed number = %d",rev);
return 0;
} |
the_stack_data/375310.c |
#include <stdio.h>
#include <stdint.h>
// the task is to find the longest gap of 0's in a binary representation of number
// you can write to stdout for debugging purposes, e.g.
// printf("this is a debug message\n");
#include <math.h>
int main()
{
solution(32) ;
}
int solution(int N) {
unsigned int i=0 , cnt = 0 ,n2=0;
unsigned int st =0 ;
// array to store binary number
int a[64];
// counter for binary array
while (N > 0) {
// storing remainder in binary array
a[i] = N % 2;
N = N / 2;
//printf("%d", a[i]) ;
i++;
}
a[i] = 2;
//len = (int)log2(N)+1;
i=0 ;
//printf("%d\n", len);
while(a[i] != 2)
{
//printf("%d,",a[i]) ;
i++;
}
i=0 ;
while(a[i] != 2)
{
if(a[i] == 1 && st == 0) // start condition
{
cnt = 0 ;
st = 1 ;
}
if(a[i] == 0 && st == 1) //
{
cnt++ ;
}
if(a[i] == 1 && st == 1) // end condition
{
if(cnt > n2)
{
n2 = cnt ;
}
//st = 0 ;
cnt = 0 ;
}
i++ ;
}
printf("%d\n", n2);
return n2 ;
// write your code in C99 (gcc 6.2.0)
}
|
the_stack_data/12637981.c | /* Endlessh: an SSH tarpit
*
* This is free and unencumbered software released into the public domain.
*/
#if defined(__OpenBSD__)
# define _BSD_SOURCE /* for pledge(2) and unveil(2) */
#else
# define _XOPEN_SOURCE 600
#endif
#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <syslog.h>
#define ENDLESSH_VERSION 1.1
#define DEFAULT_PORT 2222
#define DEFAULT_DELAY 10000 /* milliseconds */
#define DEFAULT_MAX_LINE_LENGTH 32
#define DEFAULT_MAX_CLIENTS 4096
#if defined(__FreeBSD__)
# define DEFAULT_CONFIG_FILE "/usr/local/etc/endlessh.config"
#else
# define DEFAULT_CONFIG_FILE "/etc/endlessh/config"
#endif
#define DEFAULT_BIND_FAMILY AF_UNSPEC
#define XSTR(s) STR(s)
#define STR(s) #s
static long long
epochms(void)
{
struct timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
return tv.tv_sec * 1000ULL + tv.tv_nsec / 1000000ULL;
}
static enum loglevel {
log_none,
log_info,
log_debug
} loglevel = log_none;
static void (*logmsg)(enum loglevel level, const char *, ...);
static void
logstdio(enum loglevel level, const char *format, ...)
{
if (loglevel >= level) {
int save = errno;
/* Print a timestamp */
long long now = epochms();
time_t t = now / 1000;
char date[64];
struct tm tm[1];
strftime(date, sizeof(date), "%Y-%m-%dT%H:%M:%S", gmtime_r(&t, tm));
printf("%s.%03lldZ ", date, now % 1000);
/* Print the rest of the log message */
va_list ap;
va_start(ap, format);
vprintf(format, ap);
va_end(ap);
fputc('\n', stdout);
errno = save;
}
}
static void
logsyslog(enum loglevel level, const char *format, ...)
{
static const int prio_map[] = { LOG_NOTICE, LOG_INFO, LOG_DEBUG };
if (loglevel >= level) {
int save = errno;
/* Output the log message */
va_list ap;
va_start(ap, format);
char buf[256];
vsnprintf(buf, sizeof buf, format, ap);
va_end(ap);
syslog(prio_map[level], "%s", buf);
errno = save;
}
}
static struct {
long long connects;
long long milliseconds;
long long bytes_sent;
} statistics;
struct client {
char ipaddr[INET6_ADDRSTRLEN];
long long connect_time;
long long send_next;
long long bytes_sent;
struct client *next;
int port;
int fd;
};
static struct client *
client_new(int fd, long long send_next)
{
struct client *c = malloc(sizeof(*c));
if (c) {
c->ipaddr[0] = 0;
c->connect_time = epochms();
c->send_next = send_next;
c->bytes_sent = 0;
c->next = 0;
c->fd = fd;
c->port = 0;
/* Set the smallest possible recieve buffer. This reduces local
* resource usage and slows down the remote end.
*/
int value = 1;
int r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
logmsg(log_debug, "setsockopt(%d, SO_RCVBUF, %d) = %d", fd, value, r);
if (r == -1)
logmsg(log_debug, "errno = %d, %s", errno, strerror(errno));
/* Get IP address */
struct sockaddr_storage addr;
socklen_t len = sizeof(addr);
if (getpeername(fd, (struct sockaddr *)&addr, &len) != -1) {
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
c->port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr,
c->ipaddr, sizeof(c->ipaddr));
} else {
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
c->port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr,
c->ipaddr, sizeof(c->ipaddr));
}
}
}
return c;
}
static void
client_destroy(struct client *client)
{
logmsg(log_debug, "close(%d)", client->fd);
long long dt = epochms() - client->connect_time;
logmsg(log_info,
"CLOSE host=%s port=%d fd=%d "
"time=%lld.%03lld bytes=%lld",
client->ipaddr, client->port, client->fd,
dt / 1000, dt % 1000,
client->bytes_sent);
statistics.milliseconds += dt;
close(client->fd);
free(client);
}
static void
statistics_log_totals(struct client *clients)
{
long long milliseconds = statistics.milliseconds;
for (long long now = epochms(); clients; clients = clients->next)
milliseconds += now - clients->connect_time;
logmsg(log_info, "TOTALS connects=%lld seconds=%lld.%03lld bytes=%lld",
statistics.connects,
milliseconds / 1000,
milliseconds % 1000,
statistics.bytes_sent);
}
struct fifo {
struct client *head;
struct client *tail;
int length;
};
static void
fifo_init(struct fifo *q)
{
q->head = q->tail = 0;
q->length = 0;
}
static struct client *
fifo_pop(struct fifo *q)
{
struct client *removed = q->head;
q->head = q->head->next;
removed->next = 0;
if (!--q->length)
q->tail = 0;
return removed;
}
static void
fifo_append(struct fifo *q, struct client *c)
{
if (!q->tail) {
q->head = q->tail = c;
} else {
q->tail->next = c;
q->tail = c;
}
q->length++;
}
static void
fifo_destroy(struct fifo *q)
{
struct client *c = q->head;
while (c) {
struct client *dead = c;
c = c->next;
client_destroy(dead);
}
q->head = q->tail = 0;
q->length = 0;
}
static void
die(void)
{
fprintf(stderr, "endlessh: fatal: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
static unsigned
rand16(unsigned long s[1])
{
s[0] = s[0] * 1103515245UL + 12345UL;
return (s[0] >> 16) & 0xffff;
}
static int
randline(char *line, int maxlen, unsigned long s[1])
{
int len = 3 + rand16(s) % (maxlen - 2);
for (int i = 0; i < len - 2; i++)
line[i] = 32 + rand16(s) % 95;
line[len - 2] = 13;
line[len - 1] = 10;
if (memcmp(line, "SSH-", 4) == 0)
line[0] = 'X';
return len;
}
static volatile sig_atomic_t running = 1;
static void
sigterm_handler(int signal)
{
(void)signal;
running = 0;
}
static volatile sig_atomic_t reload = 0;
static void
sighup_handler(int signal)
{
(void)signal;
reload = 1;
}
static volatile sig_atomic_t dumpstats = 0;
static void
sigusr1_handler(int signal)
{
(void)signal;
dumpstats = 1;
}
struct config {
int port;
int delay;
int max_line_length;
int max_clients;
int bind_family;
};
#define CONFIG_DEFAULT { \
.port = DEFAULT_PORT, \
.delay = DEFAULT_DELAY, \
.max_line_length = DEFAULT_MAX_LINE_LENGTH, \
.max_clients = DEFAULT_MAX_CLIENTS, \
.bind_family = DEFAULT_BIND_FAMILY, \
}
static void
config_set_port(struct config *c, const char *s, int hardfail)
{
errno = 0;
char *end;
long tmp = strtol(s, &end, 10);
if (errno || *end || tmp < 1 || tmp > 65535) {
fprintf(stderr, "endlessh: Invalid port: %s\n", s);
if (hardfail)
exit(EXIT_FAILURE);
} else {
c->port = tmp;
}
}
static void
config_set_delay(struct config *c, const char *s, int hardfail)
{
errno = 0;
char *end;
long tmp = strtol(s, &end, 10);
if (errno || *end || tmp < 1 || tmp > INT_MAX) {
fprintf(stderr, "endlessh: Invalid delay: %s\n", s);
if (hardfail)
exit(EXIT_FAILURE);
} else {
c->delay = tmp;
}
}
static void
config_set_max_clients(struct config *c, const char *s, int hardfail)
{
errno = 0;
char *end;
long tmp = strtol(s, &end, 10);
if (errno || *end || tmp < 1 || tmp > INT_MAX) {
fprintf(stderr, "endlessh: Invalid max clients: %s\n", s);
if (hardfail)
exit(EXIT_FAILURE);
} else {
c->max_clients = tmp;
}
}
static void
config_set_max_line_length(struct config *c, const char *s, int hardfail)
{
errno = 0;
char *end;
long tmp = strtol(s, &end, 10);
if (errno || *end || tmp < 3 || tmp > 255) {
fprintf(stderr, "endlessh: Invalid line length: %s\n", s);
if (hardfail)
exit(EXIT_FAILURE);
} else {
c->max_line_length = tmp;
}
}
static void
config_set_bind_family(struct config *c, const char *s, int hardfail)
{
switch (*s) {
case '4':
c->bind_family = AF_INET;
break;
case '6':
c->bind_family = AF_INET6;
break;
case '0':
c->bind_family = AF_UNSPEC;
break;
default:
fprintf(stderr, "endlessh: Invalid address family: %s\n", s);
if (hardfail)
exit(EXIT_FAILURE);
break;
}
}
enum config_key {
KEY_INVALID,
KEY_PORT,
KEY_DELAY,
KEY_MAX_LINE_LENGTH,
KEY_MAX_CLIENTS,
KEY_LOG_LEVEL,
KEY_BIND_FAMILY,
};
static enum config_key
config_key_parse(const char *tok)
{
static const char *const table[] = {
[KEY_PORT] = "Port",
[KEY_DELAY] = "Delay",
[KEY_MAX_LINE_LENGTH] = "MaxLineLength",
[KEY_MAX_CLIENTS] = "MaxClients",
[KEY_LOG_LEVEL] = "LogLevel",
[KEY_BIND_FAMILY] = "BindFamily"
};
for (size_t i = 1; i < sizeof(table) / sizeof(*table); i++)
if (!strcmp(tok, table[i]))
return i;
return KEY_INVALID;
}
static void
config_load(struct config *c, const char *file, int hardfail)
{
long lineno = 0;
FILE *f = fopen(file, "r");
if (f) {
char line[256];
while (fgets(line, sizeof(line), f)) {
lineno++;
/* Remove comments */
char *comment = strchr(line, '#');
if (comment)
*comment = 0;
/* Parse tokes on line */
char *save = 0;
char *tokens[3];
int ntokens = 0;
for (; ntokens < 3; ntokens++) {
char *tok = strtok_r(ntokens ? 0 : line, " \r\n", &save);
if (!tok)
break;
tokens[ntokens] = tok;
}
switch (ntokens) {
case 0: /* Empty line */
continue;
case 1:
fprintf(stderr, "%s:%ld: Missing value\n", file, lineno);
if (hardfail) exit(EXIT_FAILURE);
continue;
case 2: /* Expected */
break;
case 3:
fprintf(stderr, "%s:%ld: Too many values\n", file, lineno);
if (hardfail) exit(EXIT_FAILURE);
continue;
}
enum config_key key = config_key_parse(tokens[0]);
switch (key) {
case KEY_INVALID:
fprintf(stderr, "%s:%ld: Unknown option '%s'\n",
file, lineno, tokens[0]);
break;
case KEY_PORT:
config_set_port(c, tokens[1], hardfail);
break;
case KEY_DELAY:
config_set_delay(c, tokens[1], hardfail);
break;
case KEY_MAX_LINE_LENGTH:
config_set_max_line_length(c, tokens[1], hardfail);
break;
case KEY_MAX_CLIENTS:
config_set_max_clients(c, tokens[1], hardfail);
break;
case KEY_BIND_FAMILY:
config_set_bind_family(c, tokens[1], hardfail);
break;
case KEY_LOG_LEVEL: {
errno = 0;
char *end;
long v = strtol(tokens[1], &end, 10);
if (errno || *end || v < log_none || v > log_debug) {
fprintf(stderr, "%s:%ld: Invalid log level '%s'\n",
file, lineno, tokens[1]);
if (hardfail) exit(EXIT_FAILURE);
} else {
loglevel = v;
}
} break;
}
}
fclose(f);
}
}
static void
config_log(const struct config *c)
{
logmsg(log_info, "Port %d", c->port);
logmsg(log_info, "Delay %d", c->delay);
logmsg(log_info, "MaxLineLength %d", c->max_line_length);
logmsg(log_info, "MaxClients %d", c->max_clients);
logmsg(log_info, "BindFamily %s",
c->bind_family == AF_INET6 ? "IPv6 Only" :
c->bind_family == AF_INET ? "IPv4 Only" :
"IPv4 Mapped IPv6");
}
static void
usage(FILE *f)
{
fprintf(f, "Usage: endlessh [-vh] [-46] [-d MS] [-f CONFIG] [-l LEN] "
"[-m LIMIT] [-p PORT]\n");
fprintf(f, " -4 Bind to IPv4 only\n");
fprintf(f, " -6 Bind to IPv6 only\n");
fprintf(f, " -d INT Message millisecond delay ["
XSTR(DEFAULT_DELAY) "]\n");
fprintf(f, " -f Set and load config file ["
DEFAULT_CONFIG_FILE "]\n");
fprintf(f, " -h Print this help message and exit\n");
fprintf(f, " -l INT Maximum banner line length (3-255) ["
XSTR(DEFAULT_MAX_LINE_LENGTH) "]\n");
fprintf(f, " -m INT Maximum number of clients ["
XSTR(DEFAULT_MAX_CLIENTS) "]\n");
fprintf(f, " -p INT Listening port [" XSTR(DEFAULT_PORT) "]\n");
fprintf(f, " -v Print diagnostics to standard output "
"(repeatable)\n");
fprintf(f, " -V Print version information and exit\n");
}
static void
print_version(void)
{
puts("Endlessh " XSTR(ENDLESSH_VERSION));
}
static int
server_create(int port, int family)
{
int r, s, value;
s = socket(family == AF_UNSPEC ? AF_INET6 : family, SOCK_STREAM, 0);
logmsg(log_debug, "socket() = %d", s);
if (s == -1) die();
/* Socket options are best effort, allowed to fail */
value = 1;
r = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value));
logmsg(log_debug, "setsockopt(%d, SO_REUSEADDR, true) = %d", s, r);
if (r == -1)
logmsg(log_debug, "errno = %d, %s", errno, strerror(errno));
/*
* With OpenBSD IPv6 sockets are always IPv6-only, so the socket option
* is read-only (not modifiable).
* http://man.openbsd.org/ip6#IPV6_V6ONLY
*/
#ifndef __OpenBSD__
if (family == AF_INET6 || family == AF_UNSPEC) {
errno = 0;
value = (family == AF_INET6);
r = setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &value, sizeof(value));
logmsg(log_debug, "setsockopt(%d, IPV6_V6ONLY, true) = %d", s, r);
if (r == -1)
logmsg(log_debug, "errno = %d, %s", errno, strerror(errno));
}
#endif
if (family == AF_INET) {
struct sockaddr_in addr4 = {
.sin_family = AF_INET,
.sin_port = htons(port),
.sin_addr = {INADDR_ANY}
};
r = bind(s, (void *)&addr4, sizeof(addr4));
} else {
struct sockaddr_in6 addr6 = {
.sin6_family = AF_INET6,
.sin6_port = htons(port),
.sin6_addr = in6addr_any
};
r = bind(s, (void *)&addr6, sizeof(addr6));
}
logmsg(log_debug, "bind(%d, port=%d) = %d", s, port, r);
if (r == -1) die();
r = listen(s, INT_MAX);
logmsg(log_debug, "listen(%d) = %d", s, r);
if (r == -1) die();
return s;
}
/* Write a line to a client, returning client if it's still up. */
static struct client *
sendline(struct client *client, int max_line_length, unsigned long *rng)
{
char line[256];
int len = randline(line, max_line_length, rng);
for (;;) {
ssize_t out = write(client->fd, line, len);
logmsg(log_debug, "write(%d) = %d", client->fd, (int)out);
if (out == -1) {
if (errno == EINTR) {
continue; /* try again */
} else if (errno == EAGAIN || errno == EWOULDBLOCK) {
return client; /* don't care */
} else {
client_destroy(client);
return 0;
}
} else {
client->bytes_sent += out;
statistics.bytes_sent += out;
return client;
}
}
}
int
main(int argc, char **argv)
{
logmsg = logstdio;
struct config config = CONFIG_DEFAULT;
const char *config_file = DEFAULT_CONFIG_FILE;
#if defined(__OpenBSD__)
unveil(config_file, "r"); /* return ignored as the file may not exist */
if (pledge("inet stdio rpath unveil", 0) == -1)
die();
#endif
config_load(&config, config_file, 1);
int option;
while ((option = getopt(argc, argv, "46d:f:hl:m:p:svV")) != -1) {
switch (option) {
case '4':
config_set_bind_family(&config, "4", 1);
break;
case '6':
config_set_bind_family(&config, "6", 1);
break;
case 'd':
config_set_delay(&config, optarg, 1);
break;
case 'f':
config_file = optarg;
#if defined(__OpenBSD__)
unveil(config_file, "r");
if (unveil(0, 0) == -1)
die();
#endif
config_load(&config, optarg, 1);
break;
case 'h':
usage(stdout);
exit(EXIT_SUCCESS);
break;
case 'l':
config_set_max_line_length(&config, optarg, 1);
break;
case 'm':
config_set_max_clients(&config, optarg, 1);
break;
case 'p':
config_set_port(&config, optarg, 1);
break;
case 's':
logmsg = logsyslog;
break;
case 'v':
if (loglevel < log_debug)
loglevel++;
break;
case 'V':
print_version();
exit(EXIT_SUCCESS);
break;
default:
usage(stderr);
exit(EXIT_FAILURE);
}
}
if (argv[optind]) {
fprintf(stderr, "endlessh: too many arguments\n");
exit(EXIT_FAILURE);
}
if (logmsg == logsyslog) {
/* Prepare the syslog */
const char *prog = strrchr(argv[0], '/');
prog = prog ? prog + 1 : argv[0];
openlog(prog, LOG_PID, LOG_DAEMON);
} else {
/* Set output (log) to line buffered */
setvbuf(stdout, 0, _IOLBF, 0);
}
/* Log configuration */
config_log(&config);
/* Install the signal handlers */
signal(SIGPIPE, SIG_IGN);
{
struct sigaction sa = {.sa_handler = sigterm_handler};
int r = sigaction(SIGTERM, &sa, 0);
if (r == -1)
die();
}
{
struct sigaction sa = {.sa_handler = sighup_handler};
int r = sigaction(SIGHUP, &sa, 0);
if (r == -1)
die();
}
{
struct sigaction sa = {.sa_handler = sigusr1_handler};
int r = sigaction(SIGUSR1, &sa, 0);
if (r == -1)
die();
}
struct fifo fifo[1];
fifo_init(fifo);
unsigned long rng = epochms();
int server = server_create(config.port, config.bind_family);
while (running) {
if (reload) {
/* Configuration reload requested (SIGHUP) */
int oldport = config.port;
int oldfamily = config.bind_family;
config_load(&config, config_file, 0);
config_log(&config);
if (oldport != config.port || oldfamily != config.bind_family) {
close(server);
server = server_create(config.port, config.bind_family);
}
reload = 0;
}
if (dumpstats) {
/* print stats requested (SIGUSR1) */
statistics_log_totals(fifo->head);
dumpstats = 0;
}
/* Enqueue clients that are due for another message */
int timeout = -1;
long long now = epochms();
while (fifo->head) {
if (fifo->head->send_next <= now) {
struct client *c = fifo_pop(fifo);
if (sendline(c, config.max_line_length, &rng)) {
c->send_next = now + config.delay;
fifo_append(fifo, c);
}
} else {
timeout = fifo->head->send_next - now;
break;
}
}
/* Wait for next event */
struct pollfd fds = {server, POLLIN, 0};
int nfds = fifo->length < config.max_clients;
logmsg(log_debug, "poll(%d, %d)", nfds, timeout);
int r = poll(&fds, nfds, timeout);
logmsg(log_debug, "= %d", r);
if (r == -1) {
switch (errno) {
case EINTR:
logmsg(log_debug, "EINTR");
continue;
default:
fprintf(stderr, "endlessh: fatal: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
/* Check for new incoming connections */
if (fds.revents & POLLIN) {
int fd = accept(server, 0, 0);
logmsg(log_debug, "accept() = %d", fd);
statistics.connects++;
if (fd == -1) {
const char *msg = strerror(errno);
switch (errno) {
case EMFILE:
case ENFILE:
config.max_clients = fifo->length;
logmsg(log_info,
"MaxClients %d",
fifo->length);
break;
case ECONNABORTED:
case EINTR:
case ENOBUFS:
case ENOMEM:
case EPROTO:
fprintf(stderr, "endlessh: warning: %s\n", msg);
break;
default:
fprintf(stderr, "endlessh: fatal: %s\n", msg);
exit(EXIT_FAILURE);
}
} else {
long long send_next = epochms() + config.delay;
struct client *client = client_new(fd, send_next);
int flags = fcntl(fd, F_GETFL, 0); /* cannot fail */
fcntl(fd, F_SETFL, flags | O_NONBLOCK); /* cannot fail */
if (!client) {
fprintf(stderr, "endlessh: warning: out of memory\n");
close(fd);
} else {
fifo_append(fifo, client);
logmsg(log_info, "ACCEPT host=%s port=%d fd=%d n=%d/%d",
client->ipaddr, client->port, client->fd,
fifo->length, config.max_clients);
}
}
}
}
fifo_destroy(fifo);
statistics_log_totals(0);
if (logmsg == logsyslog)
closelog();
}
|
the_stack_data/182952383.c | #include <stdio.h>
#include<string.h>
#define MAXSIZE 5000
#define TRUE 1
#define FALSE 0
int main()
{
fprintf(stdout, "malloc failed\n");
int i, l;
char str[MAXSIZE];
printf("Enter string\n");
gets(str);
l =strlen(str);
l--;
for(i=0;i<=l/2;l++)
if (str[i] == str[l-i])
return TRUE;
else
return FALSE ;
return 0;
}
|
the_stack_data/23637.c | #include <libgen.h>
#include <stdio.h>
#include <string.h>
static void remove_suffix(char *base, const char *suffix)
{
size_t baselen, suflen;
char *ptr;
baselen = strlen(base);
suflen = strlen(suffix);
ptr = base + baselen - suflen;
if (!strcmp(ptr, suffix))
*ptr = '\0';
}
/* Usage: basename PATH [SUFFIX] */
int main(int argc, char *argv[])
{
const char *suffix;
char *base;
switch (argc) {
case 2:
suffix = NULL;
break;
case 3:
suffix = argv[2];
break;
default:
fputs("basename: missing operand",stderr );
return 1;
}
base = basename(argv[1]);
if (suffix)
remove_suffix(base, suffix);
puts(base);
return 0;
}
|
the_stack_data/198580270.c | //
// Created by forgot on 2019-08-04.
//
/*1021 个位数统计 (15 point(s))*/
/*给定一个 k 位整数 N=d
k−1
10
k−1
+⋯+d
1
10
1
+d
0
(0≤d
i
≤9, i=0,⋯,k−1, d
k−1
>0),请编写程序统计每种不同的个位数字出现的次数。例如:给定 N=100311,则有 2 个 0,3 个 1,和 1 个 3。
输入格式:
每个输入包含 1 个测试用例,即一个不超过 1000 位的正整数 N。
输出格式:
对 N 中每一种不同的个位数字,以 D:M 的格式在一行中输出该位数字 D 及其在 N 中出现的次数 M。要求按 D 的升序输出。
输入样例:
100311
输出样例:
0:2
1:3
3:1*/
#include <stdio.h>
#include <string.h>
//int main() {
// char strN[1001];
// scanf("%s", strN);
//
// int count[11] = {0};
//
// for (int i = 0; i < strlen(strN); i++) {
// switch (strN[i]) {
// case '0':
// count[0]++;
// break;
// case '1':
// count[1]++;
// break;
// case '2':
// count[2]++;
// break;
// case '3':
// count[3]++;
// break;
// case '4':
// count[4]++;
// break;
// case '5':
// count[5]++;
// break;
// case '6':
// count[6]++;
// break;
// case '7':
// count[7]++;
// break;
// case '8':
// count[8]++;
// break;
// case '9':
// count[9]++;
// break;
// default:
// break;
//
// }
// }
//
// for (int j = 0; j < 10; j++) {
// if (count[j]) {
// printf("%d:%d\n", j, count[j]);
// }
// }
//
// return 0;
//}
//
////法2
//int main() {
// char strN[1001];
// scanf("%s", strN);
//
// int count[11] = {0};
//
// for (int i = 0; i < strlen(strN); i++) {
// for (int j = 0; j < 10; j++) {
// if (j + '0' == strN[i]) {
// count[j]++;
// break;
// }
// }
// }
//
// for (int j = 0; j < 10; j++) {
// if (count[j]) {
// printf("%d:%d\n", j, count[j]);
// }
// }
//
// return 0;
//} |
the_stack_data/151706670.c | #include <stdio.h>
#include <stdbool.h>
#include <math.h>
int add_two_bits(int d0, int d1, int carry_in, int *carry_out)
{
// Use your implementation from problem 1
*carry_out = ((d0 ^ d1) & carry_in ) | (d0 & d1);
return (d0 ^ d1) ^ carry_in;
}
void print10_2(int n){//print
if (n/2>0){
print10_2(n/2);
printf("%d",n%2 );
}else{
printf("%d",n );
}
}
void storearray10_2(long dec, int* array){//64 bit array
int i;
for (i = 0 ;i<64; i++){
if (dec>0){
array[i] = dec % 2;
dec = dec/2;
}else{
array[i]=0;
}
}
}
void printarray(int* array, int asize){
int i;
for (i = asize-1 ;i>=0; i--){
if (asize == 64){
printf("%d",array[i] );
}else if (asize ==16){
printf("%d ",array[i] );
}else if (asize == 4){
printf("%d ",array[i] );
}
}
printf("\n");
}
//========================================
void calculate_gi(int* a,int *b,int *g){
int i;
for (i = 63 ;i>=0; i--){
g[i] = a[i] & b[i];
}
}
void calculate_pi(int* a, int* b, int* p){
int i;
for (i = 63 ;i>=0; i--){
p[i] = a[i] | b[i];
}
}
//======================================
void calculate_ggj(int * g, int*p, int* gg){
int j;
int i;
for (j = 0 ; j < 16 ; j++){
i = j*4;
gg[j] = g[i+3] | (p[i+3]&g[i+2]) | (p[i+3]&p[i+2]&g[i+1]) | (p[i+3]&p[i+2]&p[i+1]&g[i]);
}
}
void calculate_gpj(int* p,int* gp){
int j;
int i;
for (j = 0 ; j < 16 ; j++){
i = j*4;
gp[j] = p[i+3] & p[i+2] & p[i+1] & p[i];
}
}
//==========================================
void calculate_sgk(int* gg, int* gp, int* sg){
int k;
int j;
for (k = 0 ; k < 4 ; k++){
j=4 * k;
sg[k] = gg[j+3] | (gp[j+3]&gg[j+2]) | (gp[j+3]&gp[j+2]&gg[j+1]) | (gp[j+3]&gp[j+2]&gp[j+1]&gg[j]);
}
}
void calculate_spk(int* gp,int* sp){
int k;
int j;
for (k = 0 ; k < 4 ; k++){
j=4*k;
sp[k] = gp[j+3] & gp[j+2] & gp[j+1] & gp[j];
}
}
//////////////////////////////////////////
//////////////////////////////////////////
void calculate_sck(int* sg,int* sp, int* sc){
int k=0;
sc[0] = sg[k] | (sp[k] & 0);;
for (k=1 ; k < 4 ; k++){
sc[k] = sg[k] | (sp[k] & sc[k-1]);
}
}
void calculate_gcj(int* gg, int* gp, int*gc, int* sc){
int j = 0;
gc[0] = gg[j] | (gp[j] & 0);
for (j = 1 ; j < 16 ; j++){
//gc[3,7,11,15]
if ((j+1)%4==0){
gc[j] = sc[(j-3)/4];
}else{
gc[j] = gg[j] | (gp[j] & gc[j-1]);
}
}
}
void calculate_ci(int* g, int* p, int* c, int* gc){
int i = 0;
c[0] = g[0] | (p[i] & 0);
for (i = 1 ; i < 64; i++){
//c[3,7,11,15,19,23......63]
if ((i+1)%4 == 0){
c[i] = gc[(i-3)/4];
}else {
c[i] = g[i] | (p[i] & c[i-1]);
}
}
}
void calculate_sum(int* a,int* b, int*sum, int*c){
int i ;
sum[0] = a[0] ^ b[0] ^ 0;
for (i = 1; i < 64; i++){
sum[i] = a[i] ^ b[i] ^ c[i-1];
}
}
/////////////////////////////////////////////////////////////////////////////////////
int main(){
long A;
long B;
int mode;
//----------
int a[64];
int b[64];
int c[64];
int sum[64];
//-----------
int g[64];
int p[64];
//-----------
int gg[16];
int gp[16];
int gc[16];
//-----------
int sg[4];
int sp[4];
int sc[4];
//user intput A,B and mode
printf("Enter A (hex):\n");
scanf("%lx",&A);
storearray10_2(A,a);
printf("Enter B (hex):\n");
scanf("%lx",&B);
storearray10_2(B,b);
printf("Add (0) or subtract (1):\n");
scanf("%d",&mode);
//print A,B a,b
printf("A is %016lx or %ld\n",A,A );
printf("B is %016lx or %ld\n",B,B );
printf("a,b: \n");
printarray(a,64);
printarray(b,64);
printf("g,p:\n");
calculate_gi(a,b,g);
calculate_pi(a,b,p);
printarray(g,64);
printarray(p,64);
printf("gg,gp: \n");
calculate_ggj(g,p,gg);
calculate_gpj(p,gp);
printarray(gg,16);
printarray(gp,16);
printf("sg,sp: \n");
calculate_sgk(gg,gp,sg);
calculate_spk(gp,sp);
printarray(sg,4);
printarray(sp,4);
printf("sc:\n");
calculate_sck(sg,sp,sc);
printarray(sc,4);
printf("gc: \n");
calculate_gcj(gg,gp,gc,sc);
printarray(gc,16);
printf("c:\n");
calculate_ci(g,p,c,gc);
printarray(c,64);
printf("sum\n");
calculate_sum(a,b,sum,c);
printarray(sum,64);
//////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
//////////////////////////////////////////
// if (mode == 1){
// printf("Inverting %d\nB(bin) : ",B );
// }
// printf("%d\n",sizeof(long long int) );
// printf("%d\n",sizeof(int) );
// printf("%d\n",sizeof(double) );
// printf("%ld\n",sizeof(long) );
// printf("%lld\n",sizeof(long long) );
// printf("%lld\n",sizeof(unsigned long) );
//printf("%d\n",sizeof(longs) );
} |
the_stack_data/1155057.c | /* Example problem illustrating buffer overflow */
#include <stdio.h>
#include <stdlib.h>
#define strlen(s) my_strlen(s)
/* Own version of gets */
char *gets(char *s)
{
int c;
char *dest = s;
while ((c = getchar()) != '\n' && c != EOF)
*dest++ = c;
if (c == EOF && dest == s)
/* No characters read */
return NULL;
*dest++ = '\0'; /* Terminate String */
return s;
}
/* Use own versions of strlen and strcpy */
size_t my_strlen(const char *s)
{
size_t len = 0;
while (*(s++))
len++;
return len;
}
char *strcpy(char *dest, const char *src)
{
char *result = dest;
char c;
do {
c = *(src++);
*(dest++) = c;
} while (c);
return result;
}
/* $begin 460-bufovf-raw-c */
/* This is very low-quality code.
It is intended to illustrate bad programming practices.
See Practice Problem SLASHrefLBRACKprob:asm:bufovfRBRACK. */
char *get_line()
{
char buf[4];
char *result;
gets(buf);
result = malloc(strlen(buf));
strcpy(result, buf);
return result;
}
/* $end 460-bufovf-raw-c */
int main(int argc, char *argv[])
{
printf("Input>");
puts(get_line());
return 0;
}
|
the_stack_data/190767901.c | int main ()
{
int a = 0;
int b = 1 ;
int c = a | b ;
return c;
} |
the_stack_data/175144065.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function add8_379
/// Library = EvoApprox8b
/// Circuit = add8_379
/// Area (180) = 1048
/// Delay (180) = 1.880
/// Power (180) = 377.80
/// Area (45) = 79
/// Delay (45) = 0.730
/// Power (45) = 35.67
/// Nodes = 13
/// HD = 0
/// MAE = 0.00000
/// MSE = 0.00000
/// MRE = 0.00 %
/// WCE = 0
/// WCRE = 0 %
/// EP = 0.0 %
uint16_t add8_379(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n0 = (a >> 0) & 0x1;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n16 = (b >> 0) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n33;
uint8_t n55;
uint8_t n76;
uint8_t n82;
uint8_t n83;
uint8_t n112;
uint8_t n115;
uint8_t n132;
uint8_t n133;
uint8_t n175;
uint8_t n182;
uint8_t n183;
uint8_t n232;
uint8_t n233;
uint8_t n282;
uint8_t n283;
uint8_t n332;
uint8_t n333;
uint8_t n382;
uint8_t n383;
n33 = n0 & n16;
n55 = n33;
n76 = n0 ^ n16;
n82 = (n2 ^ n18) ^ n55;
n83 = (n2 & n18) | (n18 & n55) | (n2 & n55);
n112 = n83;
n115 = n112;
n132 = (n4 ^ n20) ^ n115;
n133 = (n4 & n20) | (n20 & n115) | (n4 & n115);
n175 = n133;
n182 = (n6 ^ n22) ^ n175;
n183 = (n6 & n22) | (n22 & n175) | (n6 & n175);
n232 = (n8 ^ n24) ^ n183;
n233 = (n8 & n24) | (n24 & n183) | (n8 & n183);
n282 = (n10 ^ n26) ^ n233;
n283 = (n10 & n26) | (n26 & n233) | (n10 & n233);
n332 = (n12 ^ n28) ^ n283;
n333 = (n12 & n28) | (n28 & n283) | (n12 & n283);
n382 = (n14 ^ n30) ^ n333;
n383 = (n14 & n30) | (n30 & n333) | (n14 & n333);
c |= (n76 & 0x1) << 0;
c |= (n82 & 0x1) << 1;
c |= (n132 & 0x1) << 2;
c |= (n182 & 0x1) << 3;
c |= (n232 & 0x1) << 4;
c |= (n282 & 0x1) << 5;
c |= (n332 & 0x1) << 6;
c |= (n382 & 0x1) << 7;
c |= (n383 & 0x1) << 8;
return c;
}
|
the_stack_data/237644062.c | /* Teensyduino Core Library
* http://www.pjrc.com/teensy/
* Copyright (c) 2013 PJRC.COM, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* 1. The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* 2. If the Software is incorporated into a build system that allows
* selection among a list of target devices, then similar target
* devices manufactured by PJRC.COM must be included in the list of
* target devices and selectable in the same manner.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#if F_CPU >= 20000000
#define USB_DESC_LIST_DEFINE
#include "usb_desc.h"
#ifdef NUM_ENDPOINTS
#include "usb_names.h"
#include "kinetis.h"
#include "avr_functions.h"
// USB Descriptors are binary data which the USB host reads to
// automatically detect a USB device's capabilities. The format
// and meaning of every field is documented in numerous USB
// standards. When working with USB descriptors, despite the
// complexity of the standards and poor writing quality in many
// of those documents, remember descriptors are nothing more
// than constant binary data that tells the USB host what the
// device can do. Computers will load drivers based on this data.
// Those drivers then communicate on the endpoints specified by
// the descriptors.
// To configure a new combination of interfaces or make minor
// changes to existing configuration (eg, change the name or ID
// numbers), usually you would edit "usb_desc.h". This file
// is meant to be configured by the header, so generally it is
// only edited to add completely new USB interfaces or features.
// **************************************************************
// USB Device
// **************************************************************
#define LSB(n) ((n) & 255)
#define MSB(n) (((n) >> 8) & 255)
// USB Device Descriptor. The USB host reads this first, to learn
// what type of device is connected.
static uint8_t device_descriptor[] = {
18, // bLength
1, // bDescriptorType
0x00, 0x02, // bcdUSB
#ifdef DEVICE_CLASS
DEVICE_CLASS, // bDeviceClass
#else
0,
#endif
#ifdef DEVICE_SUBCLASS
DEVICE_SUBCLASS, // bDeviceSubClass
#else
0,
#endif
#ifdef DEVICE_PROTOCOL
DEVICE_PROTOCOL, // bDeviceProtocol
#else
0,
#endif
EP0_SIZE, // bMaxPacketSize0
LSB(VENDOR_ID), MSB(VENDOR_ID), // idVendor
LSB(PRODUCT_ID), MSB(PRODUCT_ID), // idProduct
0x00, 0x01, // bcdDevice
1, // iManufacturer
2, // iProduct
3, // iSerialNumber
1 // bNumConfigurations
};
// These descriptors must NOT be "const", because the USB DMA
// has trouble accessing flash memory with enough bandwidth
// while the processor is executing from flash.
// **************************************************************
// HID Report Descriptors
// **************************************************************
// Each HID interface needs a special report descriptor that tells
// the meaning and format of the data.
#ifdef KEYBOARD_INTERFACE
// Keyboard Protocol 1, HID 1.11 spec, Appendix B, page 59-60
static uint8_t keyboard_report_desc[] = {
0x05, 0x01, // Usage Page (Generic Desktop),
0x09, 0x06, // Usage (Keyboard),
0xA1, 0x01, // Collection (Application),
0x75, 0x01, // Report Size (1),
0x95, 0x08, // Report Count (8),
0x05, 0x07, // Usage Page (Key Codes),
0x19, 0xE0, // Usage Minimum (224),
0x29, 0xE7, // Usage Maximum (231),
0x15, 0x00, // Logical Minimum (0),
0x25, 0x01, // Logical Maximum (1),
0x81, 0x02, // Input (Data, Variable, Absolute), ;Modifier byte
0x95, 0x08, // Report Count (8),
0x75, 0x01, // Report Size (1),
0x15, 0x00, // Logical Minimum (0),
0x25, 0x01, // Logical Maximum (1),
0x05, 0x0C, // Usage Page (Consumer),
0x09, 0xE9, // Usage (Volume Increment),
0x09, 0xEA, // Usage (Volume Decrement),
0x09, 0xE2, // Usage (Mute),
0x09, 0xCD, // Usage (Play/Pause),
0x09, 0xB5, // Usage (Scan Next Track),
0x09, 0xB6, // Usage (Scan Previous Track),
0x09, 0xB7, // Usage (Stop),
0x09, 0xB8, // Usage (Eject),
0x81, 0x02, // Input (Data, Variable, Absolute), ;Media keys
0x95, 0x05, // Report Count (5),
0x75, 0x01, // Report Size (1),
0x05, 0x08, // Usage Page (LEDs),
0x19, 0x01, // Usage Minimum (1),
0x29, 0x05, // Usage Maximum (5),
0x91, 0x02, // Output (Data, Variable, Absolute), ;LED report
0x95, 0x01, // Report Count (1),
0x75, 0x03, // Report Size (3),
0x91, 0x03, // Output (Constant), ;LED report padding
0x95, 0x06, // Report Count (6),
0x75, 0x08, // Report Size (8),
0x15, 0x00, // Logical Minimum (0),
0x25, 0x7F, // Logical Maximum(104),
0x05, 0x07, // Usage Page (Key Codes),
0x19, 0x00, // Usage Minimum (0),
0x29, 0x7F, // Usage Maximum (104),
0x81, 0x00, // Input (Data, Array), ;Normal keys
0xc0 // End Collection
};
#endif
#ifdef MOUSE_INTERFACE
// Mouse Protocol 1, HID 1.11 spec, Appendix B, page 59-60, with wheel extension
static uint8_t mouse_report_desc[] = {
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x02, // Usage (Mouse)
0xA1, 0x01, // Collection (Application)
0x85, 0x01, // REPORT_ID (1)
0x05, 0x09, // Usage Page (Button)
0x19, 0x01, // Usage Minimum (Button #1)
0x29, 0x08, // Usage Maximum (Button #8)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x95, 0x08, // Report Count (8)
0x75, 0x01, // Report Size (1)
0x81, 0x02, // Input (Data, Variable, Absolute)
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x30, // Usage (X)
0x09, 0x31, // Usage (Y)
0x09, 0x38, // Usage (Wheel)
0x15, 0x81, // Logical Minimum (-127)
0x25, 0x7F, // Logical Maximum (127)
0x75, 0x08, // Report Size (8),
0x95, 0x03, // Report Count (3),
0x81, 0x06, // Input (Data, Variable, Relative)
0xC0, // End Collection
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x02, // Usage (Mouse)
0xA1, 0x01, // Collection (Application)
0x85, 0x02, // REPORT_ID (2)
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x30, // Usage (X)
0x09, 0x31, // Usage (Y)
0x15, 0x00, // Logical Minimum (0)
0x26, 0xFF, 0x7F, // Logical Maximum (32767)
0x75, 0x10, // Report Size (16),
0x95, 0x02, // Report Count (2),
0x81, 0x02, // Input (Data, Variable, Absolute)
0xC0 // End Collection
};
#endif
#ifdef JOYSTICK_INTERFACE
static uint8_t joystick_report_desc[] = {
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x04, // Usage (Joystick)
0xA1, 0x01, // Collection (Application)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x75, 0x01, // Report Size (1)
0x95, 0x20, // Report Count (32)
0x05, 0x09, // Usage Page (Button)
0x19, 0x01, // Usage Minimum (Button #1)
0x29, 0x20, // Usage Maximum (Button #32)
0x81, 0x02, // Input (variable,absolute)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x07, // Logical Maximum (7)
0x35, 0x00, // Physical Minimum (0)
0x46, 0x3B, 0x01, // Physical Maximum (315)
0x75, 0x04, // Report Size (4)
0x95, 0x01, // Report Count (1)
0x65, 0x14, // Unit (20)
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x39, // Usage (Hat switch)
0x81, 0x42, // Input (variable,absolute,null_state)
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x01, // Usage (Pointer)
0xA1, 0x00, // Collection ()
0x15, 0x00, // Logical Minimum (0)
0x26, 0xFF, 0x03, // Logical Maximum (1023)
0x75, 0x0A, // Report Size (10)
0x95, 0x04, // Report Count (4)
0x09, 0x30, // Usage (X)
0x09, 0x31, // Usage (Y)
0x09, 0x32, // Usage (Z)
0x09, 0x35, // Usage (Rz)
0x81, 0x02, // Input (variable,absolute)
0xC0, // End Collection
0x15, 0x00, // Logical Minimum (0)
0x26, 0xFF, 0x03, // Logical Maximum (1023)
0x75, 0x0A, // Report Size (10)
0x95, 0x02, // Report Count (2)
0x09, 0x36, // Usage (Slider)
0x09, 0x36, // Usage (Slider)
0x81, 0x02, // Input (variable,absolute)
0xC0 // End Collection
};
#endif
#ifdef SEREMU_INTERFACE
static uint8_t seremu_report_desc[] = {
0x06, 0xC9, 0xFF, // Usage Page 0xFFC9 (vendor defined)
0x09, 0x04, // Usage 0x04
0xA1, 0x5C, // Collection 0x5C
0x75, 0x08, // report size = 8 bits (global)
0x15, 0x00, // logical minimum = 0 (global)
0x26, 0xFF, 0x00, // logical maximum = 255 (global)
0x95, SEREMU_TX_SIZE, // report count (global)
0x09, 0x75, // usage (local)
0x81, 0x02, // Input
0x95, SEREMU_RX_SIZE, // report count (global)
0x09, 0x76, // usage (local)
0x91, 0x02, // Output
0x95, 0x04, // report count (global)
0x09, 0x76, // usage (local)
0xB1, 0x02, // Feature
0xC0 // end collection
};
#endif
#ifdef RAWHID_INTERFACE
static uint8_t rawhid_report_desc[] = {
0x06, LSB(RAWHID_USAGE_PAGE), MSB(RAWHID_USAGE_PAGE),
0x0A, LSB(RAWHID_USAGE), MSB(RAWHID_USAGE),
0xA1, 0x01, // Collection 0x01
0x75, 0x08, // report size = 8 bits
0x15, 0x00, // logical minimum = 0
0x26, 0xFF, 0x00, // logical maximum = 255
0x95, RAWHID_TX_SIZE, // report count
0x09, 0x01, // usage
0x81, 0x02, // Input (array)
0x95, RAWHID_RX_SIZE, // report count
0x09, 0x02, // usage
0x91, 0x02, // Output (array)
0xC0 // end collection
};
#endif
#ifdef FLIGHTSIM_INTERFACE
static uint8_t flightsim_report_desc[] = {
0x06, 0x1C, 0xFF, // Usage page = 0xFF1C
0x0A, 0x39, 0xA7, // Usage = 0xA739
0xA1, 0x01, // Collection 0x01
0x75, 0x08, // report size = 8 bits
0x15, 0x00, // logical minimum = 0
0x26, 0xFF, 0x00, // logical maximum = 255
0x95, FLIGHTSIM_TX_SIZE, // report count
0x09, 0x01, // usage
0x81, 0x02, // Input (array)
0x95, FLIGHTSIM_RX_SIZE, // report count
0x09, 0x02, // usage
0x91, 0x02, // Output (array)
0xC0 // end collection
};
#endif
#ifdef POKKEN_INTERFACE
static uint8_t pokken_report_desc[] = {
0x05, 0x01, // Usage Page (Generic Desktop Ctrls)
0x09, 0x05, // Usage (Game Pad)
0xA1, 0x01, // Collection (Application)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x35, 0x00, // Physical Minimum (0)
0x45, 0x01, // Physical Maximum (1)
0x75, 0x01, // Report Size (1)
0x95, 0x0D, // Report Count (13)
0x05, 0x09, // Usage Page (Button)
0x19, 0x01, // Usage Minimum (0x01)
0x29, 0x0D, // Usage Maximum (0x0D)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x95, 0x03, // Report Count (3)
0x81, 0x01, // Input (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x05, 0x01, // Usage Page (Generic Desktop Ctrls)
0x25, 0x07, // Logical Maximum (7)
0x46, 0x3B, 0x01, // Physical Maximum (315)
0x75, 0x04, // Report Size (4)
0x95, 0x01, // Report Count (1)
0x65, 0x14, // Unit (System: English Rotation, Length: Centimeter)
0x09, 0x39, // Usage (Hat switch)
0x81, 0x42, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,Null State)
0x65, 0x00, // Unit (None)
0x95, 0x01, // Report Count (1)
0x81, 0x01, // Input (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x26, 0xFF, 0x00, // Logical Maximum (255)
0x46, 0xFF, 0x00, // Physical Maximum (255)
0x09, 0x30, // Usage (X)
0x09, 0x31, // Usage (Y)
0x09, 0x32, // Usage (Z)
0x09, 0x35, // Usage (Rz)
0x75, 0x08, // Report Size (8)
0x95, 0x04, // Report Count (4)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x06, 0x00, 0xFF, // Usage Page (Vendor Defined 0xFF00)
0x09, 0x20, // Usage (0x20)
0x95, 0x01, // Report Count (1)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x0A, 0x21, 0x26, // Usage (0x2621)
0x95, 0x08, // Report Count (8)
0x91, 0x02, // Output (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
0xC0, // End Collection
};
#endif
// **************************************************************
// USB Descriptor Sizes
// **************************************************************
// pre-compute the size and position of everything in the config descriptor
//
#define CONFIG_HEADER_DESCRIPTOR_SIZE 9
#define CDC_IAD_DESCRIPTOR_POS CONFIG_HEADER_DESCRIPTOR_SIZE
#ifdef CDC_IAD_DESCRIPTOR
#define CDC_IAD_DESCRIPTOR_SIZE 8
#else
#define CDC_IAD_DESCRIPTOR_SIZE 0
#endif
#define CDC_DATA_INTERFACE_DESC_POS CDC_IAD_DESCRIPTOR_POS+CDC_IAD_DESCRIPTOR_SIZE
#ifdef CDC_DATA_INTERFACE
#define CDC_DATA_INTERFACE_DESC_SIZE 9+5+5+4+5+7+9+7+7
#else
#define CDC_DATA_INTERFACE_DESC_SIZE 0
#endif
#define MIDI_INTERFACE_DESC_POS CDC_DATA_INTERFACE_DESC_POS+CDC_DATA_INTERFACE_DESC_SIZE
#ifdef MIDI_INTERFACE
#define MIDI_INTERFACE_DESC_SIZE 9+7+6+6+9+9+9+5+9+5
#else
#define MIDI_INTERFACE_DESC_SIZE 0
#endif
#define KEYBOARD_INTERFACE_DESC_POS MIDI_INTERFACE_DESC_POS+MIDI_INTERFACE_DESC_SIZE
#ifdef KEYBOARD_INTERFACE
#define KEYBOARD_INTERFACE_DESC_SIZE 9+9+7
#define KEYBOARD_HID_DESC_OFFSET KEYBOARD_INTERFACE_DESC_POS+9
#else
#define KEYBOARD_INTERFACE_DESC_SIZE 0
#endif
#define MOUSE_INTERFACE_DESC_POS KEYBOARD_INTERFACE_DESC_POS+KEYBOARD_INTERFACE_DESC_SIZE
#ifdef MOUSE_INTERFACE
#define MOUSE_INTERFACE_DESC_SIZE 9+9+7
#define MOUSE_HID_DESC_OFFSET MOUSE_INTERFACE_DESC_POS+9
#else
#define MOUSE_INTERFACE_DESC_SIZE 0
#endif
#define RAWHID_INTERFACE_DESC_POS MOUSE_INTERFACE_DESC_POS+MOUSE_INTERFACE_DESC_SIZE
#ifdef RAWHID_INTERFACE
#define RAWHID_INTERFACE_DESC_SIZE 9+9+7+7
#define RAWHID_HID_DESC_OFFSET RAWHID_INTERFACE_DESC_POS+9
#else
#define RAWHID_INTERFACE_DESC_SIZE 0
#endif
#define FLIGHTSIM_INTERFACE_DESC_POS RAWHID_INTERFACE_DESC_POS+RAWHID_INTERFACE_DESC_SIZE
#ifdef FLIGHTSIM_INTERFACE
#define FLIGHTSIM_INTERFACE_DESC_SIZE 9+9+7+7
#define FLIGHTSIM_HID_DESC_OFFSET FLIGHTSIM_INTERFACE_DESC_POS+9
#else
#define FLIGHTSIM_INTERFACE_DESC_SIZE 0
#endif
#define SEREMU_INTERFACE_DESC_POS FLIGHTSIM_INTERFACE_DESC_POS+FLIGHTSIM_INTERFACE_DESC_SIZE
#ifdef SEREMU_INTERFACE
#define SEREMU_INTERFACE_DESC_SIZE 9+9+7+7
#define SEREMU_HID_DESC_OFFSET SEREMU_INTERFACE_DESC_POS+9
#else
#define SEREMU_INTERFACE_DESC_SIZE 0
#endif
#define JOYSTICK_INTERFACE_DESC_POS SEREMU_INTERFACE_DESC_POS+SEREMU_INTERFACE_DESC_SIZE
#ifdef JOYSTICK_INTERFACE
#define JOYSTICK_INTERFACE_DESC_SIZE 9+9+7
#define JOYSTICK_HID_DESC_OFFSET JOYSTICK_INTERFACE_DESC_POS+9
#else
#define JOYSTICK_INTERFACE_DESC_SIZE 0
#endif
#define MTP_INTERFACE_DESC_POS JOYSTICK_INTERFACE_DESC_POS+JOYSTICK_INTERFACE_DESC_SIZE
#ifdef MTP_INTERFACE
#define MTP_INTERFACE_DESC_SIZE 9+7+7+7
#else
#define MTP_INTERFACE_DESC_SIZE 0
#endif
#define POKKEN_INTERFACE_DESC_POS MTP_INTERFACE_DESC_POS+MTP_INTERFACE_DESC_SIZE
#ifdef POKKEN_INTERFACE
#define POKKEN_INTERFACE_DESC_SIZE 9+9+7+7
#define POKKEN_HID_DESC_OFFSET POKKEN_INTERFACE_DESC_POS+9
#else
#define POKKEN_INTERFACE_DESC_SIZE 0
#endif
#define CONFIG_DESC_SIZE POKKEN_INTERFACE_DESC_POS+POKKEN_INTERFACE_DESC_SIZE
// **************************************************************
// USB Configuration
// **************************************************************
// USB Configuration Descriptor. This huge descriptor tells all
// of the devices capbilities.
static uint8_t config_descriptor[CONFIG_DESC_SIZE] = {
// configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10
9, // bLength;
2, // bDescriptorType;
LSB(CONFIG_DESC_SIZE), // wTotalLength
MSB(CONFIG_DESC_SIZE),
NUM_INTERFACE, // bNumInterfaces
1, // bConfigurationValue
0, // iConfiguration
0xC0, // bmAttributes
50, // bMaxPower
#ifdef CDC_IAD_DESCRIPTOR
// interface association descriptor, USB ECN, Table 9-Z
8, // bLength
11, // bDescriptorType
CDC_STATUS_INTERFACE, // bFirstInterface
2, // bInterfaceCount
0x02, // bFunctionClass
0x02, // bFunctionSubClass
0x01, // bFunctionProtocol
4, // iFunction
#endif
#ifdef CDC_DATA_INTERFACE
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
CDC_STATUS_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
1, // bNumEndpoints
0x02, // bInterfaceClass
0x02, // bInterfaceSubClass
0x01, // bInterfaceProtocol
0, // iInterface
// CDC Header Functional Descriptor, CDC Spec 5.2.3.1, Table 26
5, // bFunctionLength
0x24, // bDescriptorType
0x00, // bDescriptorSubtype
0x10, 0x01, // bcdCDC
// Call Management Functional Descriptor, CDC Spec 5.2.3.2, Table 27
5, // bFunctionLength
0x24, // bDescriptorType
0x01, // bDescriptorSubtype
0x01, // bmCapabilities
1, // bDataInterface
// Abstract Control Management Functional Descriptor, CDC Spec 5.2.3.3, Table 28
4, // bFunctionLength
0x24, // bDescriptorType
0x02, // bDescriptorSubtype
0x06, // bmCapabilities
// Union Functional Descriptor, CDC Spec 5.2.3.8, Table 33
5, // bFunctionLength
0x24, // bDescriptorType
0x06, // bDescriptorSubtype
CDC_STATUS_INTERFACE, // bMasterInterface
CDC_DATA_INTERFACE, // bSlaveInterface0
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
CDC_ACM_ENDPOINT | 0x80, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
CDC_ACM_SIZE, 0, // wMaxPacketSize
64, // bInterval
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
CDC_DATA_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
2, // bNumEndpoints
0x0A, // bInterfaceClass
0x00, // bInterfaceSubClass
0x00, // bInterfaceProtocol
0, // iInterface
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
CDC_RX_ENDPOINT, // bEndpointAddress
0x02, // bmAttributes (0x02=bulk)
CDC_RX_SIZE, 0, // wMaxPacketSize
0, // bInterval
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
CDC_TX_ENDPOINT | 0x80, // bEndpointAddress
0x02, // bmAttributes (0x02=bulk)
CDC_TX_SIZE, 0, // wMaxPacketSize
0, // bInterval
#endif // CDC_DATA_INTERFACE
#ifdef MIDI_INTERFACE
// Standard MS Interface Descriptor,
9, // bLength
4, // bDescriptorType
MIDI_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
2, // bNumEndpoints
0x01, // bInterfaceClass (0x01 = Audio)
0x03, // bInterfaceSubClass (0x03 = MIDI)
0x00, // bInterfaceProtocol (unused for MIDI)
0, // iInterface
// MIDI MS Interface Header, USB MIDI 6.1.2.1, page 21, Table 6-2
7, // bLength
0x24, // bDescriptorType = CS_INTERFACE
0x01, // bDescriptorSubtype = MS_HEADER
0x00, 0x01, // bcdMSC = revision 01.00
0x41, 0x00, // wTotalLength
// MIDI IN Jack Descriptor, B.4.3, Table B-7 (embedded), page 40
6, // bLength
0x24, // bDescriptorType = CS_INTERFACE
0x02, // bDescriptorSubtype = MIDI_IN_JACK
0x01, // bJackType = EMBEDDED
1, // bJackID, ID = 1
0, // iJack
// MIDI IN Jack Descriptor, B.4.3, Table B-8 (external), page 40
6, // bLength
0x24, // bDescriptorType = CS_INTERFACE
0x02, // bDescriptorSubtype = MIDI_IN_JACK
0x02, // bJackType = EXTERNAL
2, // bJackID, ID = 2
0, // iJack
// MIDI OUT Jack Descriptor, B.4.4, Table B-9, page 41
9,
0x24, // bDescriptorType = CS_INTERFACE
0x03, // bDescriptorSubtype = MIDI_OUT_JACK
0x01, // bJackType = EMBEDDED
3, // bJackID, ID = 3
1, // bNrInputPins = 1 pin
2, // BaSourceID(1) = 2
1, // BaSourcePin(1) = first pin
0, // iJack
// MIDI OUT Jack Descriptor, B.4.4, Table B-10, page 41
9,
0x24, // bDescriptorType = CS_INTERFACE
0x03, // bDescriptorSubtype = MIDI_OUT_JACK
0x02, // bJackType = EXTERNAL
4, // bJackID, ID = 4
1, // bNrInputPins = 1 pin
1, // BaSourceID(1) = 1
1, // BaSourcePin(1) = first pin
0, // iJack
// Standard Bulk OUT Endpoint Descriptor, B.5.1, Table B-11, pae 42
9, // bLength
5, // bDescriptorType = ENDPOINT
MIDI_RX_ENDPOINT, // bEndpointAddress
0x02, // bmAttributes (0x02=bulk)
MIDI_RX_SIZE, 0, // wMaxPacketSize
0, // bInterval
0, // bRefresh
0, // bSynchAddress
// Class-specific MS Bulk OUT Endpoint Descriptor, B.5.2, Table B-12, page 42
5, // bLength
0x25, // bDescriptorSubtype = CS_ENDPOINT
0x01, // bJackType = MS_GENERAL
1, // bNumEmbMIDIJack = 1 jack
1, // BaAssocJackID(1) = jack ID #1
// Standard Bulk IN Endpoint Descriptor, B.5.1, Table B-11, pae 42
9, // bLength
5, // bDescriptorType = ENDPOINT
MIDI_TX_ENDPOINT | 0x80, // bEndpointAddress
0x02, // bmAttributes (0x02=bulk)
MIDI_TX_SIZE, 0, // wMaxPacketSize
0, // bInterval
0, // bRefresh
0, // bSynchAddress
// Class-specific MS Bulk IN Endpoint Descriptor, B.5.2, Table B-12, page 42
5, // bLength
0x25, // bDescriptorSubtype = CS_ENDPOINT
0x01, // bJackType = MS_GENERAL
1, // bNumEmbMIDIJack = 1 jack
3, // BaAssocJackID(1) = jack ID #3
#endif // MIDI_INTERFACE
#ifdef KEYBOARD_INTERFACE
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
KEYBOARD_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
1, // bNumEndpoints
0x03, // bInterfaceClass (0x03 = HID)
0x01, // bInterfaceSubClass (0x01 = Boot)
0x01, // bInterfaceProtocol (0x01 = Keyboard)
0, // iInterface
// HID interface descriptor, HID 1.11 spec, section 6.2.1
9, // bLength
0x21, // bDescriptorType
0x11, 0x01, // bcdHID
0, // bCountryCode
1, // bNumDescriptors
0x22, // bDescriptorType
LSB(sizeof(keyboard_report_desc)), // wDescriptorLength
MSB(sizeof(keyboard_report_desc)),
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
KEYBOARD_ENDPOINT | 0x80, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
KEYBOARD_SIZE, 0, // wMaxPacketSize
KEYBOARD_INTERVAL, // bInterval
#endif // KEYBOARD_INTERFACE
#ifdef MOUSE_INTERFACE
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
MOUSE_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
1, // bNumEndpoints
0x03, // bInterfaceClass (0x03 = HID)
0x00, // bInterfaceSubClass (0x01 = Boot)
0x00, // bInterfaceProtocol (0x02 = Mouse)
0, // iInterface
// HID interface descriptor, HID 1.11 spec, section 6.2.1
9, // bLength
0x21, // bDescriptorType
0x11, 0x01, // bcdHID
0, // bCountryCode
1, // bNumDescriptors
0x22, // bDescriptorType
LSB(sizeof(mouse_report_desc)), // wDescriptorLength
MSB(sizeof(mouse_report_desc)),
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
MOUSE_ENDPOINT | 0x80, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
MOUSE_SIZE, 0, // wMaxPacketSize
MOUSE_INTERVAL, // bInterval
#endif // MOUSE_INTERFACE
#ifdef RAWHID_INTERFACE
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
RAWHID_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
2, // bNumEndpoints
0x03, // bInterfaceClass (0x03 = HID)
0x00, // bInterfaceSubClass
0x00, // bInterfaceProtocol
0, // iInterface
// HID interface descriptor, HID 1.11 spec, section 6.2.1
9, // bLength
0x21, // bDescriptorType
0x11, 0x01, // bcdHID
0, // bCountryCode
1, // bNumDescriptors
0x22, // bDescriptorType
LSB(sizeof(rawhid_report_desc)), // wDescriptorLength
MSB(sizeof(rawhid_report_desc)),
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
RAWHID_TX_ENDPOINT | 0x80, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
RAWHID_TX_SIZE, 0, // wMaxPacketSize
RAWHID_TX_INTERVAL, // bInterval
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
RAWHID_RX_ENDPOINT, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
RAWHID_RX_SIZE, 0, // wMaxPacketSize
RAWHID_RX_INTERVAL, // bInterval
#endif // RAWHID_INTERFACE
#ifdef FLIGHTSIM_INTERFACE
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
FLIGHTSIM_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
2, // bNumEndpoints
0x03, // bInterfaceClass (0x03 = HID)
0x00, // bInterfaceSubClass
0x00, // bInterfaceProtocol
0, // iInterface
// HID interface descriptor, HID 1.11 spec, section 6.2.1
9, // bLength
0x21, // bDescriptorType
0x11, 0x01, // bcdHID
0, // bCountryCode
1, // bNumDescriptors
0x22, // bDescriptorType
LSB(sizeof(flightsim_report_desc)), // wDescriptorLength
MSB(sizeof(flightsim_report_desc)),
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
FLIGHTSIM_TX_ENDPOINT | 0x80, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
FLIGHTSIM_TX_SIZE, 0, // wMaxPacketSize
FLIGHTSIM_TX_INTERVAL, // bInterval
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
FLIGHTSIM_RX_ENDPOINT, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
FLIGHTSIM_RX_SIZE, 0, // wMaxPacketSize
FLIGHTSIM_RX_INTERVAL, // bInterval
#endif // FLIGHTSIM_INTERFACE
#ifdef SEREMU_INTERFACE
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
SEREMU_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
2, // bNumEndpoints
0x03, // bInterfaceClass (0x03 = HID)
0x00, // bInterfaceSubClass
0x00, // bInterfaceProtocol
0, // iInterface
// HID interface descriptor, HID 1.11 spec, section 6.2.1
9, // bLength
0x21, // bDescriptorType
0x11, 0x01, // bcdHID
0, // bCountryCode
1, // bNumDescriptors
0x22, // bDescriptorType
LSB(sizeof(seremu_report_desc)), // wDescriptorLength
MSB(sizeof(seremu_report_desc)),
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
SEREMU_TX_ENDPOINT | 0x80, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
SEREMU_TX_SIZE, 0, // wMaxPacketSize
SEREMU_TX_INTERVAL, // bInterval
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
SEREMU_RX_ENDPOINT, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
SEREMU_RX_SIZE, 0, // wMaxPacketSize
SEREMU_RX_INTERVAL, // bInterval
#endif // SEREMU_INTERFACE
#ifdef JOYSTICK_INTERFACE
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
JOYSTICK_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
1, // bNumEndpoints
0x03, // bInterfaceClass (0x03 = HID)
0x00, // bInterfaceSubClass
0x00, // bInterfaceProtocol
0, // iInterface
// HID interface descriptor, HID 1.11 spec, section 6.2.1
9, // bLength
0x21, // bDescriptorType
0x11, 0x01, // bcdHID
0, // bCountryCode
1, // bNumDescriptors
0x22, // bDescriptorType
LSB(sizeof(joystick_report_desc)), // wDescriptorLength
MSB(sizeof(joystick_report_desc)),
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
JOYSTICK_ENDPOINT | 0x80, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
JOYSTICK_SIZE, 0, // wMaxPacketSize
JOYSTICK_INTERVAL, // bInterval
#endif // JOYSTICK_INTERFACE
#ifdef MTP_INTERFACE
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
MTP_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
3, // bNumEndpoints
0x06, // bInterfaceClass (0x06 = still image)
0x01, // bInterfaceSubClass
0x01, // bInterfaceProtocol
0, // iInterface
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
MTP_TX_ENDPOINT | 0x80, // bEndpointAddress
0x02, // bmAttributes (0x02=bulk)
MTP_TX_SIZE, 0, // wMaxPacketSize
0, // bInterval
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
MTP_RX_ENDPOINT, // bEndpointAddress
0x02, // bmAttributes (0x02=bulk)
MTP_RX_SIZE, 0, // wMaxPacketSize
0, // bInterval
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
MTP_EVENT_ENDPOINT | 0x80, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
MTP_EVENT_SIZE, 0, // wMaxPacketSize
MTP_EVENT_INTERVAL, // bInterval
#endif // MTP_INTERFACE
#ifdef POKKEN_INTERFACE
0x09, // bLength
0x04, // bDescriptorType (Interface)
POKKEN_INTERFACE, // bInterfaceNumber 0
0x00, // bAlternateSetting
0x02, // bNumEndpoints 2
0x03, // bInterfaceClass
0x00, // bInterfaceSubClass
0x00, // bInterfaceProtocol
0x00, // iInterface (String Index)
0x09, // bLength
0x21, // bDescriptorType (HID)
0x11, 0x01, // bcdHID 1.11
0x00, // bCountryCode
0x01, // bNumDescriptors
0x22, // bDescriptorType[0] (HID)
LSB(sizeof(pokken_report_desc)), // wDescriptorLength
MSB(sizeof(pokken_report_desc)),
0x07, // bLength
0x05, // bDescriptorType (Endpoint)
POKKEN_RX_ENDPOINT, // bEndpointAddress (OUT/H2D)
0x03, // bmAttributes (Interrupt)
POKKEN_RX_SIZE, 0x00, // wMaxPacketSize 64
POKKEN_RX_INTERVAL, // bInterval 10 (unit depends on device speed)
0x07, // bLength
0x05, // bDescriptorType (Endpoint)
POKKEN_TX_ENDPOINT | 0x80, // bEndpointAddress (IN/D2H)
0x03, // bmAttributes (Interrupt)
POKKEN_TX_SIZE, 0x00, // wMaxPacketSize 64
POKKEN_TX_INTERVAL, // bInterval 10 (unit depends on device speed)
#endif // POKKEN_INTERFACE
};
// **************************************************************
// String Descriptors
// **************************************************************
// The descriptors above can provide human readable strings,
// referenced by index numbers. These descriptors are the
// actual string data
/* defined in usb_names.h
struct usb_string_descriptor_struct {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wString[];
};
*/
extern struct usb_string_descriptor_struct usb_string_manufacturer_name
__attribute__ ((weak, alias("usb_string_manufacturer_name_default")));
extern struct usb_string_descriptor_struct usb_string_product_name
__attribute__ ((weak, alias("usb_string_product_name_default")));
extern struct usb_string_descriptor_struct usb_string_serial_number
__attribute__ ((weak, alias("usb_string_serial_number_default")));
struct usb_string_descriptor_struct string0 = {
4,
3,
{0x0409}
};
struct usb_string_descriptor_struct usb_string_manufacturer_name_default = {
2 + MANUFACTURER_NAME_LEN * 2,
3,
MANUFACTURER_NAME
};
struct usb_string_descriptor_struct usb_string_product_name_default = {
2 + PRODUCT_NAME_LEN * 2,
3,
PRODUCT_NAME
};
struct usb_string_descriptor_struct usb_string_serial_number_default = {
12,
3,
{0,0,0,0,0,0,0,0,0,0}
};
void usb_init_serialnumber(void)
{
char buf[11];
uint32_t i, num;
__disable_irq();
FTFL_FSTAT = FTFL_FSTAT_RDCOLERR | FTFL_FSTAT_ACCERR | FTFL_FSTAT_FPVIOL;
FTFL_FCCOB0 = 0x41;
FTFL_FCCOB1 = 15;
FTFL_FSTAT = FTFL_FSTAT_CCIF;
while (!(FTFL_FSTAT & FTFL_FSTAT_CCIF)) ; // wait
num = *(uint32_t *)&FTFL_FCCOB7;
__enable_irq();
// add extra zero to work around OS-X CDC-ACM driver bug
if (num < 10000000) num = num * 10;
ultoa(num, buf, 10);
for (i=0; i<10; i++) {
char c = buf[i];
if (!c) break;
usb_string_serial_number_default.wString[i] = c;
}
usb_string_serial_number_default.bLength = i * 2 + 2;
}
// **************************************************************
// Descriptors List
// **************************************************************
// This table provides access to all the descriptor data above.
const usb_descriptor_list_t usb_descriptor_list[] = {
//wValue, wIndex, address, length
{0x0100, 0x0000, device_descriptor, sizeof(device_descriptor)},
{0x0200, 0x0000, config_descriptor, sizeof(config_descriptor)},
#ifdef SEREMU_INTERFACE
{0x2200, SEREMU_INTERFACE, seremu_report_desc, sizeof(seremu_report_desc)},
{0x2100, SEREMU_INTERFACE, config_descriptor+SEREMU_HID_DESC_OFFSET, 9},
#endif
#ifdef KEYBOARD_INTERFACE
{0x2200, KEYBOARD_INTERFACE, keyboard_report_desc, sizeof(keyboard_report_desc)},
{0x2100, KEYBOARD_INTERFACE, config_descriptor+KEYBOARD_HID_DESC_OFFSET, 9},
#endif
#ifdef MOUSE_INTERFACE
{0x2200, MOUSE_INTERFACE, mouse_report_desc, sizeof(mouse_report_desc)},
{0x2100, MOUSE_INTERFACE, config_descriptor+MOUSE_HID_DESC_OFFSET, 9},
#endif
#ifdef JOYSTICK_INTERFACE
{0x2200, JOYSTICK_INTERFACE, joystick_report_desc, sizeof(joystick_report_desc)},
{0x2100, JOYSTICK_INTERFACE, config_descriptor+JOYSTICK_HID_DESC_OFFSET, 9},
#endif
#ifdef RAWHID_INTERFACE
{0x2200, RAWHID_INTERFACE, rawhid_report_desc, sizeof(rawhid_report_desc)},
{0x2100, RAWHID_INTERFACE, config_descriptor+RAWHID_HID_DESC_OFFSET, 9},
#endif
#ifdef FLIGHTSIM_INTERFACE
{0x2200, FLIGHTSIM_INTERFACE, flightsim_report_desc, sizeof(flightsim_report_desc)},
{0x2100, FLIGHTSIM_INTERFACE, config_descriptor+FLIGHTSIM_HID_DESC_OFFSET, 9},
#endif
#ifdef POKKEN_INTERFACE
{0x2200, POKKEN_INTERFACE, pokken_report_desc, sizeof(pokken_report_desc)},
{0x2100, POKKEN_INTERFACE, config_descriptor+POKKEN_HID_DESC_OFFSET, 9},
#endif
{0x0300, 0x0000, (const uint8_t *)&string0, 0},
{0x0301, 0x0409, (const uint8_t *)&usb_string_manufacturer_name, 0},
{0x0302, 0x0409, (const uint8_t *)&usb_string_product_name, 0},
{0x0303, 0x0409, (const uint8_t *)&usb_string_serial_number, 0},
{0, 0, NULL, 0}
};
// **************************************************************
// Endpoint Configuration
// **************************************************************
#if 0
// 0x00 = not used
// 0x19 = Recieve only
// 0x15 = Transmit only
// 0x1D = Transmit & Recieve
//
const uint8_t usb_endpoint_config_table[NUM_ENDPOINTS] =
{
0x00, 0x15, 0x19, 0x15, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif
const uint8_t usb_endpoint_config_table[NUM_ENDPOINTS] =
{
#if (defined(ENDPOINT1_CONFIG) && NUM_ENDPOINTS >= 1)
ENDPOINT1_CONFIG,
#elif (NUM_ENDPOINTS >= 1)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT2_CONFIG) && NUM_ENDPOINTS >= 2)
ENDPOINT2_CONFIG,
#elif (NUM_ENDPOINTS >= 2)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT3_CONFIG) && NUM_ENDPOINTS >= 3)
ENDPOINT3_CONFIG,
#elif (NUM_ENDPOINTS >= 3)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT4_CONFIG) && NUM_ENDPOINTS >= 4)
ENDPOINT4_CONFIG,
#elif (NUM_ENDPOINTS >= 4)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT5_CONFIG) && NUM_ENDPOINTS >= 5)
ENDPOINT5_CONFIG,
#elif (NUM_ENDPOINTS >= 5)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT6_CONFIG) && NUM_ENDPOINTS >= 6)
ENDPOINT6_CONFIG,
#elif (NUM_ENDPOINTS >= 6)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT7_CONFIG) && NUM_ENDPOINTS >= 7)
ENDPOINT7_CONFIG,
#elif (NUM_ENDPOINTS >= 7)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT8_CONFIG) && NUM_ENDPOINTS >= 8)
ENDPOINT8_CONFIG,
#elif (NUM_ENDPOINTS >= 8)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT9_CONFIG) && NUM_ENDPOINTS >= 9)
ENDPOINT9_CONFIG,
#elif (NUM_ENDPOINTS >= 9)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT10_CONFIG) && NUM_ENDPOINTS >= 10)
ENDPOINT10_CONFIG,
#elif (NUM_ENDPOINTS >= 10)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT11_CONFIG) && NUM_ENDPOINTS >= 11)
ENDPOINT11_CONFIG,
#elif (NUM_ENDPOINTS >= 11)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT12_CONFIG) && NUM_ENDPOINTS >= 12)
ENDPOINT12_CONFIG,
#elif (NUM_ENDPOINTS >= 12)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT13_CONFIG) && NUM_ENDPOINTS >= 13)
ENDPOINT13_CONFIG,
#elif (NUM_ENDPOINTS >= 13)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT14_CONFIG) && NUM_ENDPOINTS >= 14)
ENDPOINT14_CONFIG,
#elif (NUM_ENDPOINTS >= 14)
ENDPOINT_UNUSED,
#endif
#if (defined(ENDPOINT15_CONFIG) && NUM_ENDPOINTS >= 15)
ENDPOINT15_CONFIG,
#elif (NUM_ENDPOINTS >= 15)
ENDPOINT_UNUSED,
#endif
};
#endif // NUM_ENDPOINTS
#endif // F_CPU >= 20 MHz
|
the_stack_data/1036733.c | #include <curses.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 4
#define DEPTH 5
#define MIN(x, y) (x < y)? (x) : (y)
#define MAX(x, y) (x > y)? (x) : (y)
#define FOREACH(r, c) for (r = 0; r < SIZE; r++) for (c = 0; c < SIZE; c++)
typedef int** board;
typedef enum emove { UP, LEFT, RIGHT, DOWN } move_t;
/**
* Location/value triple generated between player moves.
*/
typedef struct sgen {
int val, row, col;
} gen;
void sdisplay(board, int, int);
gen *cgen(board b);
gen *cgen_r(board b, int d, double *s);
move_t cplay(board b);
move_t cplay_r(board b, int d, int*);
move_t eplay_r(board b, int d, double *score, int*);
void place(board b, gen* g);
int gameover(board b);
int shift(board b, move_t m, double *score);
void help_and_quit(int);
/**
* Return a judgment of how ``good'' the board is, for leaves of expectimax
*/
double eval(board b)
{
int r, c, count = 0, clear = 0;
int collapse = 0;
double tot = 0, score = 0;
for (r = 0; r < SIZE - 1; r++) {
for (c = 0; c < SIZE - 1; c++) {
double row = b[r][c] - b[r+1][c];
double col = b[r][c] - b[r][c+1];
if (r == 0) {
row *= 2;
col *= 2;
}
if (row == 0 || col == 0)
collapse = 1;
score += row + col;
}
}
FOREACH(r, c) {
if (b[r][c]) {
tot += b[r][c];
count++;
} else {
clear++;
}
}
score += tot / count;
/* Near-death penalty */
if (clear < 4) {
score /= 5 - clear;
}
/* Avoid death at all cost */
if (clear == 0 && collapse == 0)
return 0;
return score;
}
/**
* Return a copy of the board.
*/
board clone(board b)
{
int r, c;
board copy = (board) calloc(SIZE, sizeof(int*));
for (r = 0; r < SIZE; r++) {
copy[r] = (int*) calloc(SIZE, sizeof(int));
for (c = 0; c < SIZE; c++) {
copy[r][c] = b[r][c];
}
}
return copy;
}
/**
* Free a board.
*/
void destruct(board b) {
int r;
for (r = 0; r < SIZE; r++) {
free(b[r]);
}
free(b);
}
/**
* Return 1 if the boards are different, 0 otherwise.
*/
int different(board a, board b)
{
int r, c, diff = 0;
FOREACH(r, c) {
if (a[r][c] != b[r][c])
diff = 1;
}
return diff;
}
/**
* Have the user select a location and value triple.
* Use hjkl to navigate to the square, and hit enter to return 2 and space to
* return 4.
*/
gen *hgen(board b)
{
gen *g = (gen*) calloc(1, sizeof(gen));
char in;
g->row = 0;
g->col = 0;
g->val = 2;
while (1) {
clear();
sdisplay(b, g->row, g->col);
in = getch();
switch (in) {
case 65:
case 'k': g->row--; break;
case 66:
case 'j': g->row++; break;
case 68:
case 'h': g->col--; break;
case 67:
case 'l': g->col++; break;
case ' ': g->val = 4; //fall through and return
case 10: if (!b[g->row][g->col])
return g;
}
g->row = MIN(g->row, SIZE - 1);
g->row = MAX(g->row, 0);
g->col = MIN(g->col, SIZE - 1);
g->col = MAX(g->col, 0);
}
}
/**
* Have the computer generate a location/value triple designed to put the player
* in the worst position possible.
* Alg: Minimax, corecursively with cplay().
*/
gen *cgen(board b)
{
double score = 0;
return cgen_r(b, DEPTH, &score);
}
/**
* Recursive helper to cgen();
*/
gen *cgen_r(board b, int d, double *score)
{
gen g, *best = (gen*) calloc(1, sizeof(gen));
int r, c, min = INT_MAX, nullscore;
double s;
FOREACH(r, c) {
s = nullscore = *score;
if (!b[r][c]) {
g.row = r;
g.col = c;
g.val = 2;
board copy = clone(b);
place(copy, &g);
if (gameover(copy)) {
*best = g;
destruct(copy);
return best;
}
if (d > 1) {
shift(copy, cplay_r(copy, d - 1, &nullscore), &s);
}
if (s < min) {
min = s;
*best = g;
}
//Technically necessary for true minimax... but we can disregard:
/*
s = nullscore = *score;
g.val = 4;
copy[r][c] = 4;
if (gameover(copy)) {
*best = g;
destruct(copy);
return best;
}
if (d > 1) {
shift(copy, cplay_r(copy, d - 1, &s), &s);
}
if (s < min) {
min = s;
*best = g;
}
*/
destruct(copy);
}
}
*score = s;
return best;
}
/**
* Generate a random board location.
*/
gen *rgen(board b)
{
gen *g = (gen*) calloc(1, sizeof(gen));
g->val = 2;
if (rand() % 10 == 0)
g->val = 4;
do {
g->row = rand() % SIZE;
g->col = rand() % SIZE;
} while (b[g->row][g->col]);
return g;
}
/**
* Get a move from the computer.
* Alg: Minimax, corecursively with cgen().
* */
move_t cplay(board b)
{
int score = 0;
return cplay_r(b, DEPTH, &score);
}
/**
* Recursive helper to cplay().
*/
move_t cplay_r(board b, int d, int *score)
{
move_t m, best = UP;
int max = -1;
double s;
for (m = 0; m < 4; m++) {
s = *score;
board c = clone(b);
shift(c, m, &s);
if (!different(b, c)) {
destruct(c);
continue;
}
if (d > 1) {
gen *g = cgen_r(b, d-1, &s);
place(c, g);
free(g);
}
if (s > max) {
max = s;
best = m;
}
destruct(c);
}
*score = s;
return best;
}
/**
* Get a move from the computer using Expectimax
*/
move_t eplay(board b)
{
double score = 0;
//int d = DEPTH, dd = DEPTH, leaves = 0, newleaves = 0; // DD for "depth decided"
int d, leaves = 0;
int r, c, clear = 0;
FOREACH(r,c)
if (!b[r][c])
clear++;
switch (clear) {
case 0: d = 7; break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7: d = 5; break;
case 8:
default: d = 3;
}
move_t m = eplay_r(b, d, &score, &leaves);
return m;
}
/**
* Recursive helper to eplay().
* b: the board to find the best move on
* d: depth to search
* score: output parameter; score of the best move.
*/
move_t eplay_r(board b, int d, double *score, int *leafcount)
{
move_t m, best = -1;
double max = 0;
*score = 0;
double junk;
for (m = 0; m < 4; m++) {
if (m == DOWN && max > 0)
break;
board copy = clone(b);
if (!shift(copy, m, &junk)) {
destruct(copy);
continue;
}
/* At least this move is legal. Pick this for now. We still need to
* compute its score to compare later. */
if (best == -1)
best = m;
double s = 0;
if (d <= 1) {
s = eval(copy);
(*leafcount)++;
} else {
int count = 0;
int r, c;
FOREACH(r, c) {
gen g;
if (!copy[r][c]) {
g.row = r;
g.col = c;
g.val = 2;
board copy2 = clone(copy);
double childscore;
place(copy2, &g);
if (!gameover(copy2)) {
eplay_r(copy2, d - 2, &childscore, leafcount);
count++;
s += childscore * 0.9;
}
g.val = 4;
place(copy2, &g);
if (!gameover(copy2)) {
eplay_r(copy2, d - 2, &childscore, leafcount);
count++;
s += childscore * 0.1;
}
destruct(copy2);
}
}
if (count == 0)
s = 0;
else
s /= count;
}
if (s > max) {
max = s;
best = m;
}
destruct(copy);
}
*score = max;
return best;
}
/**
* Prefer the moves in this order:
* UP LEFT RIGHT DOWN
*/
move_t splay(board b)
{
double score;
board c = clone(b);
if (shift(c, UP, &score)) {
free(c);
return UP;
}
c = clone(b);
if (shift(c, LEFT, &score)) {
free(c);
return LEFT;
}
c = clone(b);
if (shift(c, RIGHT, &score)) {
free(c);
return RIGHT;
}
return DOWN;
}
move_t rotmove = UP;
/**
* Play up down left right in that order.
*/
move_t rotplay(board b)
{
rotmove += 1;
rotmove %= 4;
return rotmove;
}
/**
* Get a move from a human player for the given board and return it.
*/
move_t hplay(board b)
{
char in;
while (1) {
in = getch();
switch (in) {
case 65:
case 'k': return UP;
case 66:
case 'j': return DOWN;
case 68:
case 'h': return LEFT;
case 67:
case 'l': return RIGHT;
}
}
}
/**
* Return a random move.
*/
move_t rplay(board b)
{
return rand() % 4;
}
/**
* This macro, together with the appropriate inputs provided by the function
* below, performs the ``2048 shift''.
* The idea here to abstract away the small differences between the four
* directions to avoid the repetition of a very similar code block.
**/
#define SHIFT(R, C, RC, CC, MAJ, MIN) \
for (MAJ = 0; MAJ < SIZE; MAJ++) { \
int count = -1, last = -1; \
for (MIN = 0; MIN < SIZE; MIN++) { \
if (b[R][C]) { \
if (last == b[R][C]) { \
b[RC][CC] *= 2; \
*score += b[RC][CC]; \
b[R][C] = 0; \
last = -1; \
moved = 1; \
} else { \
last = b[R][C]; \
b[R][C] = 0; \
count++; \
b[RC][CC] = last; \
moved = (moved || RC != R || CC != C); \
} \
} \
} \
}
/**
* Perform a shift on board b. Return 1 if any squares were actually moved,
* 0 otherwise. Update the score accordingly.
**/
int shift(board b, move_t m, double *score)
{
int r, c, moved = 0;
switch (m) {
case UP:
SHIFT(r, c, count, c, c, r);
break;
case DOWN:
SHIFT(SIZE-r-1, c, SIZE-count-1, c, c, r);
break;
case LEFT:
SHIFT(r, c, r, count, r, c);
break;
case RIGHT:
SHIFT(r, SIZE-c-1, r, SIZE-count-1, r, c);
break;
}
return moved;
}
/**
* Place the generated value on the board.
*/
void place(board b, gen* g)
{
b[g->row][g->col] = g->val;
}
/**
* Returns 1 if the board is full and no moves exist, 0 otherwise.
*/
int gameover(board b)
{
// First of all, check if there are gaps
// Start at bottom right since we know the expectimax player prefers to go
// UP and LEFT.
int r, c;
for (r = SIZE-1; r >= 0; r--)
for (c = SIZE-1; c >= 0; c--)
if (!b[r][c])
return 0;
// Now check if any moves work.
// (This would do it by itself, but doing the above first is faster on
// average)
move_t m;
double nullscore;
for (m = 0; m < 4; m++) {
board c = clone(b);
if (shift(c, m, &nullscore)) {
destruct(c);
return 0;
}
destruct(c);
}
return 1;
}
#define DISPLAY(print) \
int r, c; \
print("\n\n"); \
for (r = 0; r < SIZE; r++) { \
print(" "); \
for (c = 0; c < SIZE; c++) { \
if (b[r][c]) \
print("[%4d]", b[r][c]); \
else \
print("[ ]"); \
} \
print("\n"); \
} \
/**
* Print a board to ncurses screen.
*/
void display(board b, int score)
{
DISPLAY(printw)
printw("%d\n", score);
}
/**
* Print the board to stdout.
*/
void pdisplay(board b)
{
DISPLAY(printf)
}
/**
* Print the board with (r, c) highlighted in red.
*/
void sdisplay(board b, int row, int col)
{
int r, c;
printw("\n\n");
for (r = 0; r < SIZE; r++) {
printw(" ");
for (c = 0; c < SIZE; c++) {
if (r == row && c == col)
attron(COLOR_PAIR(1));
if (b[r][c])
printw("[%4d]", b[r][c]);
else
printw("[ ]");
attroff(COLOR_PAIR(1));
}
printw("\n");
}
}
void help_and_quit(int status)
{
printf("\
usage: tfe [OPTIONS] [-c <number of games>] \n\
\n\
To play, use arrow keys or hjkl to enter shifts. When playing as the tile\n\
generator, move to the desired square using arrow keys, then hit enter to\n\
generator a 2, and hit space to generate a 4.\n\
\n\
Options:\n\
\n\
General:\n\
-h display this message and exit.\n\
-p print the final board to stdout.\n\
-w step through a game played by computer (note: if one of the ncurses\n\
players is selected, this option has no effect)\n\
-c <n> play n games (default is 1)\n\
\n\
Setting the player:\n\
-r random player\n\
-n ncurses interface / human (default)\n\
-m minimax player\n\
-e expectimax player\n\
-s simple player\n\
-v rotation player\n\
\n\
Setting the new tile generator:\n\
-R random generation (default)\n\
-N ncurses interface / human\n\
-M minimax generator\n\
");
exit(status);
}
int main(int argc, char *argv[])
{
int c, ncurses, pn = 1, gn = 0, pd = 0, watch = 0;
int expect_count = 0, count_to = 1;
/* "Abstract" player and tile generator... assign based on options */
gen *(*generator)(board) = rgen;
move_t (*player)(board) = hplay;
while (--argc > 0 && (*++argv)[0] == '-') { // Option parser from K&R p 117!
while ((c = *++argv[0])) {
switch (c) {
case 'h':
help_and_quit(0);
break;
case 'w':
watch = 1;
break;
case 'r':
player = rplay;
pn = 0;
break;
case 'n':
player = hplay;
pn = 1;
break;
case 'm':
player = cplay;
pn = 0;
break;
case 'e':
player = eplay;
pn = 0;
break;
case 'c':
expect_count = 1;
break;
case 's':
player = splay;
pn = 0;
break;
case 'v':
player = rotplay;
pn = 0;
break;
case 'R':
generator = rgen;
gn = 0;
break;
case 'N':
generator = hgen;
gn = 1;
break;
case 'M':
generator = cgen;
gn = 0;
break;
case 'p':
pd = 1;
break;
default:
fprintf(stderr, "Invalid option: %x\n\n", c);
help_and_quit(1);
}
}
}
if (expect_count && !argc) {
help_and_quit(1);
} else if (expect_count) {
count_to = atoi(*argv);
}
ncurses = pn || gn || watch;
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
srand(t.tv_nsec);
if (ncurses) {
initscr();
start_color();
init_pair(1, COLOR_WHITE, COLOR_RED);
cbreak();
noecho();
}
//printf("DEPTH: %d\n", DEPTH);
int count;
for (count = 0; count < count_to; count++) {
int r;
double score = 0;
board b = (board) calloc(SIZE, sizeof(int*));
for (r = 0; r < SIZE; r++) {
b[r] = (int*) calloc(SIZE, sizeof(int));
}
gen *g = (*generator)(b);
place(b, g);
free(g);
g = (*generator)(b);
place(b, g);
free(g);
while (!gameover(b)) {
if (ncurses) {
clear();
display(b, score);
if (watch && !pn && !gn)
getch();
}
move_t m = (*player)(b);
if (shift(b, m, &score)) {
g = (*generator)(b);
place(b, g);
free(g);
}
}
if (ncurses) {
endwin();
}
if (pd) {
pdisplay(b);
}
printf("%f\n", score);
}
return 0;
}
|
the_stack_data/141497.c | #include<stdio.h>
int find_candidate(int arr[],int n){
int count=1;
int i=1;
int max=arr[0];
while(i<n){
if(arr[i]==max){
count++;
}
else
count--;
if(count==0){
max=arr[i];
count=1;
}
i++;
}
return max;
}
int main(){
int n;
scanf("%d",&n);
int i=0;
int arr[n];
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
int max=find_candidate(arr,n);
printf("max is %d\n",max);
int count=0;
for(i=0;i<n;i++){
if(arr[i]==max){
count++;
}
}
if(count>n/2){
printf("%d\n",max);
}
else{
printf("none\n");
}
return 0;
}
|
the_stack_data/49126.c | #include <stdio.h>
int main() {
int numberOfCases;
scanf("%d", &numberOfCases);
if(numberOfCases >= 1 && numberOfCases <= 10){
for(int i = 0; i < numberOfCases; i++){
long int num1;
long int num2;
scanf("%li %li", &num1, &num2);
if(num2 == 0) printf("1\n");
else if(num1 == 1) printf("1\n");
else if(num1 == 0) printf("0\n");
else if(num2 == 1) printf("%li\n", num1 % 10);
else if(num1 % 10 == 0) printf("0\n");
else if(num1 % 10 == 1) printf("1\n");
else if(num1 % 10 == 5) printf("5\n");
else if(num1 % 10 == 6) printf("6\n");
else if(num1 % 10 == 2){
if(num2 % 4 == 0) printf("6\n");
else if(num2 % 4 == 1) printf("2\n");
else if(num2 % 4 == 2) printf("4\n");
else printf("8\n");
}
else if(num1 % 10 == 3){
if(num2 % 4 == 0) printf("1\n");
else if(num2 % 4 == 1) printf("3\n");
else if(num2 % 4 == 2) printf("9\n");
else printf("7\n");
}
else if(num1 % 10 == 4){
if(num2 % 2 == 0) printf("6\n");
else printf("4\n");
}
else if(num1 % 10 == 7){
if(num2 % 4 == 0) printf("1\n");
else if(num2 % 4 == 1) printf("7\n");
else if(num2 % 4 == 2) printf("9\n");
else printf("3\n");
}
else if(num1 % 10 == 8){
if(num2 % 4 == 0) printf("6\n");
else if(num2 % 4 == 1) printf("8\n");
else if(num2 % 4 == 2) printf("4\n");
else printf("2\n");
}
else if(num1 % 10 == 9){
if(num2 % 2 == 0) printf("1\n");
else printf("9\n");
}
}
}
return 0;
}
|
the_stack_data/22012266.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()
{
int n, i, sum = 0;
printf("Enter a number : ");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
sum += i;
}
printf("Sum = %d", sum);
return 0;
}
|
the_stack_data/15761644.c | // RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-ipa=inlining -analyzer-store region -verify %s
// Test when entering f1(), we set the right AnalysisDeclContext to Environment.
// Otherwise, block-level expr '1 && a' would not be block-level.
int a;
void f1() {
if (1 && a)
return;
}
void f2() {
f1();
}
|
the_stack_data/338347.c | int main(){
int teste;
char aaa,bbb;
float ccc;
teste = 2;
aaa = 'a';
bbb = "bbb come";
bbb = 2;
ccc = 3.4;
ccc = 1.5 + 2.0;
return 0;
} |
the_stack_data/178115.c | /*
* Program to compare arrays of pointers with arrays of arrays
*/
#include <stdio.h>
int main ()
{
char *s1[] = {"Al", "Capone"};
/* "Al\0" and "Capone\0" are two string literals created in the
CONSTANTS section of the RAM memory.
"s1" is an array of two pointers created in the STACK section of the
RAM memory, whose pointers point to those two string literals.
*/
char s2[][7] = {"Al", "Capone"};
/* "Al\0" and "Capone\0" are two string literals created in the
CONSTANTS section of the RAM memory.
"s2" is an array of two array, that reserves 2 * sizeof(char) bytes
in the STACK section of the RAM memory, and copies those two
string literals to the corresponding bytes.
*/
printf("Size of a char variable: %zu bytes\n", sizeof(char));
printf("Size of a pointer to a char: %zu bytes\n", sizeof(char*));
printf("Size of the array of pointers: %zu bytes\n", sizeof(s1));
printf("Size of the array of arrays: %zu bytes\n", sizeof(s2));
// Size of a char variable: 1 bytes
// Size of a pointer to a char: 4 bytes
// Size of the array of pointers: 8 bytes
// Size of the array of arrays: 14 bytes
/* As we can see, arrays of pointers and arrays of arrays are not
equivalent variables, despite of that we can operate with them in a
similar way.
*/
printf("First value pointed by the pointer array: %s\n", *(s1 + 0));
printf("Second value pointed by the pointer array: %s\n", *(s1 + 1));
printf("First value pointed by the pointer array: %s\n", s1[0]);
printf("Second value pointed by the pointer array: %s\n", s1[1]);
printf("First value pointed by the array of arrays: %s\n", *(s2 + 0));
printf("Second value pointed by the array of arrays: %s\n", *(s2 + 1));
printf("First value pointed by the array of arrays: %s\n", s2[0]);
printf("Second value pointed by the array of arrays: %s\n", s2[1]);
return 0;
}
|
the_stack_data/350905.c | /*******************************************************************************
*
* The BYTE UNIX Benchmarks - Release 3
* Module: timeit.c SID: 3.3 5/15/91 19:30:21
*******************************************************************************
* Bug reports, patches, comments, suggestions should be sent to:
*
* Ben Smith, Rick Grehan or Tom Yager
* [email protected] [email protected] [email protected]
*
*******************************************************************************
* Modification Log:
* May 12, 1989 - modified empty loops to avoid nullifying by optimizing
* compilers
* August 28, 1990 - changed timing relationship--now returns total number
* of iterations (ty)
* October 22, 1997 - code cleanup to remove ANSI C compiler warnings
* Andy Kahn <[email protected]>
*
******************************************************************************/
/* this module is #included in other modules--no separate SCCS ID */
/*
* Timing routine
*
*/
#include <signal.h>
#include <unistd.h>
void wake_me(int seconds, void (*func)(int))
{
/* set up the signal handler */
signal(SIGALRM, func);
/* get the clock running */
alarm(seconds);
}
|
the_stack_data/247016897.c | /**
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
**/
#include <stdio.h>
#include <stdlib.h>
#define N 20
int grid[N+1][N+1];
long stevilopoti[N+1][N+1];
//unsigned long stevecDesno = 0, stevecDol = 0;
unsigned long navigacija(int vrstica, int stolpec){
unsigned long stevecDesno = 0, stevecDol = 0;
if (grid[vrstica][stolpec] == 99) return 1;
if (vrstica > N ||stolpec > N) return 0;
if (stolpec == N || vrstica == N) return 1;
if (stevilopoti[vrstica][stolpec] != 0) return stevilopoti[vrstica][stolpec];
stevecDesno += navigacija(vrstica, stolpec+1);
stevecDol += navigacija(vrstica+1, stolpec);
stevilopoti[vrstica][stolpec] = stevecDesno + stevecDol;
return stevecDesno + stevecDol;
/* if (stolpec == N-1)
{
stevecDol += navigacija(vrstica+1, stolpec);
return stevecDesno+stevecDol;
}
if (vrstica == N-1)
{
stevecDesno += navigacija(vrstica, stolpec+1);
return stevecDesno+stevecDol;
}
if (stevilopoti[vrstica][stolpec] != 0) return stevilopoti[vrstica][stolpec];
stevecDesno += navigacija(vrstica, stolpec+1);
stevecDol += navigacija(vrstica+1, stolpec);
stevilopoti[vrstica][stolpec] = stevecDesno+stevecDol;
return stevecDesno+stevecDol;*/
}
void Dynamic() {
const int gridSize = N;
long gridy[gridSize+1][gridSize+1];
for (int i = 0; i < gridSize; i++) {
gridy[i][gridSize] = 1;
gridy[gridSize][i] = 1;
}
for (int i = gridSize - 1; i >= 0; i--) {
for (int j = gridSize - 1; j >= 0; j--) {
gridy[i][j] = gridy[i+1][j] + gridy[i][j+1];
}
}
printf("Dynamic: In a {%d}x{%d} grid there are {%ld} possible paths.\n", gridSize, gridSize, *gridy[0,0]);
}
void Combinatorics() {
const int gridSize = N;
long paths = 1;
for (int i = 0; i < gridSize; i++) {
paths *= (2 * gridSize) - i;
paths /= i + 1;
}
printf("Combinatorics: In a {%d}x{%d} grid there are {%ld} possible paths.\n", gridSize, gridSize, paths);
}
int main()
{
// Kombinatorika
/*
const int gridSize = N;
long paths = 1;
for (int i = 0; i < gridSize; i++) {
paths *= (2 * gridSize) - i;
paths /= i + 1;
}
printf("%ld\n", paths);*/
Combinatorics();
Dynamic();
// Sprehajanje
grid [N][N] = 99;
printf("MOJA RESITEV KI KONCNO DELA: V {%d}x{%d} sahovnici obstaja {%ld} povezav\n",N, N, navigacija(0, 0));
return 0;
}
|
the_stack_data/215767515.c | #include <linux/version.h>
#if LINUX_VERSION_CODE < KERNEL_VERSION(4,0,0)
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/socket.h>
#include <linux/udp.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <net/ip_tunnels.h>
#include <net/udp.h>
#include <net/udp_tunnel.h>
#include <net/net_namespace.h>
int rpl_udp_sock_create(struct net *net, struct udp_port_cfg *cfg,
struct socket **sockp)
{
int err;
struct socket *sock = NULL;
#if IS_ENABLED(CONFIG_IPV6)
if (cfg->family == AF_INET6) {
struct sockaddr_in6 udp6_addr;
err = sock_create_kern(AF_INET6, SOCK_DGRAM, 0, &sock);
if (err < 0)
goto error;
sk_change_net(sock->sk, net);
udp6_addr.sin6_family = AF_INET6;
memcpy(&udp6_addr.sin6_addr, &cfg->local_ip6,
sizeof(udp6_addr.sin6_addr));
udp6_addr.sin6_port = cfg->local_udp_port;
err = kernel_bind(sock, (struct sockaddr *)&udp6_addr,
sizeof(udp6_addr));
if (err < 0)
goto error;
if (cfg->peer_udp_port) {
udp6_addr.sin6_family = AF_INET6;
memcpy(&udp6_addr.sin6_addr, &cfg->peer_ip6,
sizeof(udp6_addr.sin6_addr));
udp6_addr.sin6_port = cfg->peer_udp_port;
err = kernel_connect(sock,
(struct sockaddr *)&udp6_addr,
sizeof(udp6_addr), 0);
}
if (err < 0)
goto error;
} else
#endif
if (cfg->family == AF_INET) {
struct sockaddr_in udp_addr;
err = sock_create_kern(AF_INET, SOCK_DGRAM, 0, &sock);
if (err < 0)
goto error;
sk_change_net(sock->sk, net);
udp_addr.sin_family = AF_INET;
udp_addr.sin_addr = cfg->local_ip;
udp_addr.sin_port = cfg->local_udp_port;
err = kernel_bind(sock, (struct sockaddr *)&udp_addr,
sizeof(udp_addr));
if (err < 0)
goto error;
if (cfg->peer_udp_port) {
udp_addr.sin_family = AF_INET;
udp_addr.sin_addr = cfg->peer_ip;
udp_addr.sin_port = cfg->peer_udp_port;
err = kernel_connect(sock,
(struct sockaddr *)&udp_addr,
sizeof(udp_addr), 0);
if (err < 0)
goto error;
}
} else {
return -EPFNOSUPPORT;
}
*sockp = sock;
return 0;
error:
if (sock) {
kernel_sock_shutdown(sock, SHUT_RDWR);
sk_release_kernel(sock->sk);
}
*sockp = NULL;
return err;
}
EXPORT_SYMBOL_GPL(rpl_udp_sock_create);
void rpl_setup_udp_tunnel_sock(struct net *net, struct socket *sock,
struct udp_tunnel_sock_cfg *cfg)
{
struct sock *sk = sock->sk;
/* Disable multicast loopback */
inet_sk(sk)->mc_loop = 0;
rcu_assign_sk_user_data(sk, cfg->sk_user_data);
udp_sk(sk)->encap_type = cfg->encap_type;
udp_sk(sk)->encap_rcv = cfg->encap_rcv;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,9,0)
udp_sk(sk)->encap_destroy = cfg->encap_destroy;
#endif
udp_tunnel_encap_enable(sock);
}
EXPORT_SYMBOL_GPL(rpl_setup_udp_tunnel_sock);
void ovs_udp_gso(struct sk_buff *skb)
{
int udp_offset = skb_transport_offset(skb);
struct udphdr *uh;
uh = udp_hdr(skb);
uh->len = htons(skb->len - udp_offset);
}
EXPORT_SYMBOL_GPL(ovs_udp_gso);
void ovs_udp_csum_gso(struct sk_buff *skb)
{
struct iphdr *iph = ip_hdr(skb);
int udp_offset = skb_transport_offset(skb);
ovs_udp_gso(skb);
/* csum segment if tunnel sets skb with csum. The cleanest way
* to do this just to set it up from scratch. */
skb->ip_summed = CHECKSUM_NONE;
udp_set_csum(true, skb, iph->saddr, iph->daddr,
skb->len - udp_offset);
}
EXPORT_SYMBOL_GPL(ovs_udp_csum_gso);
int rpl_udp_tunnel_xmit_skb(struct rtable *rt, struct sk_buff *skb,
__be32 src, __be32 dst, __u8 tos, __u8 ttl,
__be16 df, __be16 src_port, __be16 dst_port,
bool xnet, bool nocheck)
{
struct udphdr *uh;
__skb_push(skb, sizeof(*uh));
skb_reset_transport_header(skb);
uh = udp_hdr(skb);
uh->dest = dst_port;
uh->source = src_port;
uh->len = htons(skb->len);
udp_set_csum(nocheck, skb, src, dst, skb->len);
return iptunnel_xmit(skb->sk, rt, skb, src, dst, IPPROTO_UDP,
tos, ttl, df, xnet);
}
EXPORT_SYMBOL_GPL(rpl_udp_tunnel_xmit_skb);
void rpl_udp_tunnel_sock_release(struct socket *sock)
{
rcu_assign_sk_user_data(sock->sk, NULL);
kernel_sock_shutdown(sock, SHUT_RDWR);
sk_release_kernel(sock->sk);
}
EXPORT_SYMBOL_GPL(rpl_udp_tunnel_sock_release);
#endif /* Linux version < 4.0 */
|
the_stack_data/100139653.c |
#include <stdio.h>
void a() { printf("Found a\n"); }
void b() { printf("Found b\n"); }
int main() {
b();
a();
b();
printf("Done!\n");
return 0;
}
|
the_stack_data/176706414.c | int myLibFunction() {
return 42;
}
|
the_stack_data/248579811.c | #include<stdio.h>
int main()
{
int a,b=2;
for(a=1;a<=6;a++)
{
a=a+2;
b=b+a-4;
}
printf("%d",b);
return 0;
}
//o/p
//3
|
the_stack_data/14200988.c | /**
* Ben Ziemann
* Implementation of the "tee" command
* for Software Systems Spring 2019 HW3
*
* Reflection:
* Once I stopped being overwhelmed and made the mental call to stop diving down the rabbit hole of terms and just try something
* things went a lot of smoother. Now with more confidence on my side I made a quick list of the componenets I needed and tried to
* avoid Googling everything that I didn't immediately know to avoid sidetracking/bogging myself down in uncessary mountains of information,
* that while interesting, proved unncessary for the task or would paralyze me thinking there is more to this than
* there actually was. I think the best thing I did for myself was spend 10 or so minutes just trying out the 'tee' command
* in my terminal to understand what everything did.
*
* I think the biggest thing that slowed me down was immediately getting overwhelmed
* by trying to dive too deep into what every word meant on the command page and trying to think about everything
* all at once rather than just try one thing at a time.
*
* Next time I will: -Start the assignment earlier so the initial feeling of overwhelmingness is so paralyzing
* -Start the assignment earlier so I can try the optional part
* -Try going at it earlier on, it's unlikely I will be fully prepared no matter how much reading I do,
especially in an assignment where we are supposed to be learning new things anyways
*
* My code differs from the professional code in that they use a lot more libraries and header files, probably
* to speed operations up and allow for more and complex outputs.
* Additionally they also use ALOT more error checking (see my non-implementation of -p), taking
* advantage of enumeration to make this clean. It's also just generally cleaner.
* Finally they have a full implementation :P
*
*/
#include <stdio.h>
#include <stdlib.h>
//For getopt and arugment parsing
#include <unistd.h>
#define MAX_FILES 5
#define MAX_BUFFER 100
/**
* Implementation of 'tee' command
*
* int argc - number of arguments
* char *argv[] - the arguments, includes ./ and any flags
*/
int main (int argc, char *argv[]){
int argument;
int i;
short argOffset;
//0-overwite files, 1-append to files
short appending = 0;
char *input[MAX_BUFFER];
FILE *myFiles[MAX_FILES];
//Error check
if(argc > MAX_FILES+1){
printf("Too many files and flags! Please use one flag at most and %i files or less!\n", MAX_FILES);
return 1;
}
//Go through arguments
//Wondered about --arguments (help, version), didn't really look into them b/c time constraints
//Instead just made them characters
while((argument = getopt(argc, argv, "aiphv")) != -1){
switch(argument){
case 'a':
appending = 1;
break;
case 'i':
//Optional
printf("Optional - not implemented.\n");
return 1;
break;
case 'p':
printf("Not implemented\n");
return 1;
break;
case 'h':
printf("Use CTRL+D to end the program.\n");
printf("Use -a [FILE] to append to given files.\nUse no flags [FILE] to overwrite given files.\n");
printf("Use -v to see the creator info and version.\nUse -h to see this screen again.\n");
printf("Flag -p is not implemented. \nFlag -i is not implemented.\n");
return 1;
break;
case 'v':
printf("This tee command implementation was made by Ben Ziemann for Software Systems Spring 2019.\nLast updated 2/22/19.\n");
return 1;
break;
default:
printf("Not a valid argument. Please see -h for help.");
return 1;
}
}
//Open file(s) with correct intent
//Program assumes user only use 1 flag max (-a), otherwise none
//Real tee command only uses last flag
//./tee and whether appending affects # of arguments
if(appending){
argOffset=2;
for(i=0; i < argc-argOffset; i++){
myFiles[i] = fopen(argv[i+argOffset], "a+");
}
}
else{
argOffset=1;
for(i=0; i < argc-argOffset; i++){
myFiles[i] = fopen(argv[i+argOffset], "w+");
}
}
printf("Pleae end the program with CTRL+D, NOT CTRL+C to properly save input.\n");
//Read user input, write to file(s)
//Kill with CTRL-D
while(fgets(input, MAX_BUFFER, stdin) != NULL){
fputs(input, stdout);
for(i = 0; i < argc-argOffset; i++){
fputs(input, myFiles[i]);
}
}
//Cleanup
for(i=0; i<argc-argOffset; i++){
fclose(myFiles[i]);
}
printf("Files written!\n");
return 0;
} |
the_stack_data/64117.c | /*
gcc -std=c17 -lc -lm -pthread -o ../_build/c/language_operator_logical.exe ./c/language_operator_logical.c && (cd ../_build/c/;./language_operator_logical.exe)
https://en.cppreference.com/w/c/language/operator_logical
*/
#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
bool b = !(2+2 == 4); // not true
printf("!(2+2==4) = %s\n", b ? "true" : "false");
int n = isspace('a'); // zero if 'a' is a space, nonzero otherwise
int x = !!n; // "bang-bang", common C idiom for mapping integers to [0,1]
// (all non-zero values become 1)
char *a[2] = {"nonspace", "space"};
printf("%s\n", a[x]); // now x can be safely used as an index to array of 2 ints
}
|
the_stack_data/43651.c | unsigned char chicken_left_data[97] =
{
0x10,0x10,0x10,0x10,0x10,0x05,0x02,0x4b,0x48,0x09,0x04,0x04,0x4b,0x4b,0x4b,0x48,0x08,0x03,0x05,0x14,0x4b,0x0f,0x4b,0x48,0x08,0x04,0x04,0x4b,0x4b,0x4d,0x48,0x03,
0x01,0x48,0x04,0x05,0x08,0x48,0x4d,0x4d,0x48,0x48,0x48,0x4d,0x48,0x03,0x05,0x08,0x48,0x4d,0x4d,0x4d,0x4d,0x48,0x4d,0x48,0x03,0x05,0x08,0x48,0x4d,0x4d,0x48,0x48,
0x4d,0x4d,0x48,0x03,0x06,0x06,0x48,0x4d,0x4d,0x4d,0x4d,0x48,0x04,0x07,0x04,0x48,0x48,0x48,0x48,0x05,0x08,0x02,0x0f,0x14,0x06,0x07,0x03,0x0f,0x0f,0x14,0x06,0x10,
0x10
};
|
the_stack_data/57949679.c | #include<stdio.h>
main()
{
float p,t,r,si;
printf("Enter the principal, time and rate of interest \n");
scanf("%f%f%f",&p,&t,&r);
si=(p*t*r)/100;
printf("Simple Interest is %f",si);
}
|
the_stack_data/971787.c | #if 0
2.读入用户输入的两个字符串,分别存储到char s1[80] 和 char s2[80],
比较这两个字符串大小
#endif
#include <stdio.h>
int main()
{
char s1[80], s2[80];
int i;
printf("输入第一个字符串:");
i = 0;
do {
s1[i] = getchar();
} while (s1[i++] != '\n' && i < 80);
s1[i-1] = '\0';
printf("输入第二个字符串:");
i = 0;
do {
s2[i] = getchar();
} while (s2[i++] != '\n' && i < 80);
s2[i-1] = '\0';
for (int j = 0; j < 80; j++)
{
if (s1[j] > s2[j])
{
printf("1 > 2\n");
break;
}
else if (s1[j] < s2[j])
{
printf("1 < 2\n");
break;
}
else
{
if (s1[j] != '\0' && s2[j] != '\0')
continue;
printf("1 = 2\n");
break;
}
}
return 0;
}
|
the_stack_data/192329882.c | /**/
#include <stdio.h>
#include <math.h>
int main () {
float a;
float b;
float c;
float d;
float perc;
char grade;
printf("Enter thresholds for A, B, C, D\nin that order, decreasing percentages > ");
scanf("%f %f %f %f", &a, &b, &c, &d);
printf("Thank you. Now enter student score (percent) >");
scanf("%f", &perc);
if (perc > a) {
grade = 'A';
} else if (perc > b) {
grade = 'B';
} else if (perc > c) {
grade = 'C';
} else if (perc > d) {
grade = 'D';
} else {
grade = 'F';
}
printf("Student has an %c grade\n", grade);
return 0;
}
|
the_stack_data/84451.c | /*
* http://br.spoj.com/problems/SOMA/
*/
#include <stdio.h>
int main()
{
int n, x, soma = 0;
scanf("%d", &n);
while (n > 0) {
scanf("%d", &x);
soma += x;
n--;
}
printf("%d", soma);
return 0;
} |
the_stack_data/117327685.c | /* -*- C -*- */
/*
* Copyright (c) 2013-2020 Seagate Technology LLC and/or its Affiliates
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For any questions about this software or licensing,
* please email [email protected] or [email protected].
*
*/
void m0_be_ut_io(void)
{
}
/*
* Local variables:
* c-indentation-style: "K&R"
* c-basic-offset: 8
* tab-width: 8
* fill-column: 80
* scroll-step: 1
* End:
*/
/*
* vim: tabstop=8 shiftwidth=8 noexpandtab textwidth=80 nowrap
*/
|
the_stack_data/12991.c | /* $XConsortium: sharedlib.c,v 1.6 94/04/17 20:13:34 kaleb Exp $ */
/*
Copyright (c) 1991, 1994 X Consortium
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
*/
#if defined(SUNSHLIB) && !defined(SHAREDCODE)
#include <X11/IntrinsicP.h>
#include <X11/Xaw3d/AsciiSinkP.h>
#include <X11/Xaw3d/AsciiSrcP.h>
#include <X11/Xaw3d/AsciiTextP.h>
#include <X11/Xaw3d/MultiSinkP.h>
#include <X11/Xaw3d/MultiSrcP.h>
#include <X11/Xaw3d/BoxP.h>
#include <X11/Xaw3d/CommandP.h>
#include <X11/Xaw3d/DialogP.h>
#include <X11/Xaw3d/FormP.h>
#include <X11/Xaw3d/GripP.h>
#include <X11/Xaw3d/LabelP.h>
#include <X11/Xaw3d/ListP.h>
#include <X11/Xaw3d/MenuButtoP.h>
#include <X11/Xaw3d/PanedP.h>
#include <X11/Xaw3d/PannerP.h>
#include <X11/Xaw3d/PortholeP.h>
#include <X11/Xaw3d/RepeaterP.h>
#include <X11/Xaw3d/ScrollbarP.h>
#include <X11/Xaw3d/SimpleP.h>
#include <X11/Xaw3d/SimpleMenP.h>
#include <X11/Xaw3d/SmeP.h>
#include <X11/Xaw3d/SmeThreeDP.h>
#include <X11/Xaw3d/SmeBSBP.h>
#include <X11/Xaw3d/SmeLineP.h>
#include <X11/Xaw3d/StripCharP.h>
#include <X11/Xaw3d/TextP.h>
#include <X11/Xaw3d/TextSinkP.h>
#include <X11/Xaw3d/TextSrcP.h>
#include <X11/Xaw3d/ThreeDP.h>
#include <X11/Xaw3d/ToggleP.h>
#include <X11/Xaw3d/TreeP.h>
#include <X11/VendorP.h>
#include <X11/Xaw3d/ViewportP.h>
extern AsciiSinkClassRec asciiSinkClassRec;
WidgetClass asciiSinkObjectClass = (WidgetClass)&asciiSinkClassRec;
extern AsciiSrcClassRec asciiSrcClassRec;
WidgetClass asciiSrcObjectClass = (WidgetClass)&asciiSrcClassRec;
extern AsciiTextClassRec asciiTextClassRec;
WidgetClass asciiTextWidgetClass = (WidgetClass)&asciiTextClassRec;
#ifdef ASCII_STRING
extern AsciiStringClassRec asciiStringClassRec;
WidgetClass asciiStringWidgetClass = (WidgetClass)&asciiStringClassRec;
#endif
#ifdef ASCII_DISK
extern AsciiDiskClassRec asciiDiskClassRec;
WidgetClass asciiDiskWidgetClass = (WidgetClass)&asciiDiskClassRec;
#endif
extern MultiSinkClassRec multiSinkClassRec;
WidgetClass multiSinkObjectClass = (WidgetClass)&multiSinkClassRec;
extern MultiSrcClassRec multiSrcClassRec;
WidgetClass multiSrcObjectClass = (WidgetClass)&multiSrcClassRec;
extern BoxClassRec boxClassRec;
WidgetClass boxWidgetClass = (WidgetClass)&boxClassRec;
extern CommandClassRec commandClassRec;
WidgetClass commandWidgetClass = (WidgetClass) &commandClassRec;
extern DialogClassRec dialogClassRec;
WidgetClass dialogWidgetClass = (WidgetClass)&dialogClassRec;
extern FormClassRec formClassRec;
WidgetClass formWidgetClass = (WidgetClass)&formClassRec;
extern GripClassRec gripClassRec;
WidgetClass gripWidgetClass = (WidgetClass) &gripClassRec;
extern LabelClassRec labelClassRec;
WidgetClass labelWidgetClass = (WidgetClass)&labelClassRec;
extern ListClassRec listClassRec;
WidgetClass listWidgetClass = (WidgetClass)&listClassRec;
extern MenuButtonClassRec menuButtonClassRec;
WidgetClass menuButtonWidgetClass = (WidgetClass) &menuButtonClassRec;
extern PanedClassRec panedClassRec;
WidgetClass panedWidgetClass = (WidgetClass) &panedClassRec;
WidgetClass vPanedWidgetClass = (WidgetClass) &panedClassRec;
extern PannerClassRec pannerClassRec;
WidgetClass pannerWidgetClass = (WidgetClass) &pannerClassRec;
extern PortholeClassRec portholeClassRec;
WidgetClass portholeWidgetClass = (WidgetClass) &portholeClassRec;
extern RepeaterClassRec repeaterClassRec;
WidgetClass repeaterWidgetClass = (WidgetClass) &repeaterClassRec;
extern ScrollbarClassRec scrollbarClassRec;
WidgetClass scrollbarWidgetClass = (WidgetClass)&scrollbarClassRec;
extern SimpleClassRec simpleClassRec;
WidgetClass simpleWidgetClass = (WidgetClass)&simpleClassRec;
extern SimpleMenuClassRec simpleMenuClassRec;
WidgetClass simpleMenuWidgetClass = (WidgetClass)&simpleMenuClassRec;
extern SmeClassRec smeClassRec;
WidgetClass smeObjectClass = (WidgetClass) &smeClassRec;
extern smeThreeDClassRec smeThreeDClassRec;
WidgetClass smeThreeDObjectClass = (WidgetClass) &smeThreeDClassRec;
WidgetClass smeBSBObjectClass = (WidgetClass) &smeBSBClassRec;
extern SmeLineClassRec smeLineClassRec;
WidgetClass smeLineObjectClass = (WidgetClass) &smeLineClassRec;
extern StripChartClassRec stripChartClassRec;
WidgetClass stripChartWidgetClass = (WidgetClass) &stripChartClassRec;
extern TextClassRec textClassRec;
WidgetClass textWidgetClass = (WidgetClass)&textClassRec;
unsigned long FMT8BIT = 0L;
unsigned long XawFmt8Bit = 0L;
unsigned long XawFmtWide = 0L;
extern TextSinkClassRec textSinkClassRec;
WidgetClass textSinkObjectClass = (WidgetClass)&textSinkClassRec;
extern TextSrcClassRec textSrcClassRec;
WidgetClass textSrcObjectClass = (WidgetClass)&textSrcClassRec;
extern ThreeDClassRec threeDClassRec;
WidgetClass threeDClass = (WidgetClass)&threeDClassRec;
extern ToggleClassRec toggleClassRec;
WidgetClass toggleWidgetClass = (WidgetClass) &toggleClassRec;
extern TreeClassRec treeClassRec;
WidgetClass treeWidgetClass = (WidgetClass) &treeClassRec;
extern VendorShellClassRec vendorShellClassRec;
WidgetClass vendorShellWidgetClass = (WidgetClass) &vendorShellClassRec;
extern ViewportClassRec viewportClassRec;
WidgetClass viewportWidgetClass = (WidgetClass)&viewportClassRec;
#endif /* SUNSHLIB */
|
the_stack_data/43889034.c | #include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
main()
{
int canal1[2];
int canal2[2];
pid_t pid1, pid2;
int y=0;
int x=5;
int z;
if ( pipe(canal1) == -1 ){ printf("Erro pipe()"); return -1; }
if ( pipe(canal2) == -1 ){ printf("Erro pipe()"); return -1; }
pid1=fork();
if ( pid1 == 0 )
{
read(canal1[0],&y,sizeof(int));
printf("Valor recebido pelo Filho1 do Filho2=%d\n",y); fflush(stdout);
y=y*2;
write(canal2[1],&y,sizeof(int));
close(canal2[1]);
}
else
if (pid1 > 0 )
{
pid2=fork();
if ( pid2 == 0 )
{
write(canal1[1],&x,sizeof(int));
read(canal2[0],&x,sizeof(int));
printf("Valor recebido pelo Filho2 do Filho1=%d\n",x); fflush(stdout);
}
else
if (pid2 > 0 )
{
wait(&z);
wait(&z);
}
}
exit(0);
}
|
the_stack_data/274941.c | #include <stdlib.h>
#include <stdint.h>
uint64_t
rm_hash_64(uint64_t key)
{
key = (~key) + (key << 21);
key = key ^ (key >> 24);
key = (key + (key << 3)) + (key << 8);
key = key ^ (key >> 14);
key = (key + (key << 2)) + (key << 4);
key = key ^ (key >> 28);
key = key + (key << 31);
return (key);
}
size_t
rm_hash (void * data, size_t hash_size) {
return ((size_t) rm_hash_64 ((uint64_t)data) % hash_size);
}
|
the_stack_data/775294.c | /**
* @author : ashwek
* @date : 26/12/2018
*/
#include<stdio.h>
void main(){
int n, i, j, s;
printf("Enter n = ");
scanf("%d", &n);
//Upper-Half
for(i=1; i <=n; i++){
for(j=i; j<=n; j++) //Left Triangle
printf("* ");
for(s=1; s<i; s++) //Space
printf(" ");
for(j=i; j<=n; j++) //Right Triangle
printf("* ");
printf("\n");
}
//Lower-Half
for(i=1; i <=n; i++){
for(j=1; j<=i; j++) //Left Triangle
printf("* ");
for(s=1; s<=(n-i); s++) //Space
printf(" ");
for(j=1; j<=i; j++) //Right Triangle
printf("* ");
printf("\n");
}
}
|
the_stack_data/68887391.c | //This program is done by
//Student name:: Santosh Kumar Kalwar
//Student number:: 0331927
//Reference taken from
//http://www.it.lut.fi/kurssit/07-08/CT30A5000/home-exam.html
//http://www.faqs.org/rfcs/rfc959.html
//Stevens, W.: TCP/IP Illustrated Volume 1, page 419
//http://beej.us/guide/bgnet/output/htmlsingle/bgnet.html
//Include Files
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <math.h>
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>
//FTP commands
#define GET 1
#define PUT 2
#define OPEN 3
#define CLOSE 4
#define LS 5
#define CD 6
#define QUIT 7
#define CDUP 8
#define PASV 9
//Function declarations
int ftpfun(int,int,int,struct sockaddr_in);
int parsfun(char*);
int openfun(int,struct sockaddr_in);
int getfun(int,int,int,char*,int,struct sockaddr_in);
int putfun(int,int,int,char*,int,struct sockaddr_in);
int closefun(int);
int listfun(int,int,int,char*,int,struct sockaddr_in);
int cdfun(int,char*);
int cdupfun(int);
int passivefun(int,struct sockaddr_in*);
int receive(int,char*);
int dsoket(int,int,int);
int pdsocket(int,int,struct sockaddr_in*);
//Main Program Starts here
int main(int argc, char** argv){
int n,port,dport,sfd=-1,dsfd,l;
struct sockaddr_in o,od;
struct hostent *hp;
//Check parameters
if((argc!=7)||(strcmp("-p",argv[1]))||(strcmp("-P",argv[3]))||(strcmp("-h",argv[5]))){
printf("Use: %s -p <FTP server port> -P <data transfer port> -h <ftp server address>\n",argv[0]);
return -1;
}
//Check port
port=atoi(argv[2]);
if(port<1){
printf("Incorrect FTP port\n");
return -1;
}
//Check dataport
dport=atoi(argv[4]);
if(dport<20){
printf("Incorrect data transfer port\n");
return -1;
}else if(dport==port){
printf("FTP server port and data transfer port can not be same\n");
return -1;
}
//Check address
hp=gethostbyname(argv[6]);
if(hp==NULL){
printf("Incorrect FTP server address\n");
return h_errno;
}
//Set IP-settings
memset(&o,0,sizeof(struct sockaddr_in));
o.sin_family=AF_INET;
memcpy(&o.sin_addr.s_addr,hp->h_addr,hp->h_length);
o.sin_port=htons(port);
//Open datasocket
dsfd=socket(AF_INET,SOCK_STREAM,0);
if(dsfd<0){
printf("Error while opening datasocket\n");
return -2;
}
//Set datasocket IP-settings
memset(&od,0,sizeof(struct sockaddr_in));
od.sin_family=AF_INET;
od.sin_addr.s_addr=INADDR_ANY;
od.sin_port=htons(dport);
//Allow reuse of datasocket
n=1;
if(setsockopt(dsfd,SOL_SOCKET,SO_REUSEADDR,(void*)&n,sizeof(n))==-1){
perror("Error in setsockopt");
return errno;
}
//Bind datasocket
l=sizeof(od);
n=bind(dsfd,(struct sockaddr*)&od,l);
if(n<0){
printf("Error in setsockopt\n");
return errno;
}
//Listen datasocket
n=listen(dsfd,10);
if(n<0){
perror("Error in listen function");
return errno;
}
//Welcome Screen, interactivity
printf("\n*******************************************************************");
printf("\t\n Welcome to File Transfer Protocol (FTP Client) based on RFC 959 ");
printf("\t\n Write open,to open the connection. ");
printf("\t\n Give default Username and Password ");
printf("\t\n Client recognizes following commands- ");
printf("\t\n Commands are: get, put, ls, cd, cd.., open, close, quit, passive");
printf("\t\n Wish you have nice, File transfer session !!! ");
printf("\n*******************************************************************\n");
//Begin ftp-subprogram
l=ftpfun(sfd,dsfd,dport,o);
//Close socket only if ftp-subprogram returned an error
if(l!=0){
n=close(sfd);
if(n<0){
printf("Error while closing socket\n");
}
}
//Close datasocket
n=close(dsfd);
if(n<0){
printf("Error while cosing datasocket\n");
}
return l;
}
//FTP-subprogram
//Parameters: socket, datasocket, data transfer port, send address
int ftpfun(int sfd, int dsfd, int dport,struct sockaddr_in o){
int n,continu=1,passive=0;
fd_set rfds;
char buf[2049];
struct sockaddr_in da;
//MAIN LOOP
while(continu){
memset(buf,0,2049);
//Select-lists
FD_ZERO(&rfds);
FD_SET(0,&rfds);
n=select(1,&rfds,NULL,NULL,NULL);
if(n<0){
perror("Error in select function\n");
return errno;
}
//Read keyboard command
if(FD_ISSET(0,&rfds)){
n=read(0,buf,2048);
if(n<0){
printf("Error while reading keyboard\n");
return errno;
}
//Parse command
n=parsfun(buf);
switch(n){
case GET: //Download
if(sfd==-1){
printf("No connection to server\n");
}else{
if(passive){
dsfd=pdsocket(sfd,dsfd,&da);
if(dsfd<0){
return dsfd;
}
}
n=getfun(sfd,dsfd,dport,buf,passive,da);
if(n!=0){
return n;
}
//Select new data transfer port
dport++;
if(dport==65536){
dport=60000;
}
//Open new data transfer socket
dsfd=dsoket(dsfd,dport,passive);
if(dsfd<0){
return dsfd;
}
}
break;
case PUT: //Upload
if(sfd==-1){
printf("No connection to server\n");
}else{
if(passive){
dsfd=pdsocket(sfd,dsfd,&da);
if(dsfd<0){
return dsfd;
}
}
n=putfun(sfd,dsfd,dport,buf,passive,da);
if(n!=0){
return n;
}
//Select new data transfer port
dport++;
if(dport==65536){
dport=60000;
}
//Open new data transfer socket
dsfd=dsoket(dsfd,dport,passive);
if(dsfd<0){
return dsfd;
}
}
break;
case LS: //Directory listing
if(sfd==-1){
printf("No connection to server\n");
}else{
if(passive){
dsfd=pdsocket(sfd,dsfd,&da);
if(dsfd<0){
return dsfd;
}
}
n=listfun(sfd,dsfd,dport,buf,passive,da);
if(n<0){
return n;
}
//Select new data transfer port
dport++;
if(dport==65536){
dport=60000;
}
//Open new data transfer socket
dsfd=dsoket(dsfd,dport,passive);
if(dsfd<0){
return dsfd;
}
}
break;
case OPEN:
//Open socket if necessary
if(sfd==-1){
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0){
printf("Error while opening socket\n");
return -2;
}
}
//Open connection to the server
n=openfun(sfd,o);
//1==error
if(n==1){
n=closefun(sfd);
if(n!=0){
return n;
}else{
//Mark socket as closed
sfd=-1;
}
}else if(n<0){
return n;
}
break;
case CLOSE:
//Close connection
if(sfd==-1){
printf("No connection to server\n");
}else{
n=closefun(sfd);
if(n!=0){
return n;
}else{
//Mark socket closed
sfd=-1;
}
}
break;
case QUIT:
//Quit and close socket
if(sfd!=-1){
n=closefun(sfd);
if(n!=0){
return n;
}else{
sfd=-1;
}
}
continu=0;
break;
case CD: //Change directory
if(sfd==-1){
printf("No connection to server\n");
}else{
n=cdfun(sfd,buf);
if(n!=0){
return n;
}
}
break;
case CDUP: //Move one directory level up
if(sfd==-1){
printf("No connection to server\n");
}else{
n=cdupfun(sfd);
if(n!=0){
return n;
}
}
break;
case PASV: //Enter passive mode
if(sfd==-1){
printf("No contact with server\n");
}else{
if(!passive){
passive=1;
printf("Entering passive mode\n");
}else{
passive=0;
printf("Entering active mode\n");
}
}
break;
default: //Error in command
printf("Incorrect command\n");
}
}
}
return 0;
}
//Parsfun-subprogram
//Parses the command user gave
//Parameters: the command user gave
//Return value: 0 if error, positive value othervise
int parsfun(char* buf){
if(!strncmp(buf,"get ",4)) return GET;
else if(!strncmp(buf,"put ",4)) return PUT;
else if((!strcmp(buf,"ls\n")||(!strncmp(buf,"ls ",3)))) return LS;
else if(!strcmp(buf,"open\n")) return OPEN;
else if(!strcmp(buf,"close\n")) return CLOSE;
else if(!strcmp(buf,"quit\n")) return QUIT;
else if((!strcmp(buf,"cd..\n"))||(!strcmp(buf,"cd ..\n"))) return CDUP;
else if(!strncmp(buf,"cd ",3)) return CD;
else if(!strcmp(buf,"passive\n")) return PASV;
else return 0;
}
//Getfun-function
//Download desired file from server
//Parameters: socket, data transfer socket, data transfer port, command the user gave, passive mode
//Return value: 0 in normal case
int getfun(int sfd,int dsfd,int dport,char* par,int passive,struct sockaddr_in da){
int i,dfd,fd,continu=1;
unsigned int n;
char buf[2049],temp[2049];
struct hostent *hp;
struct sockaddr_in o;
//Remove the new line from end of the string
par[strlen(par)-1]='\0';
//Open file for writing
fd=open(&par[4],O_WRONLY|O_CREAT|O_EXCL);
if(fd<0){
if(errno==EEXIST){
printf("File already exist\n");
return 0;
}else{
printf("Error while opening file\n");
return errno;
}
}
//Send TYPE I (binary)
memset(buf,0,2049);
sprintf(buf,"TYPE I\r\n");
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n<0){
printf("Error in data transfer\n");
return n;
}
//Receive acknowlegdement
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check receive code
if(strncmp(buf,"200",3)){
printf("TYPE-Type command failed\n");
close(fd);
return 0;
}
memset(buf,0,2049);
memset(temp,0,2049);
if(!passive){
//Check home address
n=gethostname(buf,2048);
if(n<0){
perror("Error in gethostname function");
close(fd);
return errno;
}
//Convert address to IP-number
hp=gethostbyname(buf);
if(hp==NULL){
herror("Error in gethostbyname function\n");
close(fd);
return h_errno;
}
//Convert address to char-type and replace dots with commas (needed for the PORT-command)
strcpy(temp,inet_ntoa(*((struct in_addr*)hp->h_addr)));
for(i=0;i<strlen(temp);i++){
if(temp[i]=='.'){
temp[i]=',';
}
}
//PORT <ip (comma separated)>,<floor(dataport/256)>,<dataport%256>
memset(buf,0,2049);
sprintf(buf,"PORT %s,%d,%d\r\n",temp,(int)floor(dport/256),(int)dport%256);
//Send PORT-command
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
close(fd);
return -1;
}
//Receive acknowledgement
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
close(fd);
return n;
}
//Check that return code was 200
if(strncmp(buf,"200",3)){
printf("PORT-PORT command failed\n");
close(fd);
return 0;
}
}
//Send RETR-command
memset(buf,0,2049);
sprintf(buf,"RETR%s\r\n",&par[3]);
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
close(fd);
return -1;
}
//Open passive data connection
if(passive){
n=connect(dsfd,(struct sockaddr*)&da,sizeof(struct sockaddr_in));
if(n<0){
printf("Error in creating passive data connection\n");
return n;
}
dfd=dsfd;
printf("Passive data connection opened\n");
}
//Receive acknowledgement
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
close(fd);
return n;
}
//Check that return code was 150, otherwise remove file
if(strncmp(buf,"150",3)){
n=remove(&par[4]);
if(n<0){
perror("Error while deleting file");
return errno;
}
//If return code was 550 (file not found), return 0
if(!strncmp(buf,"550",3)){
return 0;
}else{
//Otherwise quit program
printf("Error while loading file\n");
return -1;
}
}
//Open active data connection
memset(buf,0,2049);
if(!passive){
n=sizeof(struct sockaddr_in);
dfd=accept(dsfd,(struct sockaddr*)&o,&n);
if(dfd<0){
printf("Error while connecting data connection\n");
close(fd);
return -3;
}
}
printf("Data connection created\n");
//Receive file
while(continu){
memset(buf,0,2049);
n=recv(dfd,buf,2048,0);
if(n<0){
printf("Error in data transfer\n");
close(fd);
close(dfd);
return n;
}else if(n==0){
continu=0;
}
//Write buffer to disk
n=write(fd,buf,n);
if(n<0){
perror("Error while wrting file");
close(fd);
close(dfd);
return errno;
}
}
//Close file
n=close(fd);
if(n<0){
printf("Error while closing file\n");
return n;
}
//Close data connection
n=close(dfd);
if(n<0){
printf("Error while closing data connection\n");
return n;
}
//Receive acknowledgement
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check that return code was 226
if(strncmp(buf,"226",3)){
printf("Error while loading file\n");
return -1;
}
return 0;
}
//Putfun-subprogram
//Upload file to server
//Parameters: socket, data transfer socket, data transfer port, command user gave, passive mode, server address if passive mode
//Return value: 0 in normal case
int putfun(int sfd,int dsfd,int dport,char* par,int passive,struct sockaddr_in da){
int i,dfd,fd,continu=1,k;
unsigned int n;
char buf[2049],temp[2049];
struct hostent *hp;
struct sockaddr_in o;
int size;
double time;
struct timeval begin,end;
//Remove new line at the end
par[strlen(par)-1]='\0';
//Open file for reading
fd=open(&par[4],O_RDONLY);
if(fd<0){
printf("File already exist\n");
return 0;
}
//Send TYPE I (binary)
memset(buf,0,2049);
sprintf(buf,"TYPE I\r\n");
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n<0){
printf("Error in data transfer\n");
return n;
}
//Receive acknowlegdement
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check return code
if(strncmp(buf,"200",3)){
printf("TYPE-Type command failed\n");
close(fd);
return 0;
}
memset(buf,0,2049);
memset(temp,0,2049);
if(!passive){
//Check home address
n=gethostname(buf,2048);
if(n<0){
perror("Error in gethostname function");
close(fd);
return errno;
}
//Conver address to IP-number
hp=gethostbyname(buf);
if(hp==NULL){
herror("Error in gethostname function\n");
close(fd);
return h_errno;
}
//Convert address to char-type and replace dots with commas
strcpy(temp,inet_ntoa(*((struct in_addr*)hp->h_addr)));
for(i=0;i<strlen(temp);i++){
if(temp[i]=='.'){
temp[i]=',';
}
}
//PORT <ip (comma separated)>,<floor(port/256)>,<port%256>
memset(buf,0,2049);
sprintf(buf,"PORT %s,%d,%d\r\n",temp,(int)floor(dport/256),(int)dport%256);
//Send PORT command
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
close(fd);
return -1;
}
//Receive acknowlegdement
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
close(fd);
return n;
}
//Check that return code was 200
if(strncmp(buf,"200",3)){
printf("PORT-PORT command failed\n");
close(fd);
return 0;
}
}
//Send STOR-command
memset(buf,0,2049);
sprintf(buf,"STOR%s\r\n",&par[3]);
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
close(fd);
return -1;
}
//Open passive data connection
if(passive){
n=connect(dsfd,(struct sockaddr*)&da,sizeof(struct sockaddr_in));
if(n<0){
printf("Error opening passive data connection\n");
return n;
}
dfd=dsfd;
}
//Receive acknowlegdement
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
close(fd);
return n;
}
//Check that return code was 150
if(strncmp(buf,"150",3)){
close(fd);
return 0;
}
//Open active data connectionFTPClient.c
memset(buf,0,2049);
n=sizeof(struct sockaddr_in);
if(!passive){
dfd=accept(dsfd,(struct sockaddr*)&o,&n);
if(dfd<0){
printf("Error while connecting data connection\n");
close(fd);
return -3;
}
printf("Data connection created\n");
}
gettimeofday(&begin,NULL);
size=0;
//Send the file
while(continu){
memset(buf,0,2049);
//Read buffer from file
k=read(fd,buf,2048);
if(k<1){
perror("Error while reading file\n");
close(fd);
close(dfd);
return errno;
}else if(k<2048){
continu=0;
}
//Calculate the size of the file
size+=k;
//Send the buffer
n=send(dfd,buf,k,0);
if(n!=k){
printf("Error in data transfer\n");
close(fd);
close(dfd);
return n;
}
}
//Trying just now..
gettimeofday(&end,NULL);
time=end.tv_sec-begin.tv_sec;
if(begin.tv_usec>end.tv_usec){
time=time-1;
}
time+=((double)(end.tv_usec-begin.tv_usec))/1000000;
printf("Transfer speed: %lf\n",(double)size/time);
printf("Time taken: %lf\n",time);
//Close file
n=close(fd);
if(n<0){
printf("Error while closing file\n");
return n;
}
//Close data connection
n=close(dfd);
if(n<0){
printf("Error while closing data connection\n");
return n;
}
//Receive ack
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check that return code was 226
if(strncmp(buf,"226",3)){
printf("Error while reading file\n");
return -1;
}
return 0;
}
//Openfun-subprogram
//Open connection to server
//Parameters: socket, address
//Return value: 0 normally, 1 if sign in failed, negative in error
int openfun(int sfd,struct sockaddr_in o){
int n,l,continu=1;
char buf[2049],temp[2049];
//Open connection to server
l=sizeof(struct sockaddr_in);
n=connect(sfd,(struct sockaddr*)&o,l);
if(n<0){
printf("No connection to server\n");
return errno;
}
printf("Connection ready\n");
//receive greeting
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
if(strncmp(buf,"220",3)){
printf("Error while connecting to server\n");
return -4;
}
//Ask for user name and password. Try tree times until give up.
while(continu){
//Give username
memset(buf,0,2049);
memset(temp,0,2049);
printf("Give user name: ");
scanf("%s",temp);
sprintf(buf,"USER %s\r\n",temp);
//Send USER-command
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
return -1;
}
//Receive ack
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check that return code was 331
if(strncmp(buf,"331",3)){
printf("Error while sending user name\n");
return -3;
}
//Give password
memset(buf,0,2049);
memset(temp,0,2049);
printf("Give password: ");
scanf("%s",temp);
sprintf(buf,"PASS %s\r\n",temp);
//Send PASS-command
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
return -1;
}
//Receive ack
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//If return code was 230 end loop, otherwise ask user id again
if(strncmp(buf,"230",3)){
printf("Inlid password\n");
continu++;
//Quit after three failed tries
if(continu>3){
printf("Login failed!\n");
return 1;
}
}else{
continu=0;
}
}
return 0;
}
//Closefun-subprogram
//close connection to server
//Parameters: socket
//Return value: 0 normally, negative in error
int closefun(int sfd){
int n;
char buf[2049];
memset(buf,0,2049);
sprintf(buf,"QUIT\r\n");
//Send QUIT-command
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
return -1;
}
//receive ack
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check that return code was 221
if(strncmp(buf,"221",3)){
printf("Error while closing connection\n");
return -3;
}
//Close connection
n=close(sfd);
if(n<0){
printf("Error while closing connection\n");
return -2;
}
return 0;
}
//Cdfun-subprogram
//Change directory in server
//Parameters: socket, command user gave
//Return value: 0 normally, negative in error
int cdfun(int sfd,char* par){
int n;
char buf[2049];
memset(buf,0,2049);
//Remove new line at the end
par[strlen(par)-1]='\0';
//Send CWD-command
sprintf(buf,"CWD %s\r\n",&par[3]);
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
return -1;
}
//Receive ack
n=receive(sfd,buf);
if(n<0){
return n;
}
return 0;
}
//Cdupfun-subprogram
//Change directory to one level up
//Parameters: socket
//return value: 0 normally, negative in error
int cdupfun(int sfd){
int n;
char buf[2049];
memset(buf,0,2049);
//Send CDUP-command
sprintf(buf,"CDUP\r\n");
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
return -1;
}
//Receive ack
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
return 0;
}
//Lsfun-subprogram
//Get directory listing from server
//Parameters: socket, data transfer socket, data transfer port, command user gave, passive mode, server address if passive mode
//Return value: 0 normally, negative in error
int listfun(int sfd,int dsfd,int dport,char* par,int passive,struct sockaddr_in da){
int i,dfd;
unsigned int n;
char buf[2049],temp[2049];
struct hostent *hp;
struct sockaddr_in o;
memset(buf,0,2049);
memset(temp,0,2049);
//Send TYPE A -command (ASCII)
sprintf(buf,"TYPE A\r\n");
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
return -1;
}
//Receive ack
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check that return code was 200
if(strncmp(buf,"200",3)){
printf("TYPE-Type command failed\n");
return 0;
}
if(!passive){
//Check host address
n=gethostname(buf,2048);
if(n<0){
perror("Error in gethostname function");
return errno;
}
//Convert address to IP-number
hp=gethostbyname(buf);
if(hp==NULL){
herror("Error in gethostbyname function\n");
return h_errno;
}
//Convert address to char-type and replace dots with commas
strcpy(temp,inet_ntoa(*((struct in_addr*)hp->h_addr)));
for(i=0;i<strlen(temp);i++){
if(temp[i]=='.'){
temp[i]=',';
}
}
//PORT <ip (comma separated)>,<floor(port/256)>,<port%256>
memset(buf,0,2049);
sprintf(buf,"PORT %s,%d,%d\r\n",temp,(int)floor(dport/256),(int)dport%256);
//Send PORT-command
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
return -1;
}
//Receive ack
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//check that return code was 200
if(strncmp(buf,"200",3)){
printf("PORT-PORT command failed\n");
return 0;
}
}
//Remove new line at the end
par[strlen(par)-1]='\0';
//Send LIST-command
memset(buf,0,2049);
sprintf(buf,"LIST%s\r\n",&par[2]);
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
return -1;
}
//Open passive data connection
if(passive){
n=connect(dsfd,(struct sockaddr*)&da,sizeof(struct sockaddr_in));
if(n<0){
printf("Error opening passive data connection\n");
return n;
}
dfd=dsfd;
}
//Receive ack
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check that return code 150
if(strncmp(buf,"150",3)){
printf("LIST-LIST command failed\n");
return 0;
}
//Open active data connection
if(!passive){
n=sizeof(struct sockaddr_in);
dfd=accept(dsfd,(struct sockaddr*)&o,&n);
if(dfd<0){
printf("Error while connecting data connection\n");
return -3;
}
printf("Data connection created\n");
}
//Receive directory listing
memset(buf,0,2049);
n=receive(dfd,buf);
if(n<0){
return n;
}
//Close data connection
n=close(dfd);
if(n<0){
printf("Error while closing connection\n");
return -3;
}
//Receive message confirming the closure of data connection
memset(buf,0,2049);
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check that return code was 226
if(strncmp(buf,"226",3)){
printf("Error");
return -4;
}
return 0;
}
//Passivefun-subprogram
//Sets the connection to passive mode
//Parameters: socket, pointer for a sockaddr_in struct where the received address and port are stored
//Return value: 0 normally, negative in error
int passivefun(int sfd,struct sockaddr_in *da){
int n,i,port;
char buf[2049],buf2[2049],*p;
memset(buf,0,2049);
memset(buf2,0,2049);
//Send PASV-command
sprintf(buf,"PASV\r\n");
printf("---> %s",buf);
n=send(sfd,buf,strlen(buf),0);
if(n!=strlen(buf)){
printf("Error in data transfer\n");
return -1;
}
//Receive ack
n=receive(sfd,buf);
if(n<0){
return n;
}
//Check that return code was 227
if(strncmp(buf,"227",3)){
printf("Error entering passive mode\n");
return -2;
}
da->sin_family=AF_INET;
//Copy the address part of the returned message
p=strchr(buf,'(');
p=strchr(p+1,',');
p=strchr(p+1,',');
p=strchr(p+1,',');
p=strchr(p+1,',');
strncpy(buf2,strchr(buf,'(')+1,p-strchr(buf,'(')-1);
for(i=0;i<strlen(buf2);i++){
if(buf2[i]==','){
buf2[i]='.';
}
}
//Convert the address from char-type
n=inet_aton(buf2,&da->sin_addr);
if(!n){
printf("Error converting address\n");
return -3;
}
memset(buf2,0,2049);
//Convert port
strncpy(buf2,p+1,strchr(p+1,',')-p-1);
port=atoi(buf2)*256;
p=strchr(p+1,',');
memset(buf2,0,2049);
strncpy(buf2,p+1,strchr(p+1,')')-p-1);
port+=atoi(buf2);
da->sin_port=htons(port);
return 0;
}
//Dsocket-subprogram
//Open new data transfer socket
//Parameters: data transfer socket, data transfer port
//Return value: positive value normally, negative in error
int dsoket(int dsfd,int dport,int passive){
struct sockaddr_in o;
int n,l;
if(!passive){
//Close old socket
n=close(dsfd);
if(n<0){
printf("Error while closing socket\n");
return n;
}
}
//Open new socket
dsfd=socket(AF_INET,SOCK_STREAM,0);
if(dsfd<0){
printf("Error while opening socket\n");
return dsfd;
}
//Set IP-settings
memset(&o,0,sizeof(struct sockaddr_in));
o.sin_family=AF_INET;
o.sin_addr.s_addr=INADDR_ANY;
o.sin_port=htons(dport);
//Allow socket reuse
n=1;
if(setsockopt(dsfd,SOL_SOCKET,SO_REUSEADDR,(void*)&n,sizeof(n))==-1){
perror("Error in setsockopt");
return -1;
}
//Bind socket
l=sizeof(o);
n=bind(dsfd,(struct sockaddr*)&o,l);
if(n<0){
printf("Error while binding socket\n");
return -1;
}
//Listen to the socket
n=listen(dsfd,10);
if(n<0){
perror("Error in listen function");
return -1;
}
return dsfd;
}
//Pdsocket-subprogram
//Open a new passive data transfer socket
//Parameters: socket, data transfer socket, server address
//Return value: positive value normally, negative in error
int pdsocket(int sfd,int dsfd, struct sockaddr_in *da){
int n;
struct sockaddr_in da2;
//Close old socket
n=close(dsfd);
if(n<0){
printf("Error closing socket\n");
return n;
}
//Open a new socket
dsfd=socket(AF_INET,SOCK_STREAM,0);
if(dsfd<0){
printf("Error opening socket\n");
return dsfd;
}
//Send PASV-command
n=passivefun(sfd,da);
if(n<0){
return n;
}
//Allow socket reuse
n=1;
if(setsockopt(dsfd,SOL_SOCKET,SO_REUSEADDR,(void*)&n,sizeof(n))==-1){
perror("Error in setsockopt()");
return -1;
}
//Set IP-settings
da2.sin_family=AF_INET;
da2.sin_addr.s_addr=INADDR_ANY;
da2.sin_port=htons(55555);
//Bind socket
n=bind(dsfd,(struct sockaddr*)&da2,sizeof(struct sockaddr_in));
if(n<0){
perror("Error in binding socket\n");
return n;
}
return dsfd;
}
//receive-subprogram
//Receive a message from server
//Parameters: socket, buffer (only return code is stored)
//Return code: 1 normally, negative in error
int receive(int sfd,char *retval){
int n,i,continu=1,pal=0;
char buf[2049],*p;
//Receive until entire message is received
while(continu){
//Receive data
memset(buf,0,2049);
n=recv(sfd,buf,2048,0);
if(n<0){
printf("Error in data transfer\n");
return n;
}else if(n==0){
printf("Connection closed by server\n");
return -2;
}
//Is there \r\n at the end?
for(i=1;i<strlen(buf);i++){
if((buf[i-1]=='\r')&&(buf[i]=='\n')) continu=0;
}
//Does the last return code have "-" at the end?
p=buf;
while(strchr(p,'\n')!=strrchr(buf,'\n')){
p=strchr(p+1,'\n');
}
if(p[3]=='-') continu=1;
//If buffer is full continue
if(n==2048) continu=1;
//Only the three first characters are returned (return code number) EXCEPT if return code is 227 (passive mode accept)
if(!pal){
strncpy(retval,buf,3);
pal=0;
if(!strncmp(buf,"227",3)){
strcpy(retval,buf);
}
}
//Print buffer
printf(buf);
}
return 1;
}
// This is the end of home exam (ftp client based on RFC 959)
// Comments and feedback at santosh (dot) kalwar (at) lut (dot) fi
|
the_stack_data/155124.c | /* C implementation of Bruce Schneier's card cipher, "Solitaire".
Paul Crowley <[email protected]>, 1999
This program is placed in the public domain.
This program is mainly for performing statistical tests on
Solitaire's output; the actual ability to encrypt text is added
only so that the implementation correctness can be verified.
So the cipher core is heavily optimised but much of the supporting
code used for actual encryption is not optimised at all, and even
contains superfluous statistics-related work.
http://www.hedonism.demon.co.uk/paul/solitaire/ */
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define STREQUAL(a,b) (strcmp(a,b) == 0)
/* State of the 54-card deck. This keeps a spare deck for copying
into. It also has three spare slots *behind* the start of the
deck: two so the deck can be moved backward if a joker is moved
from the bottom to the top in the first step, and one so that the
reference to the card before the first joker always points
somewhere even when there's a joker on the top of the pack. */
typedef struct SolState_t {
int a, b;
int *deck, *spare;
int deck1[57], deck2[57];
} SolState_t ;
SolState_t state;
int verbose = 0;
int lastout, cocount;
#define JOKER_STEP(var,ovar) \
(((var != 53) ? \
(source[var] = source[var +1], var++) : \
(source--, ovar++, source[0] = source[1], var = 1)), \
((var == ovar)?(ovar--):0))
/* Cycle the state for "rounds" outputs, skipping jokers
as usual. "lastout" is the last output, which is never a joker.
If "rounds" is zero though, cycle the state just once, even
if the output card is a joker. "lastout" may or may not be set.
This is only useful for key setup.
Note that for performance reasons, this updates the coincidence
statistics under all circumstances, so they need to be set to zero
immediately before the large batch run. */
static void cycle_deck(
int rounds
)
{
int *source, *s, *sb, *d;
int lo, hi;
int nlo, nhi, nccut;
int output;
do {
assert(state.a != state.b);
assert(state.deck[state.a] == 53);
assert(state.deck[state.b] == 53);
source = state.deck;
JOKER_STEP(state.a,state.b);
JOKER_STEP(state.b,state.a);
JOKER_STEP(state.b,state.a);
source[state.a] = 53;
source[state.b] = 53;
if (state.a < state.b) {
lo = state.a;
hi = state.b + 1;
} else {
lo = state.b;
hi = state.a + 1;
}
nlo = 54 - hi;
nhi = 54 - lo;
/* We do both the triple cut and the count cut as one
copying step; this means handling four separate cases. */
nccut = source[lo -1];
s = source;
if (lo == 0) {
/* There's a joker on the top of the pack. This can
only happen in one exact circumstance, but when it
does nccount is wrong. So we handle it specially. */
assert(state.a == 0);
assert(state.b == 2);
d = &state.spare[51];
sb = &source[3];
while(s < sb) {*d++ = *s++;}
d = &state.spare[0];
sb = &source[54];
while(s < sb) {*d++ = *s++;}
state.a = 51;
state.b = 53;
} else if (nccut <= nlo) {
/* The second cut is before the first joker. */
d = &state.spare[nhi - nccut];
sb = &source[lo -1];
while(s < sb) {*d++ = *s++;}
state.spare[53] = *s++;
d = &state.spare[nlo - nccut];
sb = &source[hi];
while(s < sb) {*d++ = *s++;}
d = &state.spare[53 - nccut];
sb = &source[nccut + hi]; /* ccut */
while(s < sb) {*d++ = *s++;}
d = &state.spare[0];
sb = &source[54];
while(s < sb) {*d++ = *s++;}
state.a += nlo - nccut - lo;
state.b += nlo - nccut - lo;
} else if (nccut < nhi) {
/* The second cut is between the two jokers */
d = &state.spare[nhi - nccut];
sb = &source[lo -1];
while(s < sb) {*d++ = *s++;}
state.spare[53] = *s++;
d = &state.spare[53 - nccut + nlo];
sb = &source[nccut - nlo + lo]; /* ccut */
while(s < sb) {*d++ = *s++;}
d = &state.spare[0];
sb = &source[hi];
while(s < sb) {*d++ = *s++;}
d = &state.spare[53 - nccut];
sb = &source[54];
while(s < sb) {*d++ = *s++;}
if (state.a < state.b) {
state.a = 53 - nccut + nlo;
state.b = nhi - nccut -1;
} else {
state.b = 53 - nccut + nlo;
state.a = nhi - nccut -1;
}
} else {
/* The second cut is after the last joker. */
d = &state.spare[53 - nccut + nhi];
sb = &source[nccut - nhi]; /* ccut */
while(s < sb) {*d++ = *s++;}
d = &state.spare[0];
sb = &source[lo -1];
while(s < sb) {*d++ = *s++;}
state.spare[53] = *s++;
d = &state.spare[53 - nccut + nlo];
sb = &source[hi];
while(s < sb) {*d++ = *s++;}
d = &state.spare[53 - nccut];
sb = &source[54];
while(s < sb) {*d++ = *s++;}
state.a += 53 - nccut + nlo - lo;
state.b += 53 - nccut + nlo - lo;
}
source = state.deck;
state.deck = state.spare;
state.spare = source;
output = state.deck[state.deck[0]];
if (output >= 26) {
if (output >= 52) {
if (output > 52)
continue;
output = 0;
} else {
output -= 26;
}
}
cocount += (lastout == output);
lastout = output;
rounds--;
} while (rounds > 0);
}
static void print_deck(
)
{
int i;
//@ loop unroll 54;
for (i = 0; i < 54; i++) {
if (state.deck[i] < 53) {
putchar(' ' + state.deck[i]);
} else if (i == state.a) {
putchar('U');
} else {
assert(i == state.b);
putchar('V');
}
}
}
/* Key the deck with a passphrase. */
static void key_deck(
char *key
)
{
int i, kval, *tmp;
state.deck = state.deck1 + 3;
state.spare = state.deck2 + 3;
//@ loop unroll 52;
for (i = 0; i < 52; i++) {
state.deck[i] = i+1;
}
state.deck[state.a = 52] = 53;
state.deck[state.b = 53] = 53;
for (; *key != '\0'; key++) {
if ( *key >= 'A' && *key <= 'Z' ) {
cycle_deck(0); /* Special value '0' is only useful here... */
/* And now perform a second count cut based on the key letter */
kval = *key - 'A' + 1;
//@ loop unroll 53;
for (i = 0; i < 53; i++)
state.spare[i] = state.deck[(i + kval) % 53];
state.spare[53] = state.deck[53];
if (state.a != 53)
state.a = (state.a + 53 - kval) % 53;
if (state.b != 53)
state.b = (state.b + 53 - kval) % 53;
tmp = state.deck;
state.deck = state.spare;
state.spare = tmp;
if (verbose) {
print_deck();
printf(" after %c\n", *key);
}
}
}
/* These are touched by the keying: fix them. */
lastout = 100; cocount = 0;
}
/* Encrypt a single character. */
static char encrypt_char(
char char_in
)
{
char char_out;
cycle_deck(1);
char_out = 'A' + (char_in - 'A' + lastout) % 26;
if (verbose) {
print_deck();
printf(" %c -> %c\n", char_in, char_out);
}
return char_out;
}
int main(
int argc,
char *argv[]
)
{
char **av = argv, *tmp;
int slow_mode = 0;
long rounds;
/* Skip the name of the program */
av++; argc--;
if (argc < 2) {
printf("Usage: [flags] key message|len\n");
}
//@ loop unroll 3;
while (argc > 2) {
if (STREQUAL(*av, "-v")) {
verbose = 1;
} else if (STREQUAL(*av, "-s")) {
slow_mode = 1;
} else {
printf ("Unrecognised flag: %s\n", *av);
exit(-1);
}
av++; argc--;
}
key_deck(av[0]);
rounds = strtol(av[1], &tmp, 0);
if (*tmp != '\0') {
/* It's not a number - so it's a string! */
char *text = av[1];
int i = 0;
//@ loop unroll 256;
for (; *text != '\0'; text++) {
if (*text >= 'A' && *text <= 'Z') {
if (i > 0 && (i % 5) == 0)
putchar(' ');
putchar(encrypt_char(*text));
i++;
}
}
while ((i % 5) != 0) {
putchar(encrypt_char('X'));
i++;
}
putchar('\n');
} else {
/* Treat it as a sequence of 'A's. */
int i;
if (rounds <= 0) {
printf("Rounds number must be greater than zero\n");
exit(-1);
}
if (verbose || slow_mode) {
for (i = 0; i < rounds; i++)
encrypt_char('A');
} else {
cycle_deck(rounds);
}
printf("Coincidences: %d / %ld\n", cocount, rounds -1);
}
return 0;
}
#ifdef __FRAMAC__
# include "__fc_builtin.h"
volatile int nondet;
// main for EVA
int eva_main() {
int argc = Frama_C_interval(0, 5);
char argv0[256], argv1[256], argv2[256], argv3[256], argv4[256];
char *argv[5] = {argv0, argv1, argv2, argv3, argv4};
//@ loop unroll 5;
for (int i = 0; i < 5; i++) {
Frama_C_make_unknown(argv[i], 255);
argv[i][255] = 0;
}
return main(argc, argv);
}
#endif // __FRAMAC__
|
the_stack_data/5592.c | //
// Created by Vashon on 2020/6/4.
//
#include <stdio.h>
// 合并排序数组,LeetCode面试题10.01
void homework_004_1001(void) {
void mergeArray(int *arrayA, int *arrayB, int countA, int countB);
int m = 3, n = 3;
int a[6] = {1, 2, 3, 0, 0, 0};
int b[3] = {2, 5, 6};
mergeArray(a, b, m, n);
for (int i = 0; i < 6; ++i) {
printf("%d ", a[i]);
}
printf("\n");
}
void mergeArray(int *arrayA, int *arrayB, int countA, int countB) {
int i = 0, j = 0, lenA = countA + countB, k = lenA - 1, moveA = 0;
while (i < lenA) {
// 当数组a中的值小于等于数组b中的值,则索引后移,这里最好是加上等于,因为这样,数组a整体后移就可以少一次
// 这里有一个隐藏条件,就是数组a元素已经移动完毕,这就应该直接将剩余的b数组元素插入到数组a,一开始这里没想到,掉坑了
if (arrayA[i] <= arrayB[j] && moveA != countA) {
i++;
moveA++; // 已经移动的a数组元素
} else {
// 数组a当前索引的值比数组b的值大,则整体后移
// 这里有一个隐藏条件,就是数组a元素已经移动完毕,就不需要再移动后面的元素了
while (i < k && moveA != countA) {
arrayA[k] = arrayA[k - 1];
k--;
}
// 将数组b的值插入数组a中,并且a、b索引后移一位
arrayA[i++] = arrayB[j++];
// 当数组b中的值都已经插入到数组a中,则结束循环
if (j == countB)
break;
// 重置k为数组a最后一位的索引
k = lenA - 1;
}
}
} |
the_stack_data/1023108.c |
int
main()
{
int x;
x = 0;
switch(x)
case 0:
;
switch(x)
case 0:
switch(x) {
case 0:
goto next;
default:
return 1;
}
return 1;
next:
switch(x)
case 1:
return 1;
switch(x) {
{
x = 1 + 1;
foo:
case 1:
return 1;
}
}
switch(x) {
case 0:
return x;
case 1:
return 1;
default:
return 1;
}
}
|
the_stack_data/193894111.c | #include <stdbool.h>
#include <stdlib.h>
//integer cmp function
int cmp(const void *lhs, const void *rhs)
{
if (*(int *)lhs == *(int *)rhs)
return 0;
return *(int *)lhs < *(int *)rhs ? -1 : 1;
}
bool isPossibleDivide(int *nums, int numsSize, int k)
{
if (numsSize % k != 0)
return false;
qsort(nums, numsSize, sizeof(int), cmp);
int arr[numsSize][2], arrSize = 0; //{val,count}
for (int i = 1, j = 0; i <= numsSize; ++i)
{
if (i == numsSize || nums[i] != nums[j])
{
arr[arrSize][0] = nums[j];
arr[arrSize][1] = i - j;
j = i;
++arrSize;
}
}
for (int i = 0; i < arrSize; ++i)
{
if (arr[i][1] == 0)
continue;
int count = arr[i][1];
if (i + k - 1 >= arrSize)
return false;
for (int j = 0; j < k; ++j)
{
if (arr[i + j][0] - arr[i][0] != j) //consecutive
return false;
arr[i + j][1] -= count;
if (arr[i + j][1] < 0)
return false;
}
}
return true;
} |
the_stack_data/140764186.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
unsigned char *read_buffer(char *file_name, size_t *size_ptr)
{
FILE *f;
unsigned char *buf;
size_t size;
/* Open file */
f = fopen(file_name, "rb");
if (!f)
return NULL;
/* Obtain file size */
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
/* Allocate and read buffer */
buf = malloc(size + 1);
fread(buf, 1, size, f);
buf[size] = '\0';
/* Return size of buffer */
if (size_ptr)
*size_ptr = size;
/* Return buffer */
return buf;
}
void write_buffer(char *file_name, const char *buffer, size_t buffer_size)
{
FILE *f;
/* Open file */
f = fopen(file_name, "w+");
/* Write buffer */
if(buffer)
fwrite(buffer, 1, buffer_size, f);
/* Close file */
fclose(f);
}
int main(int argc, char const *argv[])
{
/* Get platform */
cl_platform_id platform;
cl_uint num_platforms;
cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformIDs' failed\n");
exit(1);
}
printf("Number of platforms: %d\n", num_platforms);
printf("platform=%p\n", platform);
/* Get platform name */
char platform_name[100];
ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformInfo' failed\n");
exit(1);
}
printf("platform.name='%s'\n\n", platform_name);
/* Get device */
cl_device_id device;
cl_uint num_devices;
ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceIDs' failed\n");
exit(1);
}
printf("Number of devices: %d\n", num_devices);
printf("device=%p\n", device);
/* Get device name */
char device_name[100];
ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
device_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceInfo' failed\n");
exit(1);
}
printf("device.name='%s'\n", device_name);
printf("\n");
/* Create a Context Object */
cl_context context;
context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateContext' failed\n");
exit(1);
}
printf("context=%p\n", context);
/* Create a Command Queue Object*/
cl_command_queue command_queue;
command_queue = clCreateCommandQueue(context, device, 0, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateCommandQueue' failed\n");
exit(1);
}
printf("command_queue=%p\n", command_queue);
printf("\n");
/* Program source */
unsigned char *source_code;
size_t source_length;
/* Read program from 'native_divide_float2.cl' */
source_code = read_buffer("native_divide_float2.cl", &source_length);
/* Create a program */
cl_program program;
program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateProgramWithSource' failed\n");
exit(1);
}
printf("program=%p\n", program);
/* Build program */
ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if (ret != CL_SUCCESS )
{
size_t size;
char *log;
/* Get log size */
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);
/* Allocate log and print */
log = malloc(size);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
/* Free log and exit */
free(log);
exit(1);
}
printf("program built\n");
printf("\n");
/* Create a Kernel Object */
cl_kernel kernel;
kernel = clCreateKernel(program, "native_divide_float2", &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateKernel' failed\n");
exit(1);
}
/* Create and allocate host buffers */
size_t num_elem = 10;
/* Create and init host side src buffer 0 */
cl_float2 *src_0_host_buffer;
src_0_host_buffer = malloc(num_elem * sizeof(cl_float2));
for (int i = 0; i < num_elem; i++)
src_0_host_buffer[i] = (cl_float2){{2.0, 2.0}};
/* Create and init device side src buffer 0 */
cl_mem src_0_device_buffer;
src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float2), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float2), src_0_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create host dst buffer */
cl_float2 *dst_host_buffer;
dst_host_buffer = malloc(num_elem * sizeof(cl_float2));
memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_float2));
/* Create device dst buffer */
cl_mem dst_device_buffer;
dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_float2), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create dst buffer\n");
exit(1);
}
/* Set kernel arguments */
ret = CL_SUCCESS;
ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clSetKernelArg' failed\n");
exit(1);
}
/* Launch the kernel */
size_t global_work_size = num_elem;
size_t local_work_size = num_elem;
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
exit(1);
}
/* Wait for it to finish */
clFinish(command_queue);
/* Read results from GPU */
ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_float2), dst_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueReadBuffer' failed\n");
exit(1);
}
/* Dump dst buffer to file */
char dump_file[100];
sprintf((char *)&dump_file, "%s.result", argv[0]);
write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_float2));
printf("Result dumped to %s\n", dump_file);
/* Free host dst buffer */
free(dst_host_buffer);
/* Free device dst buffer */
ret = clReleaseMemObject(dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 0 */
free(src_0_host_buffer);
/* Free device side src buffer 0 */
ret = clReleaseMemObject(src_0_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Release kernel */
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseKernel' failed\n");
exit(1);
}
/* Release program */
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseProgram' failed\n");
exit(1);
}
/* Release command queue */
ret = clReleaseCommandQueue(command_queue);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseCommandQueue' failed\n");
exit(1);
}
/* Release context */
ret = clReleaseContext(context);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseContext' failed\n");
exit(1);
}
return 0;
} |
the_stack_data/750881.c | #include<stdio.h>
#include<stdlib.h>
int main()
{
int n,k,i,j,m,l;
int a[100010];
scanf("%d",&n);
for(i=1;i<100000;i++)
a[i]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&m);
a[m]++;
}
scanf("%d",&k);
l=99999;
for(j=0;j<k;j++)
{
i=l;
while(a[i]==0)
i--;
l=i;
m=a[i];
a[i]=0;
}
printf("%d %d\n",l,m);
return 0;
} |
the_stack_data/358321.c | #include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
static volatile uint32_t piModel = 1;
static volatile uint32_t piPeriphBase = 0x20000000;
static volatile uint32_t piBusAddr = 0x40000000;
#define SYST_BASE (piPeriphBase + 0x003000)
#define DMA_BASE (piPeriphBase + 0x007000)
#define CLK_BASE (piPeriphBase + 0x101000)
#define GPIO_BASE (piPeriphBase + 0x200000)
#define UART0_BASE (piPeriphBase + 0x201000)
#define PCM_BASE (piPeriphBase + 0x203000)
#define SPI0_BASE (piPeriphBase + 0x204000)
#define I2C0_BASE (piPeriphBase + 0x205000)
#define PWM_BASE (piPeriphBase + 0x20C000)
#define BSCS_BASE (piPeriphBase + 0x214000)
#define UART1_BASE (piPeriphBase + 0x215000)
#define I2C1_BASE (piPeriphBase + 0x804000)
#define I2C2_BASE (piPeriphBase + 0x805000)
#define DMA15_BASE (piPeriphBase + 0xE05000)
#define DMA_LEN 0x1000 /* allow access to all channels */
#define CLK_LEN 0xA8
#define GPIO_LEN 0xB4
#define SYST_LEN 0x1C
#define PCM_LEN 0x24
#define PWM_LEN 0x28
#define I2C_LEN 0x1C
#define GPSET0 7
#define GPSET1 8
#define GPCLR0 10
#define GPCLR1 11
#define GPLEV0 13
#define GPLEV1 14
#define GPPUD 37
#define GPPUDCLK0 38
#define GPPUDCLK1 39
#define SYST_CS 0
#define SYST_CLO 1
#define SYST_CHI 2
#define CLK_PASSWD (0x5A<<24)
#define CLK_CTL_MASH(x)((x)<<9)
#define CLK_CTL_BUSY (1 <<7)
#define CLK_CTL_KILL (1 <<5)
#define CLK_CTL_ENAB (1 <<4)
#define CLK_CTL_SRC(x) ((x)<<0)
#define CLK_SRCS 4
#define CLK_CTL_SRC_OSC 1 /* 19.2 MHz */
#define CLK_CTL_SRC_PLLC 5 /* 1000 MHz */
#define CLK_CTL_SRC_PLLD 6 /* 500 MHz */
#define CLK_CTL_SRC_HDMI 7 /* 216 MHz */
#define CLK_DIV_DIVI(x) ((x)<<12)
#define CLK_DIV_DIVF(x) ((x)<< 0)
#define CLK_GP0_CTL 28
#define CLK_GP0_DIV 29
#define CLK_GP1_CTL 30
#define CLK_GP1_DIV 31
#define CLK_GP2_CTL 32
#define CLK_GP2_DIV 33
#define CLK_PCM_CTL 38
#define CLK_PCM_DIV 39
#define CLK_PWM_CTL 40
#define CLK_PWM_DIV 41
static volatile uint32_t *gpioReg = MAP_FAILED;
static volatile uint32_t *systReg = MAP_FAILED;
static volatile uint32_t *clkReg = MAP_FAILED;
#define PI_BANK (gpio>>5)
#define PI_BIT (1<<(gpio&0x1F))
/* gpio modes. */
#define PI_INPUT 0
#define PI_OUTPUT 1
#define PI_ALT0 4
#define PI_ALT1 5
#define PI_ALT2 6
#define PI_ALT3 7
#define PI_ALT4 3
#define PI_ALT5 2
void gpioSetMode(unsigned gpio, unsigned mode) {
int reg, shift;
reg = gpio/10;
shift = (gpio%10) * 3;
gpioReg[reg] = (gpioReg[reg] & ~(7<<shift)) | (mode<<shift);
}
int gpioGetMode(unsigned gpio) {
int reg, shift;
reg = gpio/10;
shift = (gpio%10) * 3;
return (*(gpioReg + reg) >> shift) & 7;
}
/* Values for pull-ups/downs off, pull-down and pull-up. */
#define PI_PUD_OFF 0
#define PI_PUD_DOWN 1
#define PI_PUD_UP 2
void gpioSetPullUpDown(unsigned gpio, unsigned pud) {
*(gpioReg + GPPUD) = pud;
usleep(20);
*(gpioReg + GPPUDCLK0 + PI_BANK) = PI_BIT;
usleep(20);
*(gpioReg + GPPUD) = 0;
*(gpioReg + GPPUDCLK0 + PI_BANK) = 0;
}
int gpioRead(unsigned gpio) {
if ((*(gpioReg + GPLEV0 + PI_BANK) & PI_BIT) != 0) return 1;
else return 0;
}
void gpioWrite(unsigned gpio, unsigned level) {
if (level == 0) *(gpioReg + GPCLR0 + PI_BANK) = PI_BIT;
else *(gpioReg + GPSET0 + PI_BANK) = PI_BIT;
}
void gpioTrigger(unsigned gpio, unsigned pulseLen, unsigned level) {
if (level == 0) *(gpioReg + GPCLR0 + PI_BANK) = PI_BIT;
else *(gpioReg + GPSET0 + PI_BANK) = PI_BIT;
usleep(pulseLen);
if (level != 0) *(gpioReg + GPCLR0 + PI_BANK) = PI_BIT;
else *(gpioReg + GPSET0 + PI_BANK) = PI_BIT;
}
/* Bit (1<<x) will be set if gpio x is high. */
uint32_t gpioReadBank1(void) { return (*(gpioReg + GPLEV0)); }
uint32_t gpioReadBank2(void) { return (*(gpioReg + GPLEV1)); }
/* To clear gpio x bit or in (1<<x). */
void gpioClearBank1(uint32_t bits) { *(gpioReg + GPCLR0) = bits; }
void gpioClearBank2(uint32_t bits) { *(gpioReg + GPCLR1) = bits; }
/* To set gpio x bit or in (1<<x). */
void gpioSetBank1(uint32_t bits) { *(gpioReg + GPSET0) = bits; }
void gpioSetBank2(uint32_t bits) { *(gpioReg + GPSET1) = bits; }
unsigned gpioHardwareRevision(void) {
static unsigned rev = 0;
FILE * filp;
char buf[512];
char term;
int chars=4; /* number of chars in revision string */
if (rev) return rev;
piModel = 0;
filp = fopen ("/proc/cpuinfo", "r");
if (filp != NULL)
{
while (fgets(buf, sizeof(buf), filp) != NULL)
{
if (piModel == 0)
{
if (!strncasecmp("model name", buf, 10))
{
if (strstr (buf, "ARMv6") != NULL)
{
piModel = 1;
chars = 4;
piPeriphBase = 0x20000000;
piBusAddr = 0x40000000;
}
else if (strstr (buf, "ARMv7 Processor rev 4") != NULL)
{
piModel = 2;
chars = 6;
piPeriphBase = 0x3F000000;
piBusAddr = 0xC0000000;
}
else if (strstr (buf, "ARMv7 Processor rev 3") != NULL)
{
piModel = 4;
chars = 6;
piPeriphBase = 0xFE000000;
piBusAddr = 0xC0000000;
}
}
}
if (!strncasecmp("revision", buf, 8))
{
if (sscanf(buf+strlen(buf)-(chars+1),
"%x%c", &rev, &term) == 2)
{
if (term != '\n') rev = 0;
}
}
}
fclose(filp);
}
return rev;
}
/* Returns the number of microseconds after system boot. Wraps around
after 1 hour 11 minutes 35 seconds.
*/
uint32_t gpioTick(void) {
return systReg[SYST_CLO];
}
/* Map in registers. */
static uint32_t *initMapMem(int fd, uint32_t addr, uint32_t len) {
return (uint32_t *) mmap(0, len,
PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_SHARED|MAP_LOCKED,
fd, addr);
}
int gpioInitialise(void) {
int fd;
gpioHardwareRevision(); /* sets piModel, needed for peripherals address */
fd = open("/dev/mem", O_RDWR | O_SYNC) ;
if (fd < 0)
{
fprintf(stderr,
"This program needs root privileges. Try using sudo\n");
return -1;
}
gpioReg = initMapMem(fd, GPIO_BASE, GPIO_LEN);
systReg = initMapMem(fd, SYST_BASE, SYST_LEN);
clkReg = initMapMem(fd, CLK_BASE, CLK_LEN);
close(fd);
if ((gpioReg == MAP_FAILED) ||
(systReg == MAP_FAILED) ||
(clkReg == MAP_FAILED))
{
fprintf(stderr,
"Bad, mmap failed\n");
return -1;
}
return 0;
}
|
the_stack_data/118173.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern void signal(int sig , void *func ) ;
extern float strtof(char const *str , char const *endptr ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned short input[1] , unsigned short output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void RandomFunc(unsigned short input[1] , unsigned short output[1] )
{
unsigned short state[1] ;
char copy12 ;
char copy13 ;
char copy16 ;
char copy18 ;
{
state[0UL] = (input[0UL] | 51238316UL) >> (unsigned short)3;
if ((state[0UL] >> (unsigned short)3) & (unsigned short)1) {
if ((state[0UL] >> (unsigned short)4) & (unsigned short)1) {
if (state[0UL] & (unsigned short)1) {
state[0UL] <<= (state[0UL] & (unsigned short)7) | 1UL;
} else {
state[0UL] <<= (state[0UL] & (unsigned short)7) | 1UL;
state[0UL] <<= (state[0UL] & (unsigned short)7) | 1UL;
}
} else
if (state[0UL] & (unsigned short)1) {
copy12 = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = copy12;
copy13 = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = copy13;
copy13 = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = copy13;
}
} else
if ((state[0UL] >> (unsigned short)2) & (unsigned short)1) {
copy16 = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = copy16;
} else {
state[0UL] >>= (state[0UL] & (unsigned short)7) | 1UL;
copy18 = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = copy18;
copy18 = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = copy18;
}
output[0UL] = state[0UL] & (unsigned short)44416;
}
}
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned short input[1] ;
unsigned short output[1] ;
int randomFuns_i5 ;
unsigned short randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned short )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == (unsigned short)31026) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/617678.c | #include <stdint.h>
#include <float.h>
#include <math.h>
#define FORCE_EVAL(x) do { \
if (sizeof(x) == sizeof(float)) { \
volatile float __x; \
__x = (x); \
} else if (sizeof(x) == sizeof(double)) { \
volatile double __x; \
__x = (x); \
} else { \
volatile long double __x; \
__x = (x); \
} \
} while(0)
float my_floorf(float x)
{
union {float f; uint32_t i;} u = {x};
int e = (int)(u.i >> 23 & 0xff) - 0x7f;
uint32_t m;
if (e >= 23)
return x;
if (e >= 0) {
m = 0x007fffff >> e;
if ((u.i & m) == 0)
return x;
FORCE_EVAL(x + 0x1p120f);
if (u.i >> 31)
u.i += m;
u.i &= ~m;
} else {
FORCE_EVAL(x + 0x1p120f);
if (u.i >> 31 == 0)
u.i = 0;
else if (u.i << 1)
u.f = -1.0;
}
return u.f;
}
|
the_stack_data/37384.c | #include <fcntl.h>
#include <stdio.h>
#include <sys/select.h>
#include <unistd.h>
int main() {
int fd = open("select.c", 0, 0);
fd_set read;
FD_ZERO(&read);
FD_SET(fd, &read);
printf("Is set before? %d\n", FD_ISSET(fd, &read));
// This should actually test TCP streams and stuff, but for now I'm simply
// testing whether it ever returns or not.
printf("Amount of things ready: %d\n", select(fd + 1, &read, NULL, NULL, NULL));
printf("Is set after? %d\n", FD_ISSET(fd, &read));
close(fd);
}
|
the_stack_data/578091.c | /**
******************************************************************************
* @file stm32l4xx_ll_crs.h
* @author MCD Application Team
* @version V1.7.0
* @date 17-February-2017
* @brief CRS LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32l4xx_ll_crs.h"
#include "stm32l4xx_ll_bus.h"
/** @addtogroup STM32L4xx_LL_Driver
* @{
*/
#if defined(CRS)
/** @defgroup CRS_LL CRS
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup CRS_LL_Exported_Functions
* @{
*/
/** @addtogroup CRS_LL_EF_Init
* @{
*/
/**
* @brief De-Initializes CRS peripheral registers to their default reset values.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: CRS registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_CRS_DeInit(void)
{
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_CRS);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_CRS);
return SUCCESS;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(CRS) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/97013341.c | // Código-fonte disponível em https://github.com/mpeschke/contadeagua.git
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define NUMCONTAS 3
// ----------|--------|
// 12345678901234567890
// RESIDENCIAL
// COMERCIAL
// INDUSTRIAL
#define TIPOBUFFSIZE 11
static const char* TIPORESIDENCIAL = "RESIDENCIAL";
static const char* TIPOCOMERCIAL = "COMERCIAL";
static const char* TIPOINDUSTRIAL = "INDUSTRIAL";
enum enumTipoConta {industrial, comercial, residencial};
struct Conta
{
enum enumTipoConta tipo;
int consumo;
char idconta[100];
float valor;
} typedef stConta;
stConta contas[NUMCONTAS];
void calc_valor_conta(stConta* pconta);
void sort_contas(stConta* pcontas, int numcontas);
void imprime_contas(stConta* pcontas, int numcontas);
int main()
{
for(int i = 0; i < NUMCONTAS; i++)
{
printf("\nDigite a conta do cliente: ");
scanf("%s", contas[i].idconta);
printf("Digite o consumo (m3): ");
scanf("%d", &(contas[i].consumo));
printf("Digite o tipo de consumidor (RESIDENCIAL, COMERCIAL, INDUSTRIAL): ");
char buff[TIPOBUFFSIZE+1] = {'\0'};
scanf("%s", buff);
if(strcmp(buff, TIPORESIDENCIAL) == 0)
contas[i].tipo = residencial;
else if(strcmp(buff, TIPOCOMERCIAL) == 0)
contas[i].tipo = comercial;
else if(strcmp(buff, TIPOINDUSTRIAL) == 0)
contas[i].tipo = industrial;
calc_valor_conta(&contas[i]);
}
sort_contas(contas, NUMCONTAS);
imprime_contas(contas, NUMCONTAS);
return 0;
}
void calc_valor_conta(stConta* pconta)
{
float taxa = 0.0f;
float totalporm3 = 0.0f;
if(pconta->tipo == residencial)
{
taxa = 5.0f;
totalporm3 = pconta->consumo * 0.05f;
}
else if(pconta->tipo == comercial)
{
taxa = 500.0f;
totalporm3 = pconta->consumo * 0.25f;
}
else if(pconta->tipo == industrial)
{
taxa = 800.0f;
totalporm3 = pconta->consumo * 0.04f;
}
pconta->valor = taxa + totalporm3;
}
void sort_contas(stConta* pcontas, int numcontas)
{
for (int i = 0; i < numcontas; ++i)
for (int j = 0; j < numcontas; j++)
{
if (pcontas[i].tipo < pcontas[j].tipo)
{
stConta tmp = pcontas[i];
pcontas[i] = pcontas[j];
pcontas[j] = tmp;
}
}
}
void imprime_contas(stConta* pcontas, int numcontas)
{
printf("\n");
for (int i = 0; i < numcontas; ++i)
{
const char* TIPO = NULL;
if(pcontas[i].tipo == residencial)
TIPO = TIPORESIDENCIAL;
if(pcontas[i].tipo == comercial)
TIPO = TIPOCOMERCIAL;
if(pcontas[i].tipo == industrial)
TIPO = TIPOINDUSTRIAL;
printf("Cliente %s '%s': valor %f\n", TIPO, pcontas[i].idconta, pcontas[i].valor);
}
}
|
the_stack_data/448566.c | #include <stdio.h>
#include <locale.h>
/*
36. Leia a altura e o raio de um cilindro circular e imprima o volume do cilindro. O volume
de um cilindro é calculado por meio da seguinte fórmula: V = π(pi) * raio² * altura, onde π = 3.141592.
*/
int main(){
setlocale(LC_ALL, "");
float altura = 0;
float raio = 0;
float volume = 0;
float pi = 3.141592;
printf("Insira a altura: ");
scanf("%f", &altura);
printf("Insira o raio: ");
scanf("%f", &raio);
volume = pi * (raio * raio) * altura;
printf("Volume: %.2f\n", volume);
return 0;
}
|
the_stack_data/173578493.c | #include <stdio.h>
#define LIST_LEN 4
int main() {
unsigned char list[LIST_LEN] = {10, 0, 2, 1};
unsigned char largest = list[0];
for (int i = 1; i < LIST_LEN; i++)
if (list[i] > largest)
largest = list[i];
printf("%d", largest);
return 0;
} |
the_stack_data/25138252.c | //
// Created by Arkadiusz Placha on 24.05.2018.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]) {
srand(time(NULL));
if (argc < 3) {
printf("Not enough arguments.\n");
exit(EXIT_FAILURE);
}
FILE *file = fopen(argv[2], "w");
if (file == NULL) {
perror("Cannot create file.");
exit(EXIT_FAILURE);
}
int c = atoi(argv[1]);
if (c <= 0) {
printf("Wrong c value.\n");
exit(EXIT_FAILURE);
}
double *tab = calloc(c * c, sizeof(double));
double sum = 0;
for (int i = 0; i < c * c; ++i) {
tab[i] = (double) (rand() + 1) / (double) RAND_MAX;
sum += tab[i];
}
for (int i = 0; i < c * c; ++i) {
tab[i] /= sum;
}
fprintf(file, "%d\n", c);
for (int i = 0; i < c; ++i) {
fprintf(file, "%lf", tab[i * c]);
for (int j = 1; j < c; ++j) {
fprintf(file, " %lf", tab[i * c + j]);
}
fprintf(file, "\n");
}
fclose(file);
return 0;
} |
the_stack_data/680830.c | // RUN: %clang_cc1 -triple i386-apple-darwin9 %s -emit-llvm -o - | FileCheck -check-prefix CHECK-X32 %s
// CHECK-X32: %struct.s0 = type { i64, i64, i32, [12 x i32] }
// CHECK-X32: %struct.s1 = type { [15 x i32], %struct.s0 }
// RUN: %clang_cc1 -triple x86_64-apple-darwin9 %s -emit-llvm -o - | FileCheck -check-prefix CHECK-X64 %s
// CHECK-X64: %struct.s0 = type <{ i64, i64, i32, [12 x i32] }>
// CHECK-X64: %struct.s1 = type { [15 x i32], %struct.s0 }
// rdar://problem/7095436
#pragma pack(4)
struct s0 {
long long a __attribute__((aligned(8)));
long long b __attribute__((aligned(8)));
unsigned int c __attribute__((aligned(8)));
int d[12];
} a;
struct s1 {
int a[15];
struct s0 b;
} b;
|
the_stack_data/184519345.c | // Include libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
#include <time.h>
clock_t start, end;
double cpu_time_used;
int isqrt(int x)
{
unsigned int opr=(unsigned int)x;
unsigned int res=0;
unsigned int one=1<<30;
while (one>opr) one>>=2;
while (one!=0) {
if (opr>=res+one) {
opr=opr-res-one;
res=res+(one<<1);
}
res>>=1;
one>>=2;
}
// if (opr>res) res++; // Round up
return (int)res;
}
int main(void)
{
start=clock();
{ /* The Timed Section */
unsigned int i;
int isqr,fsqr;
for (i=0;i<4294967295;i++) {
isqr=isqrt(i);
fsqr=(int)(sqrt((i)+0.5));
if (isqr!=fsqr) {
printf("Error %d %d %u\n",i,isqr,fsqr);
getchar();
}
}
}
end=clock();
cpu_time_used=((double)(end-start))/CLOCKS_PER_SEC;
printf("Elapsed time %lf seconds\n",cpu_time_used);
return(0);
}
|
the_stack_data/120779.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
double normalCDF(double value){
return 0.5 * erfc(-value * sqrt(0.5));
}
double B = 1.96*800.0 + 50000.0;
double A = -1.96*800.0 + 50000.0;
printf("%0.2lf\n%0.2lf", A/100.0, B/100.0);
return 0;
} |
the_stack_data/608734.c | /*
三目运算符:
表达式 ? 结果A : 结果B
三目运算符返回值:
+ 表达式为真,返回结果A
+ 表达式为假,返回结果B
注意点:
在三目运算符中,?和:是一个整体,不能单独出现
*/
#include<stdio.h>
int main() {
int res = (10 > 5) ? 10 : 5;
printf("res = %d\n", res);
return 0;
} |
the_stack_data/95449771.c | void label() {
int a = 1, b = 2;
label1:
a += b;
{
label2:
b += a;
label3:
b += a;
}
exit:
return;
} |
the_stack_data/31389032.c | #include <stdio.h>
#define Peval(cmd) printf(#cmd ": %g\n", cmd);
int main() {
double *plist = (double[]){1, 2, 3};
double list[] = {1, 2, 3};
Peval(sizeof(plist) / (sizeof(double) + 0.0));
Peval(sizeof(list) / (sizeof(double) + 0.0));
} |
the_stack_data/153267348.c | struct test {
int val;
};
int main() {
struct test t = { 1 };
return t.val;
}
|
the_stack_data/289018.c | #include <stdio.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <linux/if_tun.h>
#define RUST_CONST(name, type, printf_type) printf("pub const " #name ": " #type " = " printf_type ";\n", name);
int main() {
RUST_CONST(TUNSETIFF, c_int, "%lu")
RUST_CONST(SIOCSIFADDR, c_int, "%d")
RUST_CONST(SIOCGIFINDEX, c_int, "%d")
RUST_CONST(SIOCGIFFLAGS, c_int, "%d")
RUST_CONST(SIOCSIFFLAGS, c_int, "%d")
RUST_CONST(IFF_TUN, c_short, "%d")
RUST_CONST(IFF_TAP, c_short, "%d")
RUST_CONST(IFF_UP, c_short, "%d")
RUST_CONST(IFF_RUNNING, c_short, "%d")
RUST_CONST(IFNAMSIZ, usize, "%d")
return 0;
}
|
the_stack_data/29140.c | /*
* Benchmarks contributed by Divyesh Unadkat[1,2], Supratik Chakraborty[1], Ashutosh Gupta[1]
* [1] Indian Institute of Technology Bombay, Mumbai
* [2] TCS Innovation labs, Pune
*
*/
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern void __VERIFIER_assume(int);
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
extern int __VERIFIER_nondet_int();
int N;
int main ( ) {
N = __VERIFIER_nondet_int();
if(N <= 0) return 1;
__VERIFIER_assume(N <= 2147483647/sizeof(int));
int b[N];
int x[1];
int i, j;
x[0] = 0;
for(i = 0; i < N; i++)
{
x[0] = x[0] + N;
}
for(j = 0; j < N; j++) {
b[j] = x[0] + N*N;
}
for(j = 0; j < N; j++) {
b[j] = b[j] + N*N;
}
for(j = 0; j < N; j++) {
__VERIFIER_assert ( b[j] == 3*N*N );
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.