file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/694600.c | /* #include<stdio.h> */
/* To obtain two read effects on a and b and a warning abount inneffective update of i invall02 */
typedef struct two_fields{int one; int two[10];} tf_t;
void call02(int i, int j, int y[10], int * q[10], tf_t *p)
{
/* i can be modified locally, but it won't show in the summary
effects... which creates a problem for transformer and
precondition computation. */
i = j + 1;
y[i] = 0;
p->one = 1;
p->two[j] = 2.;
*q[i]=3;
}
main()
{
int a;
int b;
int x[10];
int * ap[10];
tf_t s;
tf_t *sp = &s;
call02(a, b, x, ap, sp);
}
|
the_stack_data/55532.c | /* EAN Check Digit Computation */
#include <stdio.h>
#include <stdlib.h>
int main() {
int ean1 = 0;
int ean2 = 0;
int ean3 = 0;
int ean4 = 0;
int ean5 = 0;
int ean6 = 0;
int ean7 = 0;
int ean8 = 0;
int ean9 = 0;
int ean10 = 0;
int ean11 = 0;
int ean12 = 0;
int checkdigit = 0;
int oddsum = 0;
int evensum = 0;
printf("Enter the first 12 digits of an EAN: ");
scanf("%01d%01d%01d%01d%01d%01d%01d%01d%01d%01d%01d%01d", &ean1, &ean2, &ean3, &ean4, &ean5, &ean6, &ean7, &ean8, &ean9, &ean10, &ean11, &ean12);
evensum = ean2 + ean4 + ean6 + ean8 + ean10 + ean12;
oddsum = ean1 + ean3 + ean5 + ean7 + ean9 + ean11;
checkdigit = 9-(((evensum*3 + oddsum)-1)%10);
printf("Check digit: %d\n", checkdigit);
return 0;
}
|
the_stack_data/72274.c | // d52cbaca0ef8cf4fd3d6354deb5066970fb6511d02d18d15835e6014ed847fb0
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <byteswap.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>
/* ltoh: little to host */
/* htol: little to host */
#if __BYTE_ORDER == __LITTLE_ENDIAN
# define ltohl(x) (x)
# define ltohs(x) (x)
# define htoll(x) (x)
# define htols(x) (x)
#elif __BYTE_ORDER == __BIG_ENDIAN
# define ltohl(x) __bswap_32(x)
# define ltohs(x) __bswap_16(x)
# define htoll(x) __bswap_32(x)
# define htols(x) __bswap_16(x)
#endif
#define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", __LINE__, __FILE__, errno, strerror(errno)); exit(1); } while(0)
#define MAP_SIZE (64*1024UL)
#define MAP_MASK (MAP_SIZE - 1)
int main(int argc, char **argv) {
int fd;
void *map_base, *virt_addr;
uint32_t read_result, writeval;
off_t target;
/* access width */
int access_width = 'w';
char *device;
/* not enough arguments given? */
if (argc < 3) {
fprintf(stderr, "\nUsage:\t%s <device> <address> [[type] data]\n"
"\tdevice : character device to access\n"
"\taddress : memory address to access\n"
"\ttype : access operation type : [b]yte, [h]alfword, [w]ord\n"
"\tdata : data to be written for a write\n\n",
argv[0]);
exit(1);
}
printf("argc = %d\n", argc);
device = strdup(argv[1]);
printf("device: %s\n", device);
target = strtoul(argv[2], 0, 0);
printf("address: 0x%08x\n", (unsigned int)target);
printf("access type: %s\n", argc >= 4? "write": "read");
/* data given? */
if (argc >= 4)
{
printf("access width given.\n");
access_width = tolower(argv[3][0]);
}
printf("access width: ");
if (access_width == 'b')
printf("byte (8-bits)\n");
else if (access_width == 'h')
printf("half word (16-bits)\n");
else if (access_width == 'w')
printf("word (32-bits)\n");
else
{
printf("word (32-bits)\n");
access_width = 'w';
}
if ((fd = open(argv[1], O_RDWR | O_SYNC)) == -1) FATAL;
printf("character device %s opened.\n", argv[1]);
fflush(stdout);
/* map one page */
map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map_base == (void *) -1) FATAL;
printf("Memory mapped at address %p.\n", map_base);
fflush(stdout);
/* calculate the virtual address to be accessed */
virt_addr = map_base + target;
/* read only */
if (argc <= 4) {
//printf("Read from address %p.\n", virt_addr);
switch(access_width) {
case 'b':
read_result = *((uint8_t *) virt_addr);
printf("Read 8-bits value at address 0x%08x (%p): 0x%02x\n", (unsigned int)target, virt_addr, (unsigned int)read_result);
break;
case 'h':
read_result = *((uint16_t *) virt_addr);
/* swap 16-bit endianess if host is not little-endian */
read_result = ltohs(read_result);
printf("Read 16-bit value at address 0x%08x (%p): 0x%04x\n", (unsigned int)target, virt_addr, (unsigned int)read_result);
break;
case 'w':
read_result = *((uint32_t *) virt_addr);
/* swap 32-bit endianess if host is not little-endian */
read_result = ltohl(read_result);
printf("Read 32-bit value at address 0x%08x (%p): 0x%08x\n", (unsigned int)target, virt_addr, (unsigned int)read_result);
return (int)read_result;
break;
default:
fprintf(stderr, "Illegal data type '%c'.\n", access_width);
exit(2);
}
fflush(stdout);
}
/* data value given, i.e. writing? */
if (argc >= 5)
{
writeval = strtoul(argv[4], 0, 0);
switch (access_width)
{
case 'b':
printf("Write 8-bits value 0x%02x to 0x%08x (0x%p)\n", (unsigned int)writeval, (unsigned int)target, virt_addr);
*((uint8_t *) virt_addr) = writeval;
#if 0
if (argc > 4) {
read_result = *((uint8_t *) virt_addr);
printf("Written 0x%02x; readback 0x%02x\n", writeval, read_result);
}
#endif
break;
case 'h':
printf("Write 16-bits value 0x%04x to 0x%08x (0x%p)\n", (unsigned int)writeval, (unsigned int)target, virt_addr);
/* swap 16-bit endianess if host is not little-endian */
writeval = htols(writeval);
*((uint16_t *) virt_addr) = writeval;
#if 0
if (argc > 4) {
read_result = *((uint16_t *) virt_addr);
printf("Written 0x%04x; readback 0x%04x\n", writeval, read_result);
}
#endif
break;
case 'w':
printf("Write 32-bits value 0x%08x to 0x%08x (0x%p)\n", (unsigned int)writeval, (unsigned int)target, virt_addr);
/* swap 32-bit endianess if host is not little-endian */
writeval = htoll(writeval);
*((uint32_t *) virt_addr) = writeval;
#if 0
if (argc > 4) {
read_result = *((uint32_t *) virt_addr);
printf("Written 0x%08x; readback 0x%08x\n", writeval, read_result);
}
#endif
break;
}
fflush(stdout);
}
if (munmap(map_base, MAP_SIZE) == -1) FATAL;
close(fd);
return 0;
}
|
the_stack_data/218893060.c | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
#include <omp.h>
//SSE STUFF
#ifdef __SSE__
#include <xmmintrin.h>
#endif
//const vars
const int XPICR = 1000;
const int YPICR = 1000;
uint IterateMandelbrot(float a, float b );//prototype
void GenerateMandleBlock(uint* buffer, int yStart, int yEnd);
int getYstep(int cahcesize, int yStart, int yEnd);
void GenMandleSSEOMP(uint* buffer, int yStart, int yEnd);
__m128i IterateMandelbrotOMPOPT( __m128 a, __m128 b );
uint* GenerateMandleCache(int yStart, int yEnd, int cachesize, int localbuffersize){
int yStep = getYstep(cachesize,yStart,yEnd);
uint* localbuffer = (uint*)malloc(sizeof(uint)*localbuffersize+1);
int i, j;
int iCnt = 0;
for(i = yStart ; i<=yEnd; i+=yStep){
j = i + yStep;
if(j>yEnd)
j = yEnd;//safely bound j
int blockSize = (int)(j - i)*XPICR;
uint* iterBuffer = (uint*)malloc(sizeof(uint)*blockSize+1);
GenerateMandleBlock(iterBuffer, i, j);
memcpy(localbuffer+(iCnt), iterBuffer, blockSize * sizeof(uint));
iCnt+=blockSize;
}
return localbuffer;
}
int getYstep(int cahcesize, int yStart, int yEnd){
int test = (((XPICR/1000)*4));
if (test <= 0)
test = 1;
int yStep = (int)((cahcesize)/test);//defines y step
if (yStep<1)
yStep = 1;
if(yStep>cahcesize)
yStep = cahcesize;
return yStep;
}
void GenerateMandleBlock(uint* buffer, int yStart, int yEnd){
omp_set_num_threads(omp_get_max_threads());
int i,j;
int iCnt = 0;
float IXRES = 1.0f/(float)XPICR;
float IYRES = 1.0f/(float)YPICR;
float a;
float b;
#pragma omp parallel for private(j, i) schedule(runtime) ordered
for(j=yStart; j < yEnd; j++ )
for(i=0; i < XPICR; i++ ){
a = -2.05f + 3.00f*(float)i*IXRES;
b = 1.10f - 2.24f*(float)j*IYRES;
#pragma omp ordered
{
buffer[iCnt++] = IterateMandelbrot(a,b);
}
}
}
void GenerateMandle(uint* buffer, int yStart, int yEnd){
int i,j;
int iCnt = 0;
float IXRES = 1.0f/(float)XPICR;
float IYRES = 1.0f/(float)YPICR;
for(j=yStart; j < yEnd; j++ )
for(i=0; i < XPICR; i++ ){
const float a = -2.05f + 3.00f*(float)i*IXRES;
const float b = 1.10f - 2.24f*(float)j*IYRES;
*(buffer++) = IterateMandelbrot(a,b);
}
}
uint IterateMandelbrot(float a, float b ){
float x, y, x2, y2;
x = x2 = 0.0f;
y = y2 = 0.0f;
float m2;
// escape time algorithm
int i;
float h = 0.0;
volatile int flag = 0;
for(i=0; i< 2048; i++ )
{
if (flag==1)
continue;
y = 2.0f*x*y+b;
x = x2-y2+a;
x2 = x*x;
y2 = y*y;
m2 = x2+y2;
if( m2>100.0f )
flag = 1;
h+=1.0;
}
h=h+1.0-log2(.5*log(m2));
return (h/100.0)*256;
}
int PPMmin(int i1, int i2){
if (i1 < i2)
return i1;
else
return i2;
}
//PPM SAVER
void MandleSavePPM(uint* MandleBuffer){
//ASCII PPM P3
FILE *fsave = fopen("result.ppm", "wt");
int i, j, k, jmax;
int index = 0;
fprintf (fsave, "P3\n");
fprintf (fsave, "%d %d\n", XPICR, YPICR);
fprintf (fsave, "%d\n", 255);
for (i = 0; i<YPICR; i++){
for (k=0; k<XPICR; k=k+4){
jmax = PPMmin(k + 4, XPICR);
for (j = k; j < jmax; j++){
index = ((j) * XPICR) + i;
fprintf (fsave, " %d %d %d", MandleBuffer[index]%256 , MandleBuffer[index]%256 , MandleBuffer[index]%256);
}
fprintf(fsave, "\n" );
}
}
fclose (fsave);
}
///SSE
uint* GenMandleSSEOMPCache(int yStart, int yEnd, int cachesize, int localbuffersize){
int yStep = getYstep(cachesize,yStart,yEnd);
uint* localbuffer = (uint*)malloc(sizeof(uint)*localbuffersize+1);
int i, j;
int iCnt = 0;
for(i = yStart ; i<=yEnd; i+=yStep){
j = i + yStep;
if(j>yEnd)
j = yEnd;//safely bound j
int blockSize = (int)(j - i)*XPICR;
uint* iterBuffer = (uint*)malloc(sizeof(uint)*blockSize+1);
GenMandleSSEOMP(iterBuffer, i, j);
memcpy(localbuffer+(iCnt), iterBuffer, blockSize * sizeof(uint));
iCnt+=blockSize;
}
return localbuffer;
}
void GenMandleSSEOMP(uint* buffer, int yStart, int yEnd){
__m128i *buffer4 = (__m128i *)buffer;
const __m128 ixres = _mm_set1_ps( 1.0f/(float)XPICR );
const __m128 iyres = _mm_set1_ps( 1.0f/(float)YPICR );
int j=0,i=0;
int iCnt = 0;
// #pragma omp parallel for schedule(runtime) private(i, j) ordered
for(j=yStart; j < yEnd; j++ )
for(i=0; i < XPICR; i+=4 )
{
__m128 a, b;
a = _mm_set_ps( i+3, i+2, i+1, i+0 );
a = _mm_mul_ps( a, ixres );
a = _mm_mul_ps( a, _mm_set1_ps( 3.00f) );
a = _mm_add_ps( a, _mm_set1_ps(-2.25f) );
b = _mm_set1_ps( (float)j );
b = _mm_mul_ps( b, iyres );
b = _mm_mul_ps( b, _mm_set1_ps(-2.24f) );
b = _mm_add_ps( b, _mm_set1_ps( 1.12f) );
// #pragma omp ordered
{
_mm_store_si128( buffer4++, IterateMandelbrotOMPOPT( a, b ));
}
}
}
inline __m128i IterateMandelbrotOMPOPT( __m128 a, __m128 b ){
__m128 x, y, x2, y2, m2;
__m128 co, ite;
unsigned int i;
const __m128 one = _mm_set1_ps(1.0f);
const __m128 th = _mm_set1_ps(4.0f);
x = _mm_setzero_ps();
y = _mm_setzero_ps();
x2 = _mm_setzero_ps();
y2 = _mm_setzero_ps();
co = _mm_setzero_ps();
ite = _mm_setzero_ps();
//volatile int flag=0;
for( i=0; i < 2048; i++ ){
y = _mm_mul_ps( x, y );
y = _mm_add_ps( _mm_add_ps(y,y), b );
x = _mm_add_ps( _mm_sub_ps(x2,y2), a );
x2 = _mm_mul_ps( x, x );
y2 = _mm_mul_ps( y, y );
m2 = _mm_add_ps(x2,y2);
co = _mm_or_ps( co, _mm_cmpgt_ps( m2, th ) );
ite = _mm_add_ps( ite, _mm_andnot_ps( co, one ) );
if( _mm_movemask_ps( co )==0x0f )
break;
}
// create color
const __m128i bb = _mm_cvtps_epi32( ite );
const __m128i gg = _mm_slli_si128( bb, 1 );
const __m128i rr = _mm_slli_si128( bb, 2 );
const __m128i color = _mm_or_si128( _mm_or_si128(rr,gg),bb );
return( color );
}
|
the_stack_data/18565.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STRINGS 10
//соединяет left с right
//возвращает "цену" пересечения left и right
int get_intersection_cost(char* left,char* right){
int i;
if (strlen(left)>0)
for (i=0;i!=strlen(left);i++){
unsigned int right_index = 0;
unsigned int left_index = i;
while((left[left_index]==right[right_index])&&
(left_index<strlen(left))&&
(right_index<strlen(right))){
left_index++;
right_index++;
}
if (left_index==strlen(left)){
//есть пересечение длиной (left_index - i)
return strlen(left) - (left_index - i);
}
}
return strlen(left);
}
typedef struct {
int num;
int lengths[MAX_STRINGS];
} node, *pnode;
void calculate_intersections(char** strings,int count, int current_index,pnode pl){
int i;
char* current_string = strings[current_index];
for (i=0;i!=count;i++)
if (i!=current_index)
pl->lengths[i] = get_intersection_cost(current_string,strings[i]);
}
int min_length = 0;
int min_path[MAX_STRINGS];
void get_min_length(
pnode current_node,
pnode other_nodes,
int other_nodes_count,
int* visited_nodes_nums,
int visited_nodes_count,
int sum_len){
//необходимо обойти все узлы из all_nodes
//кроме current_node и тех, что перечислены в prev_nodes_nums
if (visited_nodes_count == other_nodes_count - 1){
//больше двигаться некуда.
if (sum_len<min_length){
visited_nodes_nums[visited_nodes_count] = current_node->num;
min_length = sum_len;
memcpy(min_path,visited_nodes_nums,MAX_STRINGS*sizeof(int));
}
} else{
int i;
//ищем следующий узел
for (i=0;i!=other_nodes_count;i++){
int k,wf=0;
pnode pn = &(other_nodes[i]);
int length_to_pn;
int _sum, _v_count;
int _visited_nodes[MAX_STRINGS];
//пропускаем текущий узел
if (other_nodes[i].num == current_node->num)
continue;
//проверяем pn - нет-ли его в пройденном маршруте?
if (visited_nodes_count)
for (k=0;k!=visited_nodes_count;k++)
if (pn->num == visited_nodes_nums[k]){
wf=1;
break;
}
if (wf)
continue;
//следующий узел - pn
length_to_pn = current_node->lengths[pn->num];
_sum = sum_len + length_to_pn;
memset(_visited_nodes,0,MAX_STRINGS*sizeof(int));
memcpy(_visited_nodes,visited_nodes_nums,visited_nodes_count*sizeof(int));
_visited_nodes[visited_nodes_count] = current_node->num;
_v_count = visited_nodes_count + 1;
get_min_length(pn,other_nodes,other_nodes_count,_visited_nodes,_v_count,_sum);
}
}
}
int get_result_length(char** strings, int* path,node* nodes,int count){
//считаем длину результ. строки
int i;
int res_len = 0;
for (i=0;i!=count;i++){
int current_string_index = path[i];
char* c_string = strings[current_string_index];
res_len += strlen(c_string);
if (i>0){
//отнимаем кол-во символов, которое попало в пересечение строк (i+1) и (i)
//aaaaaaaccc
// cccbbbbbb
int prev_string_index = path[i-1];
node n = nodes[prev_string_index];
int cost = n.lengths[current_string_index];
char* prev_string = strings[prev_string_index];
int intersec_len = strlen(prev_string) - cost;
res_len -= intersec_len;
}
}
return res_len;
}
int main(int argc,char** argv)
{
int i;
int N;
node ints[MAX_STRINGS];
pnode plens;
char *strings[MAX_STRINGS];
memset(strings,0,MAX_STRINGS*sizeof(char*));
scanf("%d",&N);
i = 0;
while(i!=N){
strings[i] = (char*)malloc(1024); //макс. длина строки в условиях не указана
scanf("%s",strings[i]);
i++;
}
memset(ints,0,MAX_STRINGS*sizeof(node));
//считаем пересечения строк (каждая с каждой)
plens = ints;
for (i=0;i!=N;i++,plens++){
calculate_intersections(strings,N,i,plens);
plens->num = i;
}
min_length = 0xFFFFFF;
memset(min_path,0,MAX_STRINGS*sizeof(int));
for (i=0;i!=N;i++){
int visited_nodes[MAX_STRINGS];
memset(visited_nodes,0,MAX_STRINGS*sizeof(int));
get_min_length(&(ints[i]),ints,N,visited_nodes,0,0);
}
//вывод на экран последовательности соединения строк
//for (i=0;i!=N;i++)
// printf("%d\n",min_path[i]);
min_length = get_result_length(strings,min_path,ints,N);
printf("%d\n",min_length);
for (i=0;i!=N;i++)
if (strings[i]!=0)
free(strings[i]);
return 0;
} |
the_stack_data/137792.c | #include<stdio.h>
double f(int x);
int main()
{
int m, n, X;
scanf("%d %d", &m, &n);
X=f(m)/(f(n)*f(m-n));
printf("%d", X);
return 0;
}
double f(int x)
{
int i;
double f;
f=1;
for(i=1;i<=x;i++)
f = f*i;
return f;
} |
the_stack_data/206392827.c | /*!
* t-bloom.c - bloom test for lcdb
* Copyright (c) 2022, Christopher Jeffrey (MIT License).
* https://github.com/chjj/lcdb
*
* Parts of this software are based on google/leveldb:
* Copyright (c) 2011, The LevelDB Authors. All rights reserved.
* https://github.com/google/leveldb
*
* See LICENSE for more information.
*/
int
ldb_test_bloom(void);
int main(void) {
return ldb_test_bloom();
}
|
the_stack_data/248579392.c | #include<stdio.h>
int main()
{
int m,n,i,k,p;
scanf("%d%d",&m,&n);
k=m;p = 1;
for(i = 1;i<n;i++){
k = k*(m-1);m--;
}
for(i = 1;i<n;i++){
p = p*(i+1);
}
printf("%d",k/p);
} |
the_stack_data/479143.c | /* main.c XL main */
main()
{
statements();
}
|
the_stack_data/57861.c | #include "stdio.h"
#include "unistd.h"
#include "stdlib.h"
int main(int argc, char **argv) {
char * const args[] = {
"top", "-d", "2", "-n", "10", NULL
};
if (execvp("/bin/top", args)) {
perror("execl failed:");
exit(1);
}
return 0; } |
the_stack_data/103265338.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function mul8_033
/// Library = EvoApprox8b
/// Circuit = mul8_033
/// Area (180) = 6565
/// Delay (180) = 5.670
/// Power (180) = 2883.70
/// Area (45) = 477
/// Delay (45) = 2.070
/// Power (45) = 249.70
/// Nodes = 111
/// HD = 283640
/// MAE = 137.64789
/// MSE = 36798.22656
/// MRE = 3.08 %
/// WCE = 817
/// WCRE = 100 %
/// EP = 95.9 %
uint16_t mul8_033(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 n32;
uint8_t n33;
uint8_t n34;
uint8_t n35;
uint8_t n38;
uint8_t n39;
uint8_t n41;
uint8_t n47;
uint8_t n50;
uint8_t n66;
uint8_t n67;
uint8_t n69;
uint8_t n77;
uint8_t n82;
uint8_t n93;
uint8_t n94;
uint8_t n102;
uint8_t n103;
uint8_t n114;
uint8_t n115;
uint8_t n132;
uint8_t n148;
uint8_t n182;
uint8_t n232;
uint8_t n248;
uint8_t n264;
uint8_t n282;
uint8_t n364;
uint8_t n365;
uint8_t n382;
uint8_t n398;
uint8_t n399;
uint8_t n414;
uint8_t n415;
uint8_t n514;
uint8_t n532;
uint8_t n548;
uint8_t n614;
uint8_t n632;
uint8_t n648;
uint8_t n664;
uint8_t n665;
uint8_t n682;
uint8_t n683;
uint8_t n732;
uint8_t n748;
uint8_t n764;
uint8_t n782;
uint8_t n798;
uint8_t n814;
uint8_t n832;
uint8_t n844;
uint8_t n845;
uint8_t n865;
uint8_t n882;
uint8_t n883;
uint8_t n898;
uint8_t n899;
uint8_t n914;
uint8_t n915;
uint8_t n932;
uint8_t n933;
uint8_t n948;
uint8_t n949;
uint8_t n964;
uint8_t n982;
uint8_t n998;
uint8_t n1014;
uint8_t n1032;
uint8_t n1048;
uint8_t n1064;
uint8_t n1082;
uint8_t n1099;
uint8_t n1114;
uint8_t n1115;
uint8_t n1132;
uint8_t n1148;
uint8_t n1149;
uint8_t n1164;
uint8_t n1165;
uint8_t n1182;
uint8_t n1183;
uint8_t n1198;
uint8_t n1199;
uint8_t n1214;
uint8_t n1215;
uint8_t n1232;
uint8_t n1248;
uint8_t n1264;
uint8_t n1282;
uint8_t n1298;
uint8_t n1314;
uint8_t n1332;
uint8_t n1348;
uint8_t n1364;
uint8_t n1382;
uint8_t n1383;
uint8_t n1398;
uint8_t n1399;
uint8_t n1414;
uint8_t n1415;
uint8_t n1432;
uint8_t n1433;
uint8_t n1448;
uint8_t n1449;
uint8_t n1464;
uint8_t n1465;
uint8_t n1482;
uint8_t n1483;
uint8_t n1498;
uint8_t n1514;
uint8_t n1532;
uint8_t n1548;
uint8_t n1564;
uint8_t n1582;
uint8_t n1598;
uint8_t n1614;
uint8_t n1632;
uint8_t n1648;
uint8_t n1664;
uint8_t n1665;
uint8_t n1682;
uint8_t n1683;
uint8_t n1698;
uint8_t n1699;
uint8_t n1714;
uint8_t n1715;
uint8_t n1732;
uint8_t n1733;
uint8_t n1748;
uint8_t n1749;
uint8_t n1764;
uint8_t n1782;
uint8_t n1798;
uint8_t n1814;
uint8_t n1832;
uint8_t n1848;
uint8_t n1849;
uint8_t n1864;
uint8_t n1882;
uint8_t n1898;
uint8_t n1899;
uint8_t n1914;
uint8_t n1915;
uint8_t n1932;
uint8_t n1933;
uint8_t n1948;
uint8_t n1949;
uint8_t n1964;
uint8_t n1965;
uint8_t n1982;
uint8_t n1983;
uint8_t n1998;
uint8_t n1999;
uint8_t n2014;
uint8_t n2015;
n32 = ~(n18 | n14);
n33 = ~(n18 | n14);
n34 = ~((n33 | n32) & n14);
n35 = ~((n33 | n32) & n14);
n38 = ~(n6 | n34 | n10);
n39 = ~(n6 | n34 | n10);
n41 = n28 & n38;
n47 = ~((n26 | n16) & n41);
n50 = ~(n39 & n28);
n66 = n47 | n28;
n67 = n47 | n28;
n69 = ~n41;
n77 = ~(n10 & n12);
n82 = n6 & n20;
n93 = ~(n10 | n66);
n94 = ~((n77 & n67) | n18);
n102 = ~((n26 | n50) & n35);
n103 = ~((n26 | n50) & n35);
n114 = n103 & n50;
n115 = n103 & n50;
n132 = n94 & n16;
n148 = n14 & n16;
n182 = n93 & n0;
n232 = n8 & n18;
n248 = n10 & n18;
n264 = n12 & n18;
n282 = n14 & n18;
n364 = n114 ^ n232;
n365 = n114 & n232;
n382 = n132 | n248;
n398 = n148 ^ n264;
n399 = n148 & n264;
n414 = n399 ^ n282;
n415 = n399 & n282;
n514 = n10 & n20;
n532 = n12 & n20;
n548 = n14 & n20;
n614 = n364 | n82;
n632 = n382 ^ n102;
n648 = n398 | n514;
n664 = n414 ^ n532;
n665 = n414 & n532;
n682 = (n415 ^ n548) ^ n665;
n683 = (n415 & n548) | (n548 & n665) | (n415 & n665);
n732 = n4 & n22;
n748 = n6 & n22;
n764 = n8 & n22;
n782 = n10 & n22;
n798 = n12 & n22;
n814 = n14 & n22;
n832 = n665;
n844 = ~n69;
n845 = ~n69;
n865 = n614 | n732;
n882 = (n632 ^ n748) ^ n865;
n883 = (n632 & n748) | (n748 & n865) | (n632 & n865);
n898 = (n648 ^ n764) ^ n883;
n899 = (n648 & n764) | (n764 & n883) | (n648 & n883);
n914 = (n664 ^ n782) ^ n899;
n915 = (n664 & n782) | (n782 & n899) | (n664 & n899);
n932 = (n682 ^ n798) ^ n915;
n933 = (n682 & n798) | (n798 & n915) | (n682 & n915);
n948 = (n683 ^ n814) ^ n933;
n949 = (n683 & n814) | (n814 & n933) | (n683 & n933);
n964 = ~n949;
n982 = n845 & n24;
n998 = n4 & n844;
n1014 = n6 & n24;
n1032 = n8 & n24;
n1048 = n10 & n24;
n1064 = n12 & n24;
n1082 = n14 & n24;
n1099 = n365 & n964;
n1114 = (n41 ^ n982) ^ n1099;
n1115 = (n41 & n982) | (n982 & n1099) | (n41 & n1099);
n1132 = (n1115 & n998) | (~n1115 & n882);
n1148 = n898 ^ n1014;
n1149 = n898 & n1014;
n1164 = (n914 ^ n1032) ^ n1149;
n1165 = (n914 & n1032) | (n1032 & n1149) | (n914 & n1149);
n1182 = (n932 ^ n1048) ^ n1165;
n1183 = (n932 & n1048) | (n1048 & n1165) | (n932 & n1165);
n1198 = (n948 ^ n1064) ^ n1183;
n1199 = (n948 & n1064) | (n1064 & n1183) | (n948 & n1183);
n1214 = (n949 ^ n1082) ^ n1199;
n1215 = (n949 & n1082) | (n1082 & n1199) | (n949 & n1199);
n1232 = n0 & n26;
n1248 = n2 & n26;
n1264 = n4 & n26;
n1282 = n6 & n26;
n1298 = n8 & n26;
n1314 = n10 & n26;
n1332 = n12 & n26;
n1348 = n14 & n26;
n1364 = n1114 | n1232;
n1382 = n1132 ^ n1248;
n1383 = n1132 & n1248;
n1398 = (n1148 ^ n1264) ^ n1383;
n1399 = (n1148 & n1264) | (n1264 & n1383) | (n1148 & n1383);
n1414 = (n1164 ^ n1282) ^ n1399;
n1415 = (n1164 & n1282) | (n1282 & n1399) | (n1164 & n1399);
n1432 = (n1182 ^ n1298) ^ n1415;
n1433 = (n1182 & n1298) | (n1298 & n1415) | (n1182 & n1415);
n1448 = (n1198 ^ n1314) ^ n1433;
n1449 = (n1198 & n1314) | (n1314 & n1433) | (n1198 & n1433);
n1464 = (n1214 ^ n1332) ^ n1449;
n1465 = (n1214 & n1332) | (n1332 & n1449) | (n1214 & n1449);
n1482 = (n1215 ^ n1348) ^ n1465;
n1483 = (n1215 & n1348) | (n1348 & n1465) | (n1215 & n1465);
n1498 = n0 & n28;
n1514 = n2 & n28;
n1532 = n4 & n28;
n1548 = n6 & n28;
n1564 = n8 & n28;
n1582 = n10 & n28;
n1598 = n12 & n28;
n1614 = n14 & n28;
n1632 = n1382 ^ n1498;
n1648 = n1398 ^ n1514;
n1664 = n1414 ^ n1532;
n1665 = n1414 & n1532;
n1682 = (n1432 ^ n1548) ^ n1665;
n1683 = (n1432 & n1548) | (n1548 & n1665) | (n1432 & n1665);
n1698 = (n1448 ^ n1564) ^ n1683;
n1699 = (n1448 & n1564) | (n1564 & n1683) | (n1448 & n1683);
n1714 = (n1464 ^ n1582) ^ n1699;
n1715 = (n1464 & n1582) | (n1582 & n1699) | (n1464 & n1699);
n1732 = (n1482 ^ n1598) ^ n1715;
n1733 = (n1482 & n1598) | (n1598 & n1715) | (n1482 & n1715);
n1748 = (n1483 ^ n1614) ^ n1733;
n1749 = (n1483 & n1614) | (n1614 & n1733) | (n1483 & n1733);
n1764 = n0 & n30;
n1782 = n2 & n30;
n1798 = n4 & n30;
n1814 = n6 & n30;
n1832 = n8 & n30;
n1848 = n10 & n30;
n1849 = n10 & n30;
n1864 = n12 & n30;
n1882 = n14 & n30;
n1898 = n1648 ^ n1764;
n1899 = n1648 & n1764;
n1914 = (n1664 ^ n1782) ^ n1899;
n1915 = (n1664 & n1782) | (n1782 & n1899) | (n1664 & n1899);
n1932 = (n1682 ^ n1798) ^ n1915;
n1933 = (n1682 & n1798) | (n1798 & n1915) | (n1682 & n1915);
n1948 = (n1698 ^ n1814) ^ n1933;
n1949 = (n1698 & n1814) | (n1814 & n1933) | (n1698 & n1933);
n1964 = (n1714 ^ n1832) ^ n1949;
n1965 = (n1714 & n1832) | (n1832 & n1949) | (n1714 & n1949);
n1982 = (n1732 ^ n1848) ^ n1965;
n1983 = (n1732 & n1848) | (n1848 & n1965) | (n1732 & n1965);
n1998 = (n1748 ^ n1864) ^ n1983;
n1999 = (n1748 & n1864) | (n1864 & n1983) | (n1748 & n1983);
n2014 = (n1749 ^ n1882) ^ n1999;
n2015 = (n1749 & n1882) | (n1882 & n1999) | (n1749 & n1999);
c |= (n1849 & 0x1) << 0;
c |= (n182 & 0x1) << 1;
c |= (n115 & 0x1) << 2;
c |= (n832 & 0x1) << 3;
c |= (n1165 & 0x1) << 4;
c |= (n1364 & 0x1) << 5;
c |= (n1632 & 0x1) << 6;
c |= (n1898 & 0x1) << 7;
c |= (n1914 & 0x1) << 8;
c |= (n1932 & 0x1) << 9;
c |= (n1948 & 0x1) << 10;
c |= (n1964 & 0x1) << 11;
c |= (n1982 & 0x1) << 12;
c |= (n1998 & 0x1) << 13;
c |= (n2014 & 0x1) << 14;
c |= (n2015 & 0x1) << 15;
return c;
}
|
the_stack_data/410889.c | /* $OpenBSD: sleep.c,v 1.19 2009/10/27 23:59:22 deraadt Exp $ */
/* $NetBSD: sleep.c,v 1.8 1995/03/21 09:11:11 cgd Exp $ */
/*
* Copyright (c) 1988, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <ctype.h>
#include <errno.h>
#include <locale.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
extern char *__progname;
void usage(void);
void alarmh(int);
int
main(int argc, char *argv[])
{
int ch;
time_t secs = 0, t;
char *cp;
long nsecs = 0;
struct timespec rqtp;
int i;
setlocale(LC_ALL, "");
signal(SIGALRM, alarmh);
while ((ch = getopt(argc, argv, "")) != -1)
switch(ch) {
default:
usage();
}
argc -= optind;
argv += optind;
if (argc != 1)
usage();
cp = *argv;
while ((*cp != '\0') && (*cp != '.')) {
if (!isdigit(*cp))
usage();
t = (secs * 10) + (*cp++ - '0');
if (t / 10 != secs) /* oflow */
return (EINVAL);
secs = t;
}
/* Handle fractions of a second */
if (*cp == '.') {
cp++;
for (i = 100000000; i > 0; i /= 10) {
if (*cp == '\0')
break;
if (!isdigit(*cp))
usage();
nsecs += (*cp++ - '0') * i;
}
/*
* We parse all the way down to nanoseconds
* in the above for loop. Be pedantic about
* checking the rest of the argument.
*/
while (*cp != '\0') {
if (!isdigit(*cp++))
usage();
}
}
rqtp.tv_sec = secs;
rqtp.tv_nsec = nsecs;
if ((secs > 0) || (nsecs > 0))
if (nanosleep(&rqtp, NULL))
return (errno);
return (0);
}
void
usage(void)
{
(void)fprintf(stderr, "usage: %s seconds\n", __progname);
exit(1);
}
/*
* POSIX 1003.2 says sleep should exit with 0 return code on reception
* of SIGALRM.
*/
/* ARGSUSED */
void
alarmh(int signo)
{
/*
* exit() flushes stdio buffers, which is not legal in a signal
* handler. Use _exit().
*/
_exit(0);
}
|
the_stack_data/36075417.c | // RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s
void test() {
#pragma omp target
#pragma omp teams
;
}
// CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc>
// CHECK: `-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-teams.c:3:1, line:7:1> line:3:6 test 'void ()'
// CHECK-NEXT: `-CompoundStmt {{.*}} <col:13, line:7:1>
// CHECK-NEXT: `-OMPTargetDirective {{.*}} <line:4:9, col:19>
// CHECK-NEXT: `-CapturedStmt {{.*}} <line:5:9, col:18>
// CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: |-CapturedStmt {{.*}} <col:9, col:18>
// CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-OMPTeamsDirective {{.*}} <col:9, col:18> openmp_structured_block
// CHECK-NEXT: | | `-CapturedStmt {{.*}} <line:6:3>
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-NullStmt {{.*}} <col:3> openmp_structured_block
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | `-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams.c:5:9) *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams.c:4:9) *const restrict'
// CHECK-NEXT: | |-RecordDecl {{.*}} <line:5:9> col:9 implicit struct definition
// CHECK-NEXT: | | `-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-NullStmt {{.*}} <line:6:3> openmp_structured_block
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | `-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams.c:5:9) *const restrict'
// CHECK-NEXT: |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit .global_tid. 'const int'
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict'
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const'
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams.c:4:9) *const restrict'
// CHECK-NEXT: |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition
// CHECK-NEXT: | `-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: |-OMPTeamsDirective {{.*}} <line:5:9, col:18> openmp_structured_block
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:6:3>
// CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-NullStmt {{.*}} <col:3> openmp_structured_block
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | `-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams.c:5:9) *const restrict'
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams.c:4:9) *const restrict'
// CHECK-NEXT: |-RecordDecl {{.*}} <line:5:9> col:9 implicit struct definition
// CHECK-NEXT: | `-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: |-NullStmt {{.*}} <line:6:3> openmp_structured_block
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: `-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams.c:5:9) *const restrict'
|
the_stack_data/40764163.c | #include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
char* ltrim(char*);
char* rtrim(char*);
int parse_int(char*);
/*
* Complete the 'getMax' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts STRING_ARRAY operations as parameter.
*/
/*
* To return the integer array from the function, you should:
* - Store the size of the array to be returned in the result_count variable
* - Allocate the array statically or dynamically
*
* For example,
* int* return_integer_array_using_static_allocation(int* result_count) {
* *result_count = 5;
*
* static int a[5] = {1, 2, 3, 4, 5};
*
* return a;
* }
*
* int* return_integer_array_using_dynamic_allocation(int* result_count) {
* *result_count = 5;
*
* int *a = malloc(5 * sizeof(int));
*
* for (int i = 0; i < 5; i++) {
* *(a + i) = i + 1;
* }
*
* return a;
* }
*
*/
int* getMax(int operations_count, char** operations, int* result_count) {
int *stack = malloc(sizeof(int) * 100000);
int *maxStack = malloc(sizeof(int) * 100000);
int *result = malloc(sizeof(int) * 100000);
int size = 0;
int maxSize = 0;
for (int i = 0; i < operations_count; i++) {
char *op = operations[i];
if (op[0] == '1') {
int v = atoi(op + 1);
stack[size++] = v;
if (maxSize == 0 || (v >= maxStack[maxSize-1])) {
maxStack[maxSize++] = v;
}
} else if (op[0] == '2') {
int v = stack[--size];
if (v == maxStack[maxSize-1]) {
--maxSize;
}
} else if (op[0] == '3') {
result[*result_count] = maxStack[maxSize-1];
(*result_count)++;
}
}
for (int i = 0; i < size; i++) {
printf("%d ", stack[i]);
}
printf("\n");
for (int i = 0; i < maxSize; i++) {
printf("%d ", maxStack[i]);
}
printf("\n");
return result;
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
int n = parse_int(ltrim(rtrim(readline())));
char** ops = malloc(n * sizeof(char*));
for (int i = 0; i < n; i++) {
char* ops_item = readline();
*(ops + i) = ops_item;
}
int res_count;
int* res = getMax(n, ops, &res_count);
for (int i = 0; i < res_count; i++) {
fprintf(fptr, "%d", *(res + i));
if (i != res_count - 1) {
fprintf(fptr, "\n");
}
}
fprintf(fptr, "\n");
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\0';
break;
}
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
data = realloc(data, data_length);
if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
char* ltrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
while (*str != '\0' && isspace(*str)) {
str++;
}
return str;
}
char* rtrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
char* end = str + strlen(str) - 1;
while (end >= str && isspace(*end)) {
end--;
}
*(end + 1) = '\0';
return str;
}
int parse_int(char* str) {
char* endptr;
int value = strtol(str, &endptr, 10);
if (endptr == str || *endptr != '\0') {
exit(EXIT_FAILURE);
}
return value;
}
|
the_stack_data/98574260.c | # include <stdio.h>
# include <ctype.h>
void main()
{
char ch;
printf("Please enter some text(input a point to quit).\n");
do{
ch = getchar();
if(islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
putchar(ch);
} while(ch != '.');
} |
the_stack_data/28262257.c | #include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b) {
int t = *b;
*b = *a;
*a = t;
}
void insertionsort(int* arr, int begin, int end) {
int i, j;
for (i=begin+1; i<end; i++) {
for (j=i-1; j>=begin; j--) {
if (arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]);
else break;
}
}
}
int main() {
int num;
int* data;
scanf("%d", &num);
data = malloc(sizeof(int) * num);
int i;
for (i=0; i<num; i++) {
scanf("%d", &data[i]);
}
insertionsort(data, 0, num);
for (i=0; i<num; i++) {
printf("%d ", data[i]);
}
printf("\n");
return 0;
}
|
the_stack_data/14201183.c |
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <time.h>
#include <unistd.h>
#define NUM_PHIL 5
#define NUM_FORK 5
sem_t forks[NUM_FORK];
int randomInRange(int min, int max){
return min + random()% ((max - min)+1);
}
void *life(void *threadid)
{
long tid;
tid = (long)threadid;
srandom((tid+1)*time(NULL));
while(1){
printf("soy el phil %ld y quiero mis tenedores \n",tid);
if(tid % 2 == 0){
//tomar izquierdo
sem_wait(&forks[(tid+1)& NUM_FORK]);
//tomar derecho
sem_wait(&forks[tid]);
}else {
//tomo derecho
sem_wait(&forks[tid]);
//tomo izquierdo
sem_wait(&forks[(tid+1)& NUM_FORK]);
}
//comer
printf("soy el phil %ld y voy a comer \n", tid);
sleep(randomInRange(5,20));
//Regresa tenedores
sem_post(&forks[tid]);
sem_post(&forks[(tid+1)& NUM_FORK]);
//pensar
printf("soy el phil %ld y voy a pensar \n", tid);
sleep(randomInRange(5,20));
}
}
int main(int argc, char *argv[])
{
pthread_t philosophers[NUM_PHIL];
int rc;
long t;
for(t=0;t<NUM_PHIL;t++){
sem_init(&forks[t],0,1);
}
for(t=0;t<NUM_PHIL;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&philosophers[t], NULL, life, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
} |
the_stack_data/688997.c | extern void *malloc(__SIZE_TYPE__);
extern void abort(void);
extern void free(void *);
typedef struct SEntry
{
unsigned char num;
} TEntry;
typedef struct STable
{
TEntry data[2];
} TTable;
TTable *init ()
{
return malloc(sizeof(TTable));
}
void
expect_func (int a, unsigned char *b) __attribute__ ((noinline));
static inline void
inlined_wrong (TEntry *entry_p, int flag);
void
inlined_wrong (TEntry *entry_p, int flag)
{
unsigned char index;
entry_p->num = 0;
if (flag == 0)
abort();
for (index = 0; index < 1; index++)
entry_p->num++;
if (!entry_p->num)
{
abort();
}
}
void
expect_func (int a, unsigned char *b)
{
if (abs ((a == 0)))
abort ();
if (abs ((b == 0)))
abort ();
}
int
main ()
{
unsigned char index = 0;
TTable *table_p = init();
TEntry work;
inlined_wrong (&(table_p->data[1]), 1);
expect_func (1, &index);
inlined_wrong (&work, 1);
free (table_p);
return 0;
}
|
the_stack_data/600693.c | #include <stdio.h>
void main() {
int i;
for (i = 1; i <= 9; i++) {
printf("2 * %d = %d\n", i, 2 * i);
}
}
|
the_stack_data/234518509.c | int Factorial(int n)
{
int fact = 1;
int m = 1;
do {
fact *= m;
m++;
} while(m < n);
return m;
}
|
the_stack_data/151705328.c | #ifdef MP_PYTHON_LIB
#include "MPGLKMC.h"
#include <numpy/arrayobject.h>
static PyObject *PyKMCTextBitmap(PyObject *self, PyObject *args, PyObject *kwds)
{
const char *string;
int font_type;
static char *kwlist[] = { "string", "font_type", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwds, "si", kwlist, &string, &font_type)) {
return NULL;
}
MPGL_TextBitmap(string, font_type);
Py_RETURN_NONE;
}
static PyMethodDef MPGLKMCPyMethods[] = {
{ "text_bitmap", (PyCFunction)PyKMCTextBitmap, METH_VARARGS | METH_KEYWORDS,
"text_bitmap(string, font_type) : draw text" },
{ NULL } /* Sentinel */
};
#ifdef PY3
static struct PyModuleDef MPGLKMCPyModule = {
PyModuleDef_HEAD_INIT,
"MPGLKMC",
NULL,
-1,
MPGLKMCPyMethods,
};
#endif
#ifndef PY3
PyMODINIT_FUNC initMPGLKMC(void)
#else
PyMODINIT_FUNC PyInit_MPGLKMC(void)
#endif
{
PyObject *m;
#ifndef PY3
if (PyType_Ready(&MPGL_KMCDrawDataPyType) < 0) return;
if (PyType_Ready(&MPGL_ModelPyType) < 0) return;
if (PyType_Ready(&MPGL_ColormapPyType) < 0) return;
if (PyType_Ready(&MPGL_ScenePyType) < 0) return;
m = Py_InitModule3("MPGLKMC", MPGLKMCPyMethods, "MPGLKMC extention");
if (m == NULL) return;
#else
if (PyType_Ready(&MPGL_KMCDrawDataPyType) < 0) return NULL;
if (PyType_Ready(&MPGL_ModelPyType) < 0) return NULL;
if (PyType_Ready(&MPGL_ColormapPyType) < 0) return NULL;
if (PyType_Ready(&MPGL_ScenePyType) < 0) return NULL;
m = PyModule_Create(&MPGLKMCPyModule);
if (m == NULL) return NULL;
#endif
import_array();
Py_INCREF(&MPGL_KMCDrawDataPyType);
PyModule_AddObject(m, "draw", (PyObject *)&MPGL_KMCDrawDataPyType);
Py_INCREF(&MPGL_ModelPyType);
PyModule_AddObject(m, "model", (PyObject *)&MPGL_ModelPyType);
Py_INCREF(&MPGL_ColormapPyType);
PyModule_AddObject(m, "colormap", (PyObject *)&MPGL_ColormapPyType);
Py_INCREF(&MPGL_ScenePyType);
PyModule_AddObject(m, "scene", (PyObject *)&MPGL_ScenePyType);
#ifdef PY3
return m;
#endif
}
#endif /* MP_PYTHON_LIB */ |
the_stack_data/148577181.c | /*Exercise 4 - Functions
Implement the three functions minimum(), maximum() and multiply() below the main() function.
Do not change the code given in the main() function when you are implementing your solution.*/
#include <stdio.h>
int minimum(int no1, int no2);
int maximum(int no1, int no2);
int multiply(int no1, int no2);
int main() {
int no1, no2;
printf("Enter a value for no 1 : ");
scanf("%d", &no1);
printf("Enter a value for no 2 : ");
scanf("%d", &no2);
printf("%d ", minimum(no1, no2));
printf("%d ", maximum(no1, no2));
printf("%d ", multiply(no1, no2));
return 0;
}
int minimum(int no1, int no2)
{
if(no1 < no2)
return no1;
else if(no1>no2)
return no2;
else
return 0;
}
int maximum(int no1, int no2)
{
if(no1> no2)
return no1;
else if(no1 < no2)
return no2;
else
return 0;
}
int multiply( int no1,int no2)
{
int mul;
return mul = no1 * no2;
} |
the_stack_data/129556.c | #include <stdlib.h>
int main() {
volatile long *arr = malloc(10 * sizeof(long));
arr[5] = 23;
arr[4] = 65;
return arr[5] + arr[4];
}
|
the_stack_data/190767282.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int correl(float x[],float y[],float *z,int npts,int lags,float *rmax,int *kmax);
int nint(double x);
int stats_c(float x[], int npts, int k, float *mean, float *stdev, float *skew, float *kurtosis);
int get_tau(float y1[],float y2[],double tstart1,double tstart2,int npts,
float laglen,double sr,double *tau,float *ccc,float *cccp)
/*
This function cross-correlates time series.
It is assumed that the time series are float arrays in y1 and y2.
The additional array z is created to hold the cross-correlation series.
y1,y2: data series to be cross-correlated
tstart1,2 start times (epoch seconds) of data series
npts: length of the two series
sr: sampling rate of the two series (not a whole number)
laglen: maximum amount (seconds) of offset for cross-correlation
laglen << npts/sr (laglen ~ 0.2 npts/sr is typical)
tau: signal time diff. (epoch seconds) of second - first
(This closely reflects the origin time difference.)
ccc: cross-correlation coefficient (-1 <= ccc <= 1)
cccp: relative amplitude of second event over first event
return value:0 -- no error
1 -- real sample rate too far from integer value
2 -- number of requested lags is larger than length of series
3 -- divisor = 0.0 in computing refined tau
*/
{
int iret,len,isr,lags,kmax,i,j,k;
float *z;
float dummy,amean1,amean2,stdev1,stdev2,del,tmax,rmax;
float ym,y0,yp,a,b,c,tpeak,tshift;
float tol=0.01;
/*tol is the tolerance to allow the real sampling rate to deviate from an
integer value; for instance for tol = 0.01, 99.99 and 100.01 are
acceptable and are taken to be nominally 100. This value is set here
to 0.01, and will produce only up to 1/10 of a millisecond error in 1 sec.*/
/*Check if sample rate is nearly integer. Some tolerance must be allowed
because sample rates given by CSS3.0 data may not be exactly whole
numbers.*/
isr = nint(sr);
if (fabs(isr - sr) > tol) return 1;
/*Get mean and stdev estimate and remove mean.*/
iret = stats_c(y1,npts,2,&amean1,&stdev1,&dummy,&dummy);
for (i=0;i<npts;i++) y1[i] = y1[i] - amean1;
iret = stats_c(y2,npts,2,&amean2,&stdev2,&dummy,&dummy);
for (i=0;i<npts;i++) y2[i] = y2[i] - amean2;
lags = nint(laglen*sr);
if (lags > npts) return 2;
len = 2*lags + 1;
z = malloc(len*sizeof(float));
del = 1.0/sr;
/*Get cross-correlation in time domain and normalize by standard deviations.
Normalize by stn. dev. squared of the first event to get an estimate
of the amplitude of the second event relative to that of the first. The
log10 of this estimate would estimate the magnitude difference.*/
iret = correl(y1,y2,z,npts,lags,&rmax,&kmax);
/*Recompute standard deviations based on exact correlation match delay.
For kmax = 0, the match was at zero delay, and no correction is needed.*/
if (kmax < 0)
{
iret = stats_c(y1-kmax,npts+kmax,2,&amean1,&stdev1,&dummy,&dummy);
iret = stats_c(y2 ,npts+kmax,2,&amean2,&stdev2,&dummy,&dummy);
}
if (kmax > 0)
{
iret = stats_c(y1 ,npts-kmax,2,&amean1,&stdev1,&dummy,&dummy);
iret = stats_c(y2+kmax,npts-kmax,2,&amean2,&stdev2,&dummy,&dummy);
}
*ccc = rmax/(stdev1*stdev2);
*cccp = rmax/(stdev1*stdev1);
/*Occasional cases may arise where this leads to |CCF| > 1, so reset it
to +/-1 if greater. Such cases arise when the interpolated peak of the
cross-correlation function goes above +1 or below -1.*/
if (*ccc > 1.0) *ccc = 1.0;
if (*ccc < -1.0) *ccc = -1.0;
/*Compute the delay. A positive tmax means the 2nd signal is delayed
wrt 1st by that amount.*/
tmax=kmax*del;
/*Pick out 3 points around maximum and compute best-fit parabola.*/
ym = z[kmax+lags-1];
y0 = z[kmax+lags];
yp = z[kmax+lags+1];
a = ( ym/2 + yp/2 - y0)/pow((double) del,2);
b = (-ym/2 + yp/2)/del;
c = y0;
/*Peak is at relative time where derivative = 0.*/
if (a == 0.0)
{
free(z);
return 3;
}
tpeak = -b/(2*a);
/*Get total time shift.*/
tshift = tmax + tpeak;
/*Compute absolute time shift between signals. If the 2nd is later than the
1st, the shift is positive.*/
*tau = tstart2 - tstart1 + tshift;
free(z);
return 0;
}
int correl(float x[],float y[],float *z,int npts,int lags,float *rmax,int *kmax)
/*
This returns the crosscorrelation function, normalized by the number
of points used but not by the stdev's of the two time series.
x,y = two time series
z = array to hold the cross-correlation function
npts = length of the two time series
lags = number of lags (n = 2*lags + 1)
rmax = maximum of the correlation function (positive or negative).
To handle cases where polarity reversal may occur, the maximum is
allowed to be positive or negative.
kmax = point of this maximum (relative to center point)
e.g., if the zero-lag coef. is maximum, kmax = 0
Note: The zeroth lag will be the midpoint of the returned series z.
*/
{
int n,j,i;
*rmax = 0.0;
n = 2*lags + 1;
for (j=0;j<n;j++)
{
z[j] = 0.0;
for (i=0;i<npts;i++)
if(i+j-lags >= 0 && i+j-lags < npts) z[j] = z[j] + x[i]*y[i+j-lags];
/* Normalize the CCF by the partial length. This is like doing a circular
cross-correlation with zero padding.*/
z[j] = z[j]/(npts - abs(j-lags));
if (fabs(z[j]) > fabs(*rmax))
{
*rmax = z[j];
*kmax = j-lags;
}
}
return 0;
}
|
the_stack_data/190768294.c | //
// Created by xudong on 2021/9/2.
//
int metalogger_init(void){
return 0;
} |
the_stack_data/126540.c | void my_module_(void) {}
|
the_stack_data/101206.c |
#include <stdio.h>
void scilab_rt_champ1_d2d2i2i2d0d2s0_(int in00, int in01, double matrixin0[in00][in01],
int in10, int in11, double matrixin1[in10][in11],
int in20, int in21, int matrixin2[in20][in21],
int in30, int in31, int matrixin3[in30][in31],
double scalarin0,
int in40, int in41, double matrixin4[in40][in41],
char* scalarin1)
{
int i;
int j;
double val0 = 0;
double val1 = 0;
int val2 = 0;
int val3 = 0;
double val4 = 0;
for (i = 0; i < in00; ++i) {
for (j = 0; j < in01; ++j) {
val0 += matrixin0[i][j];
}
}
printf("%f", val0);
for (i = 0; i < in10; ++i) {
for (j = 0; j < in11; ++j) {
val1 += matrixin1[i][j];
}
}
printf("%f", val1);
for (i = 0; i < in20; ++i) {
for (j = 0; j < in21; ++j) {
val2 += matrixin2[i][j];
}
}
printf("%d", val2);
for (i = 0; i < in30; ++i) {
for (j = 0; j < in31; ++j) {
val3 += matrixin3[i][j];
}
}
printf("%d", val3);
printf("%f", scalarin0);
for (i = 0; i < in40; ++i) {
for (j = 0; j < in41; ++j) {
val4 += matrixin4[i][j];
}
}
printf("%f", val4);
printf("%s", scalarin1);
}
|
the_stack_data/148578197.c | /**
******************************************************************************
* @file stm32g4xx_ll_usart.c
* @author MCD Application Team
* @brief USART LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_ll_usart.h"
#include "stm32g4xx_ll_rcc.h"
#include "stm32g4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
/** @addtogroup STM32G4xx_LL_Driver
* @{
*/
#if defined (USART1) || defined (USART2) || defined (USART3) || defined (UART4) || defined (UART5)
/** @addtogroup USART_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Macros
* @{
*/
#define IS_LL_USART_PRESCALER(__VALUE__) (((__VALUE__) == LL_USART_PRESCALER_DIV1) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV2) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV4) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV6) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV8) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV10) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV12) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV16) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV32) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV64) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV128) \
|| ((__VALUE__) == LL_USART_PRESCALER_DIV256))
/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available
* divided by the smallest oversampling used on the USART (i.e. 8) */
#define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 18750000U)
/* __VALUE__ In case of oversampling by 16 and 8, BRR content must be greater than or equal to 16d. */
#define IS_LL_USART_BRR_MIN(__VALUE__) ((__VALUE__) >= 16U)
/* __VALUE__ BRR content must be lower than or equal to 0xFFFF. */
#define IS_LL_USART_BRR_MAX(__VALUE__) ((__VALUE__) <= 0x0000FFFFU)
#define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \
|| ((__VALUE__) == LL_USART_DIRECTION_RX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX_RX))
#define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \
|| ((__VALUE__) == LL_USART_PARITY_EVEN) \
|| ((__VALUE__) == LL_USART_PARITY_ODD))
#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_7B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_8B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_9B))
#define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \
|| ((__VALUE__) == LL_USART_OVERSAMPLING_8))
#define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \
|| ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT))
#define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \
|| ((__VALUE__) == LL_USART_PHASE_2EDGE))
#define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \
|| ((__VALUE__) == LL_USART_POLARITY_HIGH))
#define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \
|| ((__VALUE__) == LL_USART_CLOCK_ENABLE))
#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_1) \
|| ((__VALUE__) == LL_USART_STOPBITS_1_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_2))
#define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_CTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup USART_LL_Exported_Functions
* @{
*/
/** @addtogroup USART_LL_EF_Init
* @{
*/
/**
* @brief De-initialize USART registers (Registers restored to their default values).
* @param USARTx USART Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are de-initialized
* - ERROR: USART registers are not de-initialized
*/
ErrorStatus LL_USART_DeInit(USART_TypeDef *USARTx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
if (USARTx == USART1)
{
/* Force reset of USART clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_USART1);
/* Release reset of USART clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_USART1);
}
else if (USARTx == USART2)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2);
}
else if (USARTx == USART3)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART3);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3);
}
#if defined(UART4)
else if (USARTx == UART4)
{
/* Force reset of UART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART4);
/* Release reset of UART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART4);
}
#endif /* UART4 */
#if defined(UART5)
else if (USARTx == UART5)
{
/* Force reset of UART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART5);
/* Release reset of UART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART5);
}
#endif /* UART5 */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Initialize USART registers according to the specified
* parameters in USART_InitStruct.
* @note As some bits in USART configuration registers can only be written when
* the USART is disabled (USART_CR1_UE bit =0), USART Peripheral should be in disabled state prior calling
* this function. Otherwise, ERROR result will be returned.
* @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0).
* @param USARTx USART Instance
* @param USART_InitStruct pointer to a LL_USART_InitTypeDef structure
* that contains the configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are initialized according to USART_InitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, LL_USART_InitTypeDef *USART_InitStruct)
{
ErrorStatus status = ERROR;
uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_PRESCALER(USART_InitStruct->PrescalerValue));
assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate));
assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth));
assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits));
assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity));
assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection));
assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl));
assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR1 Configuration ---------------------
* Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters:
* - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value
* - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value
* - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value
* - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value.
*/
MODIFY_REG(USARTx->CR1,
(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS |
USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8),
(USART_InitStruct->DataWidth | USART_InitStruct->Parity |
USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling));
/*---------------------------- USART CR2 Configuration ---------------------
* Configure USARTx CR2 (Stop bits) with parameters:
* - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value.
* - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit().
*/
LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits);
/*---------------------------- USART CR3 Configuration ---------------------
* Configure USARTx CR3 (Hardware Flow Control) with parameters:
* - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to
* USART_InitStruct->HardwareFlowControl value.
*/
LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl);
/*---------------------------- USART BRR Configuration ---------------------
* Retrieve Clock frequency used for USART Peripheral
*/
if (USARTx == USART1)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART1_CLKSOURCE);
}
else if (USARTx == USART2)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART2_CLKSOURCE);
}
else if (USARTx == USART3)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART3_CLKSOURCE);
}
#if defined(UART4)
else if (USARTx == UART4)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART4_CLKSOURCE);
}
#endif /* UART4 */
#if defined(UART5)
else if (USARTx == UART5)
{
periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_UART5_CLKSOURCE);
}
#endif /* UART5 */
else
{
/* Nothing to do, as error code is already assigned to ERROR value */
}
/* Configure the USART Baud Rate :
- prescaler value is required
- valid baud rate value (different from 0) is required
- Peripheral clock as returned by RCC service, should be valid (different from 0).
*/
if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO)
&& (USART_InitStruct->BaudRate != 0U))
{
status = SUCCESS;
LL_USART_SetBaudRate(USARTx,
periphclk,
USART_InitStruct->PrescalerValue,
USART_InitStruct->OverSampling,
USART_InitStruct->BaudRate);
/* Check BRR is greater than or equal to 16d */
assert_param(IS_LL_USART_BRR_MIN(USARTx->BRR));
/* Check BRR is lower than or equal to 0xFFFF */
assert_param(IS_LL_USART_BRR_MAX(USARTx->BRR));
}
/*---------------------------- USART PRESC Configuration -----------------------
* Configure USARTx PRESC (Prescaler) with parameters:
* - PrescalerValue: USART_PRESC_PRESCALER bits according to USART_InitStruct->PrescalerValue value.
*/
LL_USART_SetPrescaler(USARTx, USART_InitStruct->PrescalerValue);
}
/* Endif (=> USART not in Disabled state => return ERROR) */
return (status);
}
/**
* @brief Set each @ref LL_USART_InitTypeDef field to default value.
* @param USART_InitStruct pointer to a @ref LL_USART_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct)
{
/* Set USART_InitStruct fields to default values */
USART_InitStruct->PrescalerValue = LL_USART_PRESCALER_DIV1;
USART_InitStruct->BaudRate = 9600U;
USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B;
USART_InitStruct->StopBits = LL_USART_STOPBITS_1;
USART_InitStruct->Parity = LL_USART_PARITY_NONE ;
USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX;
USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE;
USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16;
}
/**
* @brief Initialize USART Clock related settings according to the
* specified parameters in the USART_ClockInitStruct.
* @note As some bits in USART configuration registers can only be written when
* the USART is disabled (USART_CR1_UE bit =0), USART Peripheral should be in disabled state prior calling
* this function. Otherwise, ERROR result will be returned.
* @param USARTx USART Instance
* @param USART_ClockInitStruct pointer to a @ref LL_USART_ClockInitTypeDef structure
* that contains the Clock configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers related to Clock settings are initialized according
* to USART_ClockInitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check USART Instance and Clock signal output parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR2 Configuration -----------------------*/
/* If Clock signal has to be output */
if (USART_ClockInitStruct->ClockOutput == LL_USART_CLOCK_DISABLE)
{
/* Deactivate Clock signal delivery :
* - Disable Clock Output: USART_CR2_CLKEN cleared
*/
LL_USART_DisableSCLKOutput(USARTx);
}
else
{
/* Ensure USART instance is USART capable */
assert_param(IS_USART_INSTANCE(USARTx));
/* Check clock related parameters */
assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity));
assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase));
assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse));
/*---------------------------- USART CR2 Configuration -----------------------
* Configure USARTx CR2 (Clock signal related bits) with parameters:
* - Enable Clock Output: USART_CR2_CLKEN set
* - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value
* - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value
* - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value.
*/
MODIFY_REG(USARTx->CR2,
USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL,
USART_CR2_CLKEN | USART_ClockInitStruct->ClockPolarity |
USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse);
}
}
/* Else (USART not in Disabled state => return ERROR */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value.
* @param USART_ClockInitStruct pointer to a @ref LL_USART_ClockInitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
/* Set LL_USART_ClockInitStruct fields with default values */
USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE;
USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput =
LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput =
LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput =
LL_USART_CLOCK_DISABLE */
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* USART1 || USART2 || USART3 || UART4 || UART5 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/366712.c | /* $OpenBSD: bcd.c,v 1.13 2009/10/27 23:59:24 deraadt Exp $ */
/* $NetBSD: bcd.c,v 1.6 1995/04/24 12:22:23 cgd Exp $ */
/*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Steve Hayman of the Indiana University Computer Science Dept.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* bcd --
*
* Read one line of standard input and produce something that looks like a
* punch card. An attempt to reimplement /usr/games/bcd. All I looked at
* was the man page.
*
* I couldn't find a BCD table handy so I wrote a shell script to deduce what
* the patterns were that the old bcd was using for each possible 8-bit
* character. These are the results -- the low order 12 bits represent the
* holes. (A 1 bit is a hole.) These may be wrong, but they match the old
* program!
*
* Steve Hayman
* [email protected]
* 1989 11 30
*
*
* I found an error in the table. The same error is found in the SunOS 4.1.1
* version of bcd. It has apparently been around a long time. The error caused
* 'Q' and 'R' to have the same punch code. I only noticed the error due to
* someone pointing it out to me when the program was used to print a cover
* for an APA! The table was wrong in 4 places. The other error was masked
* by the fact that the input is converted to upper case before lookup.
*
* Dyane Bruce
* [email protected]
* Nov 5, 1993
*/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
u_short holes[256] = {
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x206, 0x20a, 0x042, 0x442, 0x222, 0x800, 0x406,
0x812, 0x412, 0x422, 0xa00, 0x242, 0x400, 0x842, 0x300,
0x200, 0x100, 0x080, 0x040, 0x020, 0x010, 0x008, 0x004,
0x002, 0x001, 0x012, 0x40a, 0x80a, 0x212, 0x00a, 0x006,
0x022, 0x900, 0x880, 0x840, 0x820, 0x810, 0x808, 0x804,
0x802, 0x801, 0x500, 0x480, 0x440, 0x420, 0x410, 0x408,
0x404, 0x402, 0x401, 0x280, 0x240, 0x220, 0x210, 0x208,
0x204, 0x202, 0x201, 0x082, 0x822, 0x600, 0x282, 0x30f,
0x900, 0x880, 0x840, 0x820, 0x810, 0x808, 0x804, 0x802,
0x801, 0x500, 0x480, 0x440, 0x420, 0x410, 0x408, 0x404,
0x402, 0x401, 0x280, 0x240, 0x220, 0x210, 0x208, 0x204,
0x202, 0x201, 0x082, 0x806, 0x822, 0x600, 0x282, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x206, 0x20a, 0x042, 0x442, 0x222, 0x800, 0x406, 0x812,
0x412, 0x422, 0xa00, 0x242, 0x400, 0x842, 0x300, 0x200,
0x100, 0x080, 0x040, 0x020, 0x010, 0x008, 0x004, 0x002,
0x001, 0x012, 0x40a, 0x80a, 0x212, 0x00a, 0x006, 0x022,
0x900, 0x880, 0x840, 0x820, 0x810, 0x808, 0x804, 0x802,
0x801, 0x500, 0x480, 0x440, 0x420, 0x410, 0x408, 0x404,
0x402, 0x401, 0x280, 0x240, 0x220, 0x210, 0x208, 0x204,
0x202, 0x201, 0x082, 0x806, 0x822, 0x600, 0x282, 0x30f,
0x900, 0x880, 0x840, 0x820, 0x810, 0x808, 0x804, 0x802,
0x801, 0x500, 0x480, 0x440, 0x420, 0x410, 0x408, 0x404,
0x402, 0x401, 0x280, 0x240, 0x220, 0x210, 0x208, 0x204,
0x202, 0x201, 0x082, 0x806, 0x822, 0x600, 0x282, 0x0
};
/*
* i'th bit of w.
*/
#define bit(w,i) ((w)&(1<<(i)))
void printcard(char *);
int
main(int argc, char *argv[])
{
char cardline[80];
/*
* The original bcd prompts with a "%" when reading from stdin,
* but this seems kind of silly. So this one doesn't.
*/
if (argc > 1) {
while (--argc)
printcard(*++argv);
} else
while (fgets(cardline, sizeof(cardline), stdin))
printcard(cardline);
exit(0);
}
#define COLUMNS 48
void
printcard(char *str)
{
static const char rowchars[] = " 123456789";
int i, row;
char *p;
/* ruthlessly remove newlines and truncate at 48 characters. */
str[strcspn(str, "\n")] = '\0';
if (strlen(str) > COLUMNS)
str[COLUMNS] = '\0';
/* make string upper case. */
for (p = str; *p; ++p)
if (isascii(*p) && islower(*p))
*p = toupper(*p);
/* top of card */
putchar(' ');
for (i = 1; i <= COLUMNS; ++i)
putchar('_');
putchar('\n');
/*
* line of text. Leave a blank if the character doesn't have
* a hole pattern.
*/
p = str;
putchar('/');
for (i = 1; *p; i++, p++)
if (holes[(int)*p])
putchar(*p);
else
putchar(' ');
while (i++ <= COLUMNS)
putchar(' ');
putchar('|');
putchar('\n');
/*
* 12 rows of potential holes; output a ']', which looks kind of
* like a hole, if the appropriate bit is set in the holes[] table.
* The original bcd output a '[', a backspace, five control A's,
* and then a ']'. This seems a little excessive.
*/
for (row = 0; row <= 11; ++row) {
putchar('|');
for (i = 0, p = str; *p; i++, p++) {
if (bit(holes[(int)*p], 11 - row))
putchar(']');
else
putchar(rowchars[row]);
}
while (i++ < COLUMNS)
putchar(rowchars[row]);
putchar('|');
putchar('\n');
}
/* bottom of card */
putchar('|');
for (i = 1; i <= COLUMNS; i++)
putchar('_');
putchar('|');
putchar('\n');
}
|
the_stack_data/100140540.c | /*
* Copyright (C) 2011-2016 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef HAVE_SGX
#include "global_data.h"
#include <string.h>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <link.h>
/**
* This function is commonly provided by glibc for application to walk
* through list of shared objects. It is needed inside Enclave so that
* the libunwind code can work correctly.
*/
int dl_iterate_phdr(
int (*callback) (struct dl_phdr_info *info,
size_t size, void *data),
void *data)
{
struct dl_phdr_info info;
ElfW(Ehdr) *ehdr;
memset(&info, 0, sizeof(info));
ehdr = (ElfW(Ehdr) *) &__ImageBase;
info.dlpi_addr = (ElfW(Addr)) ehdr;
info.dlpi_name = "";
info.dlpi_phdr = (ElfW(Phdr) *) ((char *)ehdr + ehdr->e_phoff);
info.dlpi_phnum = ehdr->e_phnum;
/* No iteration here - the Enclave is merely one shared object. */
return callback(&info, sizeof(info), data);
}
#endif
|
the_stack_data/92324522.c | #include <stdio.h>
#include <stdio.h>
#include <math.h>
int main ()
{
float x,y;
scanf ("%f %f", &x, &y) ;
printf ("%f\n", pow(x,y));
return 0;
}
|
the_stack_data/95450404.c | int sched_get_priority_min(int policy)
{
return 0;
}
|
the_stack_data/58877.c | int mx_sqrt(int x) {
if (x <= 0)
return 0;
if (x == 1)
return 1;
int half = x / 2;
if (half > 46340)
half = 46340;
for (int i = 1; i <= half; i++) {
if (i * i == x) {
return i;
}
}
return 0;
}
|
the_stack_data/476155.c | const char root_certs[] =
// /C=US/O=Microsoft Corporation/CN=Microsoft RSA Root Certificate Authority 2017
// Not After : Jul 18 23:00:23 2042 GMT
// SHA1=73A5E64A3BFF8316FF0EDCCC618A906E4EAE4D74
"-----BEGIN CERTIFICATE-----\n"
"MIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBl\n"
"MQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYw\n"
"NAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5\n"
"IDIwMTcwHhcNMTkxMjE4MjI1MTIyWhcNNDIwNzE4MjMwMDIzWjBlMQswCQYDVQQG\n"
"EwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1N\n"
"aWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwggIi\n"
"MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKW76UM4wplZEWCpW9R2LBifOZ\n"
"Nt9GkMml7Xhqb0eRaPgnZ1AzHaGm++DlQ6OEAlcBXZxIQIJTELy/xztokLaCLeX0\n"
"ZdDMbRnMlfl7rEqUrQ7eS0MdhweSE5CAg2Q1OQT85elss7YfUJQ4ZVBcF0a5toW1\n"
"HLUX6NZFndiyJrDKxHBKrmCk3bPZ7Pw71VdyvD/IybLeS2v4I2wDwAW9lcfNcztm\n"
"gGTjGqwu+UcF8ga2m3P1eDNbx6H7JyqhtJqRjJHTOoI+dkC0zVJhUXAoP8XFWvLJ\n"
"jEm7FFtNyP9nTUwSlq31/niol4fX/V4ggNyhSyL71Imtus5Hl0dVe49FyGcohJUc\n"
"aDDv70ngNXtk55iwlNpNhTs+VcQor1fznhPbRiefHqJeRIOkpcrVE7NLP8TjwuaG\n"
"YaRSMLl6IE9vDzhTyzMMEyuP1pq9KsgtsRx9S1HKR9FIJ3Jdh+vVReZIZZ2vUpC6\n"
"W6IYZVcSn2i51BVrlMRpIpj0M+Dt+VGOQVDJNE92kKz8OMHY4Xu54+OU4UZpyw4K\n"
"UGsTuqwPN1q3ErWQgR5WrlcihtnJ0tHXUeOrO8ZV/R4O03QK0dqq6mm4lyiPSMQH\n"
"+FJDOvTKVTUssKZqwJz58oHhEmrARdlns87/I6KJClTUFLkqqNfs+avNJVgyeY+Q\n"
"W5g5xAgGwax/Dj0ApQIDAQABo1QwUjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/\n"
"BAUwAwEB/zAdBgNVHQ4EFgQUCctZf4aycI8awznjwNnpv7tNsiMwEAYJKwYBBAGC\n"
"NxUBBAMCAQAwDQYJKoZIhvcNAQEMBQADggIBAKyvPl3CEZaJjqPnktaXFbgToqZC\n"
"LgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC\n"
"gMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6\n"
"tZRGrox/2KJQJWVggEbbMwSubLWYdFQl3JPk+ONVFT24bcMKpBLBaYVu32TxU5nh\n"
"SnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2\n"
"TaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3\n"
"pvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0ki69bIImtt2dmefU6xqaWM/5TkshGsRGR\n"
"xpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp\n"
"GWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9\n"
"dOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKTc0QWbej09+CVgI+WXTik9KveCjCHk9hN\n"
"AHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB\n"
"RA+GsCyRxj3qrg+E\n"
"-----END CERTIFICATE-----\n"
// /C=US/O=Microsoft Corporation/CN=Microsoft ECC Root Certificate Authority 2017
// Not After : Jul 18 23:16:04 2042 GMT
// SHA1=999A64C37FF47D9FAB95F14769891460EEC4C3C5
"-----BEGIN CERTIFICATE-----\n"
"MIICWTCCAd+gAwIBAgIQZvI9r4fei7FK6gxXMQHC7DAKBggqhkjOPQQDAzBlMQsw\n"
"CQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYD\n"
"VQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw\n"
"MTcwHhcNMTkxMjE4MjMwNjQ1WhcNNDIwNzE4MjMxNjA0WjBlMQswCQYDVQQGEwJV\n"
"UzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNy\n"
"b3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwdjAQBgcq\n"
"hkjOPQIBBgUrgQQAIgNiAATUvD0CQnVBEyPNgASGAlEvaqiBYgtlzPbKnR5vSmZR\n"
"ogPZnZH6thaxjG7efM3beaYvzrvOcS/lpaso7GMEZpn4+vKTEAXhgShC48Zo9OYb\n"
"hGBKia/teQ87zvH2RPUBeMCjVDBSMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8E\n"
"BTADAQH/MB0GA1UdDgQWBBTIy5lycFIM+Oa+sgRXKSrPQhDtNTAQBgkrBgEEAYI3\n"
"FQEEAwIBADAKBggqhkjOPQQDAwNoADBlAjBY8k3qDPlfXu5gKcs68tvWMoQZP3zV\n"
"L8KxzJOuULsJMsbG7X7JNpQS5GiFBqIb0C8CMQCZ6Ra0DvpWSNSkMBaReNtUjGUB\n"
"iudQZsIxtzm6uBoiB078a1QWIP8rtedMDE2mT3M=\n"
"-----END CERTIFICATE-----\n"
// /C=US/O=Internet Security Research Group/CN=ISRG Root X1
// Not After : Jun 4 11:04:38 2035 GMT
// SHA1=CABD2A79A1076A31F21D253635CB039D4329A5E8
"-----BEGIN CERTIFICATE-----\n"
"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n"
"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n"
"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n"
"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n"
"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n"
"MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n"
"h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n"
"0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n"
"A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n"
"T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n"
"B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n"
"B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n"
"KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n"
"OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n"
"jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n"
"qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n"
"rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
"HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n"
"hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n"
"ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n"
"3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n"
"NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n"
"ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n"
"TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n"
"jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n"
"oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n"
"4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n"
"mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n"
"emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n"
"-----END CERTIFICATE-----\n"
// /C=BM/O=QuoVadis Limited/CN=QuoVadis Root CA 2
// Not After : Nov 24 18:23:33 2031 GMT
// SHA1=CA3AFBCF1240364B44B216208880483919937CF7
"-----BEGIN CERTIFICATE-----\n"
"MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x\n"
"GTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv\n"
"b3QgQ0EgMjAeFw0wNjExMjQxODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNV\n"
"BAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W\n"
"YWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCa\n"
"GMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6XJxg\n"
"Fyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55J\n"
"WpzmM+Yklvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bB\n"
"rrcCaoF6qUWD4gXmuVbBlDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp\n"
"+ARz8un+XJiM9XOva7R+zdRcAitMOeGylZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1\n"
"ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt66/3FsvbzSUr5R/7mp/i\n"
"Ucw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1JdxnwQ5hYIiz\n"
"PtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og\n"
"/zOhD7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UH\n"
"oycR7hYQe7xFSkyyBNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuI\n"
"yV77zGHcizN300QyNQliBJIWENieJ0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1Ud\n"
"EwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBQahGK8SEwzJQTU7tD2\n"
"A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGUa6FJpEcwRTEL\n"
"MAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT\n"
"ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2f\n"
"BluornFdLwUvZ+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzn\n"
"g/iN/Ae42l9NLmeyhP3ZRPx3UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2Bl\n"
"fF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodmVjB3pjd4M1IQWK4/YY7yarHvGH5K\n"
"WWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK+JDSV6IZUaUtl0Ha\n"
"B0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrWIozc\n"
"hLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPR\n"
"TUIZ3Ph1WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWD\n"
"mbA4CD/pXvk1B+TJYm5Xf6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0Z\n"
"ohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y\n"
"4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8VCLAAVBpQ570su9t+Oza\n"
"8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u\n"
"-----END CERTIFICATE-----\n"
// /C=DE/O=D-Trust GmbH/CN=D-TRUST Root Class 3 CA 2 2009
// Not After : Nov 5 08:35:58 2029 GMT
// SHA1=58E8ABB0361533FB80F79B1B6D29D3FF8D5F00F0
"-----BEGIN CERTIFICATE-----\n"
"MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF\n"
"MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD\n"
"bGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha\n"
"ME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM\n"
"HkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB\n"
"BQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03\n"
"UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42\n"
"tSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R\n"
"ySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM\n"
"lFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp\n"
"/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G\n"
"A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G\n"
"A1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj\n"
"dG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy\n"
"MENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl\n"
"cmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js\n"
"L2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL\n"
"BQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni\n"
"acfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0\n"
"o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K\n"
"zCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8\n"
"PIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y\n"
"Johw1+qRzT65ysCQblrGXnRl11z+o+I=\n"
"-----END CERTIFICATE-----\n"
// /C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=AAA Certificate Services
// Not After : Dec 31 23:59:59 2028 GMT
// SHA1=D1EB23A46D17D68FD92564C2F1F1601764D8E349
"-----BEGIN CERTIFICATE-----\n"
"MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb\n"
"MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow\n"
"GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj\n"
"YXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL\n"
"MAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE\n"
"BwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM\n"
"GEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP\n"
"ADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua\n"
"BtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe\n"
"3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4\n"
"YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR\n"
"rOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm\n"
"ez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU\n"
"oBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF\n"
"MAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v\n"
"QUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t\n"
"b2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF\n"
"AAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q\n"
"GE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz\n"
"Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2\n"
"G9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi\n"
"l2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3\n"
"smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg==\n"
"-----END CERTIFICATE-----\n"
// /C=IE/O=Baltimore/OU=CyberTrust/CN=Baltimore CyberTrust Root
// Not After : May 12 23:59:00 2025 GMT
// SHA1=D4DE20D05E66FC53FE1A50882C78DB2852CAE474
"-----BEGIN CERTIFICATE-----\n"
"MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ\n"
"RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD\n"
"VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX\n"
"DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y\n"
"ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy\n"
"VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr\n"
"mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr\n"
"IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK\n"
"mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu\n"
"XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy\n"
"dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye\n"
"jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1\n"
"BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3\n"
"DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92\n"
"9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx\n"
"jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0\n"
"Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz\n"
"ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS\n"
"R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp\n"
"-----END CERTIFICATE-----\n"
// /C=IT/L=Milan/O=Actalis S.p.A./03358520967/CN=Actalis Authentication Root CA
// Not After : Sep 22 11:22:02 2030 GMT
// SHA1=F373B387065A28848AF2F34ACE192BDDC78E9CAC
"-----BEGIN CERTIFICATE-----\n"
"MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UE\n"
"BhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8w\n"
"MzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290\n"
"IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDkyMjExMjIwMlowazELMAkGA1UEBhMC\n"
"SVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1\n"
"ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENB\n"
"MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNv\n"
"UTufClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX\n"
"4ay8IMKx4INRimlNAJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9\n"
"KK3giq0itFZljoZUj5NDKd45RnijMCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/\n"
"gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1fYVEiVRvjRuPjPdA1Yprb\n"
"rxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2oxgkg4YQ\n"
"51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2F\n"
"be8lEfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxe\n"
"KF+w6D9Fz8+vm2/7hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4F\n"
"v6MGn8i1zeQf1xcGDXqVdFUNaBr8EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbn\n"
"fpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5jF66CyCU3nuDuP/jVo23Eek7\n"
"jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLYiDrIn3hm7Ynz\n"
"ezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt\n"
"ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAL\n"
"e3KHwGCmSUyIWOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70\n"
"jsNjLiNmsGe+b7bAEzlgqqI0JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDz\n"
"WochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKxK3JCaKygvU5a2hi/a5iB0P2avl4V\n"
"SM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+Xlff1ANATIGk0k9j\n"
"pwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC4yyX\n"
"X04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+Ok\n"
"fcvHlXHo2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7R\n"
"K4X9p2jIugErsWx0Hbhzlefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btU\n"
"ZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXemOR/qnuOf0GZvBeyqdn6/axag67XH/JJU\n"
"LysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9vwGYT7JZVEc+NHt4bVaT\n"
"LnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg==\n"
"-----END CERTIFICATE-----\n"
// /C=JP/O=SECOM Trust Systems CO.,LTD./OU=Security Communication RootCA2
// Not After : May 29 05:00:39 2029 GMT
// SHA1=5F3B8CF2F810B37D78B4CEEC1919C37334B9C774
"-----BEGIN CERTIFICATE-----\n"
"MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl\n"
"MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe\n"
"U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX\n"
"DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy\n"
"dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj\n"
"YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV\n"
"OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr\n"
"zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM\n"
"VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ\n"
"hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO\n"
"ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw\n"
"awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs\n"
"OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3\n"
"DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF\n"
"coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc\n"
"okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8\n"
"t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy\n"
"1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/\n"
"SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03\n"
"-----END CERTIFICATE-----\n"
// /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Global Root CA
// Not After : Nov 10 00:00:00 2031 GMT
// SHA1=A8985D3A65E5E5C4B2D7D66D40C6DD2FB19C5436
"-----BEGIN CERTIFICATE-----\n"
"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n"
"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n"
"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n"
"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n"
"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n"
"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n"
"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n"
"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n"
"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n"
"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n"
"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n"
"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n"
"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n"
"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n"
"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n"
"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n"
"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n"
"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n"
"-----END CERTIFICATE-----\n"
// /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Global Root G2
// Not After : Jan 15 12:00:00 2038 GMT
// SHA1=DF3C24F9BFD666761B268073FE06D1CC8D4F82A4
"-----BEGIN CERTIFICATE-----\n"
"MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh\n"
"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH\n"
"MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT\n"
"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG\n"
"9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI\n"
"2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx\n"
"1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ\n"
"q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz\n"
"tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ\n"
"vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP\n"
"BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV\n"
"5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY\n"
"1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4\n"
"NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG\n"
"Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91\n"
"8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe\n"
"pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl\n"
"MrY=\n"
"-----END CERTIFICATE-----\n"
// /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA
// Not After : Nov 10 00:00:00 2031 GMT
// SHA1=5FB7EE0633E259DBAD0C4C9AE6D38F1A61C7DC25
"-----BEGIN CERTIFICATE-----\n"
"MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs\n"
"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
"d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j\n"
"ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL\n"
"MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3\n"
"LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug\n"
"RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm\n"
"+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW\n"
"PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM\n"
"xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB\n"
"Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3\n"
"hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg\n"
"EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF\n"
"MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA\n"
"FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec\n"
"nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z\n"
"eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF\n"
"hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2\n"
"Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe\n"
"vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep\n"
"+OkuE6N36B9K\n"
"-----END CERTIFICATE-----\n"
// /C=US/O=Entrust, Inc./OU=See www.entrust.net/legal-terms/OU=(c) 2009 Entrust, Inc. - for authorized use only/CN=Entrust Root Certification Authority - G2
// Not After : Dec 7 17:55:54 2030 GMT
// SHA1=8CF427FD790C3AD166068DE81E57EFBB932272D4
"-----BEGIN CERTIFICATE-----\n"
"MIIEPjCCAyagAwIBAgIESlOMKDANBgkqhkiG9w0BAQsFADCBvjELMAkGA1UEBhMC\n"
"VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50\n"
"cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3Qs\n"
"IEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVz\n"
"dCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIwHhcNMDkwNzA3MTcy\n"
"NTU0WhcNMzAxMjA3MTc1NTU0WjCBvjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUVu\n"
"dHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwt\n"
"dGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0\n"
"aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmlj\n"
"YXRpb24gQXV0aG9yaXR5IC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\n"
"AoIBAQC6hLZy254Ma+KZ6TABp3bqMriVQRrJ2mFOWHLP/vaCeb9zYQYKpSfYs1/T\n"
"RU4cctZOMvJyig/3gxnQaoCAAEUesMfnmr8SVycco2gvCoe9amsOXmXzHHfV1IWN\n"
"cCG0szLni6LVhjkCsbjSR87kyUnEO6fe+1R9V77w6G7CebI6C1XiUJgWMhNcL3hW\n"
"wcKUs/Ja5CeanyTXxuzQmyWC48zCxEXFjJd6BmsqEZ+pCm5IO2/b1BEZQvePB7/1\n"
"U1+cPvQXLOZprE4yTGJ36rfo5bs0vBmLrpxR57d+tVOxMyLlbc9wPBr64ptntoP0\n"
"jaWvYkxN4FisZDQSA/i2jZRjJKRxAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAP\n"
"BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqciZ60B7vfec7aVHUbI2fkBJmqzAN\n"
"BgkqhkiG9w0BAQsFAAOCAQEAeZ8dlsa2eT8ijYfThwMEYGprmi5ZiXMRrEPR9RP/\n"
"jTkrwPK9T3CMqS/qF8QLVJ7UG5aYMzyorWKiAHarWWluBh1+xLlEjZivEtRh2woZ\n"
"Rkfz6/djwUAFQKXSt/S1mja/qYh2iARVBCuch38aNzx+LaUa2NSJXsq9rD1s2G2v\n"
"1fN2D807iDginWyTmsQ9v4IbZT+mD12q/OWyFcq1rca8PdCE6OoGcrBNOTJ4vz4R\n"
"nAuknZoh8/CbCzB428Hch0P+vGOaysXCHMnHjf87ElgI5rY97HosTvuDls4MPGmH\n"
"VHOkc8KT/1EQrBVUAdj8BbGJoX90g5pJ19xOe4pIb4tF9g==\n"
"-----END CERTIFICATE-----\n"
// /C=US/O=Starfield Technologies, Inc./OU=Starfield Class 2 Certification Authority
// Not After : Jun 29 17:39:16 2034 GMT
// SHA1=AD7E1C28B064EF8F6003402014C3D0E3370EB58A
"-----BEGIN CERTIFICATE-----\n"
"MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl\n"
"MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp\n"
"U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw\n"
"NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE\n"
"ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp\n"
"ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3\n"
"DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf\n"
"8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN\n"
"+lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0\n"
"X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa\n"
"K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA\n"
"1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G\n"
"A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR\n"
"zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0\n"
"YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD\n"
"bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w\n"
"DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3\n"
"L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D\n"
"eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl\n"
"xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp\n"
"VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY\n"
"WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=\n"
"-----END CERTIFICATE-----\n"
// /C=US/O=The Go Daddy Group, Inc./OU=Go Daddy Class 2 Certification Authority
// Not After : Jun 29 17:06:20 2034 GMT
// SHA1=2796BAE63F1801E277261BA0D77770028F20EEE4
"-----BEGIN CERTIFICATE-----\n"
"MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh\n"
"MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE\n"
"YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3\n"
"MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo\n"
"ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg\n"
"MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN\n"
"ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA\n"
"PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w\n"
"wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi\n"
"EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY\n"
"avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+\n"
"YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE\n"
"sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h\n"
"/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5\n"
"IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj\n"
"YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD\n"
"ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy\n"
"OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P\n"
"TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ\n"
"HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER\n"
"dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf\n"
"ReYNnyicsbkqWletNw+vHX/bvZ8=\n"
"-----END CERTIFICATE-----\n"
// /C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 2006 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 3 Public Primary Certification Authority - G5
// Not After : Jul 16 23:59:59 2036 GMT
// SHA1=4EB6D578499B1CCF5F581EAD56BE3D9B6744A5E5
"-----BEGIN CERTIFICATE-----\n"
"MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB\n"
"yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL\n"
"ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp\n"
"U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW\n"
"ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0\n"
"aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL\n"
"MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW\n"
"ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln\n"
"biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp\n"
"U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y\n"
"aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1\n"
"nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex\n"
"t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz\n"
"SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG\n"
"BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+\n"
"rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/\n"
"NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E\n"
"BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH\n"
"BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy\n"
"aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv\n"
"MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE\n"
"p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y\n"
"5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK\n"
"WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ\n"
"4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N\n"
"hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq\n"
"-----END CERTIFICATE-----\n"
// /O=Digital Signature Trust Co./CN=DST Root CA X3
// Not After : Sep 30 14:01:15 2021 GMT
// SHA1=DAC9024F54D8F6DF94935FB1732638CA6AD77C13
"-----BEGIN CERTIFICATE-----\n"
"MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/\n"
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n"
"DkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow\n"
"PzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD\n"
"Ew5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\n"
"AN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmTrE4O\n"
"rz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEq\n"
"OLl5CjH9UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9b\n"
"xiqKqy69cK3FCxolkHRyxXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw\n"
"7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40dutolucbY38EVAjqr2m7xPi71XAicPNaD\n"
"aeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV\n"
"HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQMA0GCSqG\n"
"SIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69\n"
"ikugdB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXr\n"
"AvHRAosZy5Q6XkjEGB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZz\n"
"R8srzJmwN0jP41ZL9c8PDHIyh8bwRLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5\n"
"JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubSfZGL+T0yjWW06XyxV3bqxbYo\n"
"Ob8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ\n"
"-----END CERTIFICATE-----\n"
// /OU=GlobalSign Root CA - R2/O=GlobalSign/CN=GlobalSign
// Not After : Dec 15 08:00:00 2021 GMT
// SHA1=75E0ABB6138512271C04F85FDDDE38E4B7242EFE
"-----BEGIN CERTIFICATE-----\n"
"MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G\n"
"A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp\n"
"Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1\n"
"MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG\n"
"A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI\n"
"hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL\n"
"v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8\n"
"eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq\n"
"tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd\n"
"C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa\n"
"zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB\n"
"mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH\n"
"V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n\n"
"bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG\n"
"3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs\n"
"J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO\n"
"291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS\n"
"ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd\n"
"AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7\n"
"TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==\n"
"-----END CERTIFICATE-----\n"
; |
the_stack_data/1068366.c | // RUN: %llvmgcc -emit-llvm -c -o %t1.bc %s
// RUN: rm -rf %t.klee-out
// RUN: %klee --output-dir=%t.klee-out --exit-on-error %t1.bc
#include <stdio.h>
#include <time.h>
#include <assert.h>
int main() {
time_t t = 60 * 60 * 24 * 7; // one week after the epoch
struct tm *lt = localtime(&t);
klee_define_external_object(lt, sizeof(struct tm));
int year = lt->tm_year;
assert(year == 70); // should be 1970
return 0;
}
|
the_stack_data/247019302.c | /*
Faz uma comunicação com um determininado host na rede, essa comunicação pode prosseguir, ou não.
By Fabiano Santos
//Em construção
*/
#include <stdio.h>
//#include <netdb.h>
#include <arpa/inet.h> // htons(), inet_addr()
#include <netinet/in.h>// struct sockaddr_in
#include <sys/socket.h>// socket() connect()
#include <sys/types.h>// AF_INET, SOCK_STREAM
#include <unistd.h>// close()
int main(int argc, char *argv[]){
int meusocket;
int conecta;//Reliaza a conexão
int porta;
int inicio = 0;
int final = 65535;
char *destino;
destino = argv[1];//Destino recebe o que o usuário passar como primeiro argumento
printf(" ##############################################################################\n");
printf("# #\n");
printf("# ###### ##### ##### ####### ###### ###### ## # # #\n");
printf("# # # # # # # # # # # # ## # #\n");
printf("# ##### # # #### # ###### # ###### # # # #\n");
printf("# # # # # # # # # # # # # # #\n");
printf("# # ##### # # # ###### ###### # # # ## #\n");
printf("# #\n");
printf("# Versão: 1.0 #\n");
printf("# By: Fabiano Santos #\n");
printf(" ##############################################################################\n\n");
struct sockaddr_in alvo;// Estrutura responsável pela conexão com a internet
//Laço para range de portas
for(porta = inicio; porta < final; porta++){
meusocket = socket(AF_INET, SOCK_STREAM, 0);//AF_INET- Familia Arpanet Internet Protocol/* 0 é o protocolo ip*/
alvo.sin_family = AF_INET;// A estrutura vai utilizar a familia AF_INET
alvo.sin_port = htons(porta);//Faz a comunicação com a porta 80 do alvo'
alvo.sin_addr.s_addr = inet_addr(destino);// Endereço do alvo da conexão
conecta = connect(meusocket, (struct sockaddr *)&alvo, sizeof alvo);//Faz a conexão com o alvo
/*Testa se a conexão foi bem sucedida com o alvo. Se retornar 0, a porta esta aberta,
se retornar -1 a porta está fechada*/
if(conecta == 0)
{
printf("Host %s Porta %d - status [aberta] \n",destino, porta);
close(meusocket);//Fecha o socket
close(conecta);//Fecha o conecta
}
else{
close(meusocket);
close(conecta);
}
}
return 0;
}
|
the_stack_data/30235.c | #include <stdio.h>
int main(){
int x, y, i, ans;
ans = 1;
printf("Enter base and exponent: ");
scanf("%d %d", &x, &y);
for(i=1;i<=y;i++){
ans = ans * x;
}
printf("\nAns: %d", ans);
return 0;
} |
the_stack_data/138784.c | #include <stdio.h>
int main()
{
float a, b, s;
printf("A: ");
scanf("%f", &a);
printf("b: ");
scanf("%f", &b);
s=a+b;
printf("S=%.2f\n", s);
return 0;
}
|
the_stack_data/17573.c | /* 11-2. 포인터는 영희이다! (포인터)
- * 연산자
주소값에 대응되는 데이터를 가져오는 연산자
*/
// 연산자
#include <stdio.h>
int main() {
int *p;
int a;
p = &a;
*p = 3;
printf("a 의 값 : %d \n", a);
printf("*p 의 값 : %d \n", *p);
return 0;
} |
the_stack_data/1181655.c | #include <stdio.h>
#define Max 10000
void ler_vetor(int vet[],int n) {
int i;
for(i=0;i<n;i++)
scanf("%d",&vet[i]);
}
int busca_maior(int vet[], int n, int valor) {
int i;
i = 0;
while((i<n)&&(valor!=vet[i]))
i++;
if(i==n)
printf("NAO ACHEI\n");
else printf("ACHEI\n");
}
int main() {
int n, qtd, x, i, vetor[Max];
scanf("%d",&n);
ler_vetor(vetor,n); //vetor = &vetor[0]
scanf("%d",&qtd);
for(i=0;i<qtd;i++) {
scanf("%d",&x);
busca_valor
(vetor,n,x);
}
return 0;
} |
the_stack_data/32951277.c | #include <stdlib.h>
int
main(void)
{
char *buf;
const size_t bufsiz = 512;
int res = posix_memalign(&buf, sizeof(void *), bufsiz);
if (!res && buf)
free(buf);
return 0;
}
|
the_stack_data/29825176.c | /*
* mbed Microcontroller Library
* Copyright (c) 2017-2018 Future Electronics
*
* 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.
*/
#if DEVICE_SERIAL
#include <string.h>
#include "cmsis.h"
#include "mbed_assert.h"
#include "mbed_error.h"
#include "PeripheralPins.h"
#include "pinmap.h"
#include "serial_api.h"
#include "psoc6_utils.h"
#include "drivers/peripheral/sysclk/cy_sysclk.h"
#include "drivers/peripheral/gpio/cy_gpio.h"
#include "drivers/peripheral/scb/cy_scb_uart.h"
#include "drivers/peripheral/sysint/cy_sysint.h"
#define UART_OVERSAMPLE 12
#define UART_DEFAULT_BAUDRATE 115200
#define NUM_SERIAL_PORTS 8
#define SERIAL_DEFAULT_IRQ_PRIORITY 3
typedef struct serial_s serial_obj_t;
#if DEVICE_SERIAL_ASYNCH
#define OBJ_P(in) (&(in->serial))
#else
#define OBJ_P(in) (in)
#endif
/*
* NOTE: Cypress PDL high level API implementation of USART doe not
* align well with Mbed interface for interrupt-driven serial I/O.
* For this reason only low level PDL API is used here.
*/
static const cy_stc_scb_uart_config_t default_uart_config = {
.uartMode = CY_SCB_UART_STANDARD,
.enableMutliProcessorMode = false,
.smartCardRetryOnNack = false,
.irdaInvertRx = false,
.irdaEnableLowPowerReceiver = false,
.oversample = UART_OVERSAMPLE,
.enableMsbFirst = false,
.dataWidth = 8UL,
.parity = CY_SCB_UART_PARITY_NONE,
.stopBits = CY_SCB_UART_STOP_BITS_1,
.enableInputFilter = false,
.breakWidth = 11UL,
.dropOnFrameError = false,
.dropOnParityError = false,
.receiverAddress = 0x0UL,
.receiverAddressMask = 0x0UL,
.acceptAddrInFifo = false,
.enableCts = false,
.ctsPolarity = CY_SCB_UART_ACTIVE_LOW,
.rtsRxFifoLevel = 20UL,
.rtsPolarity = CY_SCB_UART_ACTIVE_LOW,
.rxFifoTriggerLevel = 0UL,
.rxFifoIntEnableMask = 0x0UL,
.txFifoTriggerLevel = 0UL,
.txFifoIntEnableMask = 0x0UL
};
int stdio_uart_inited = false;
serial_t stdio_uart;
typedef struct irq_info_s {
serial_obj_t *serial_obj;
uart_irq_handler handler;
uint32_t id_arg;
IRQn_Type irqn;
#if defined (TARGET_MCU_PSOC6_M0)
cy_en_intr_t cm0p_irq_src;
#endif
} irq_info_t;
static irq_info_t irq_info[NUM_SERIAL_PORTS] = {
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn}
};
static void serial_irq_dispatcher(uint32_t serial_id)
{
MBED_ASSERT(serial_id < NUM_SERIAL_PORTS);
irq_info_t *info = &irq_info[serial_id];
serial_obj_t *obj = info->serial_obj;
MBED_ASSERT(obj);
#if DEVICE_SERIAL_ASYNCH
if (obj->async_handler) {
obj->async_handler();
return;
}
#endif
if (Cy_SCB_GetRxInterruptStatusMasked(obj->base) & CY_SCB_RX_INTR_NOT_EMPTY) {
info->handler(info->id_arg, RxIrq);
Cy_SCB_ClearRxInterrupt(obj->base, CY_SCB_RX_INTR_NOT_EMPTY);
}
if (Cy_SCB_GetTxInterruptStatusMasked(obj->base) & (CY_SCB_TX_INTR_LEVEL | CY_SCB_UART_TX_DONE)) {
info->handler(info->id_arg, TxIrq);
}
}
static void serial_irq_dispatcher_uart0(void)
{
serial_irq_dispatcher(0);
}
static void serial_irq_dispatcher_uart1(void)
{
serial_irq_dispatcher(1);
}
static void serial_irq_dispatcher_uart2(void)
{
serial_irq_dispatcher(2);
}
static void serial_irq_dispatcher_uart3(void)
{
serial_irq_dispatcher(3);
}
static void serial_irq_dispatcher_uart4(void)
{
serial_irq_dispatcher(4);
}
static void serial_irq_dispatcher_uart5(void)
{
serial_irq_dispatcher(5);
}
void serial_irq_dispatcher_uart6(void)
{
serial_irq_dispatcher(6);
}
static void serial_irq_dispatcher_uart7(void)
{
serial_irq_dispatcher(7);
}
static void (*irq_dispatcher_table[])(void) = {
serial_irq_dispatcher_uart0,
serial_irq_dispatcher_uart1,
serial_irq_dispatcher_uart2,
serial_irq_dispatcher_uart3,
serial_irq_dispatcher_uart4,
serial_irq_dispatcher_uart5,
serial_irq_dispatcher_uart6,
serial_irq_dispatcher_uart7
};
static IRQn_Type serial_irq_allocate_channel(serial_obj_t *obj)
{
#if defined (TARGET_MCU_PSOC6_M0)
irq_info[obj->serial_id].cm0p_irq_src = scb_0_interrupt_IRQn + obj->serial_id;
return cy_m0_nvic_allocate_channel(CY_SERIAL_IRQN_ID + obj->serial_id);
#else
return (IRQn_Type)(scb_0_interrupt_IRQn + obj->serial_id);
#endif // M0
}
static void serial_irq_release_channel(IRQn_Type channel, uint32_t serial_id)
{
#if defined (TARGET_MCU_PSOC6_M0)
cy_m0_nvic_release_channel(channel, CY_SERIAL_IRQN_ID + serial_id);
#endif //M0
}
static int serial_irq_setup_channel(serial_obj_t *obj)
{
cy_stc_sysint_t irq_config;
irq_info_t *info = &irq_info[obj->serial_id];
if (info->irqn == unconnected_IRQn) {
IRQn_Type irqn = serial_irq_allocate_channel(obj);
if (irqn < 0) {
return (-1);
}
// Configure NVIC
irq_config.intrPriority = SERIAL_DEFAULT_IRQ_PRIORITY;
irq_config.intrSrc = irqn;
#if defined (TARGET_MCU_PSOC6_M0)
irq_config.cm0pSrc = info->cm0p_irq_src;
#endif
if (Cy_SysInt_Init(&irq_config, irq_dispatcher_table[obj->serial_id]) != CY_SYSINT_SUCCESS) {
return(-1);
}
info->irqn = irqn;
info->serial_obj = obj;
NVIC_EnableIRQ(irqn);
}
return 0;
}
/*
* Calculates fractional divider value.
*/
static uint32_t divider_value(uint32_t frequency, uint32_t frac_bits)
{
/* UARTs use peripheral clock */
return ((CY_CLK_PERICLK_FREQ_HZ * (1 << frac_bits)) + (frequency / 2)) / frequency;
}
static cy_en_sysclk_status_t serial_init_clock(serial_obj_t *obj, uint32_t baudrate)
{
cy_en_sysclk_status_t status = CY_SYSCLK_BAD_PARAM;
if (obj->div_num == CY_INVALID_DIVIDER) {
uint32_t divider_num = cy_clk_allocate_divider(CY_SYSCLK_DIV_16_5_BIT);
if (divider_num < PERI_DIV_16_5_NR) {
/* Assign fractional divider. */
status = Cy_SysClk_PeriphAssignDivider(obj->clock, CY_SYSCLK_DIV_16_5_BIT, divider_num);
if (status == CY_SYSCLK_SUCCESS) {
obj->div_type = CY_SYSCLK_DIV_16_5_BIT;
obj->div_num = divider_num;
}
} else {
// Try 16-bit divider.
divider_num = cy_clk_allocate_divider(CY_SYSCLK_DIV_16_BIT);
if (divider_num < PERI_DIV_16_NR) {
/* Assign 16-bit divider. */
status = Cy_SysClk_PeriphAssignDivider(obj->clock, CY_SYSCLK_DIV_16_BIT, divider_num);
if (status == CY_SYSCLK_SUCCESS) {
obj->div_type = CY_SYSCLK_DIV_16_BIT;
obj->div_num = divider_num;
}
} else {
error("Serial: cannot assign clock divider.");
}
}
} else {
status = CY_SYSCLK_SUCCESS;
}
if (status == CY_SYSCLK_SUCCESS) {
/* Set baud rate */
if (obj->div_type == CY_SYSCLK_DIV_16_5_BIT) {
Cy_SysClk_PeriphDisableDivider(CY_SYSCLK_DIV_16_5_BIT, obj->div_num);
uint32_t divider = divider_value(baudrate * UART_OVERSAMPLE, 5);
status = Cy_SysClk_PeriphSetFracDivider(CY_SYSCLK_DIV_16_5_BIT,
obj->div_num,
(divider >> 5) - 1, // integral part
divider & 0x1F); // fractional part
Cy_SysClk_PeriphEnableDivider(CY_SYSCLK_DIV_16_5_BIT, obj->div_num);
} else if (obj->div_type == CY_SYSCLK_DIV_16_BIT) {
Cy_SysClk_PeriphDisableDivider(CY_SYSCLK_DIV_16_BIT, obj->div_num);
status = Cy_SysClk_PeriphSetDivider(CY_SYSCLK_DIV_16_BIT,
obj->div_num,
divider_value(baudrate * UART_OVERSAMPLE, 0));
Cy_SysClk_PeriphEnableDivider(CY_SYSCLK_DIV_16_BIT, obj->div_num);
}
}
return status;
}
/*
* Initializes i/o pins for UART tx/rx.
*/
static void serial_init_pins(serial_obj_t *obj)
{
int tx_function = pinmap_function(obj->pin_tx, PinMap_UART_TX);
int rx_function = pinmap_function(obj->pin_rx, PinMap_UART_RX);
if (cy_reserve_io_pin(obj->pin_tx) || cy_reserve_io_pin(obj->pin_rx)) {
error("Serial TX/RX pin reservation conflict.");
}
pin_function(obj->pin_tx, tx_function);
pin_function(obj->pin_rx, rx_function);
}
/*
* Initializes i/o pins for UART flow control.
*/
static void serial_init_flow_pins(serial_obj_t *obj)
{
if (obj->pin_rts != NC) {
int rts_function = pinmap_function(obj->pin_rts, PinMap_UART_RTS);
if (cy_reserve_io_pin(obj->pin_rts)) {
error("Serial RTS pin reservation conflict.");
}
pin_function(obj->pin_rts, rts_function);
}
if (obj->pin_cts != NC) {
int cts_function = pinmap_function(obj->pin_cts, PinMap_UART_CTS);
if (cy_reserve_io_pin(obj->pin_cts)) {
error("Serial CTS pin reservation conflict.");
}
pin_function(obj->pin_cts, cts_function);
}
}
/*
* Initializes and enables UART/SCB.
*/
static void serial_init_peripheral(serial_obj_t *obj)
{
cy_stc_scb_uart_config_t uart_config = default_uart_config;
uart_config.dataWidth = obj->data_width;
uart_config.parity = obj->parity;
uart_config.stopBits = obj->stop_bits;
uart_config.enableCts = (obj->pin_cts != NC);
Cy_SCB_UART_Init(obj->base, &uart_config, NULL);
Cy_SCB_UART_Enable(obj->base);
}
#if DEVICE_SLEEP && DEVICE_LPTICKER && SERIAL_PM_CALLBACK_ENABLED
static cy_en_syspm_status_t serial_pm_callback(cy_stc_syspm_callback_params_t *params)
{
serial_obj_t *obj = (serial_obj_t *)params->context;
cy_en_syspm_status_t status = CY_SYSPM_FAIL;
switch (params->mode) {
case CY_SYSPM_CHECK_READY:
/* If all data elements are transmitted from the TX FIFO and
* shifter and the RX FIFO is empty: the UART is ready to enter
* Deep Sleep mode.
*/
if (Cy_SCB_UART_IsTxComplete(obj->base)) {
if (0UL == Cy_SCB_UART_GetNumInRxFifo(obj->base)) {
/* Disable the UART. The transmitter stops driving the
* lines and the receiver stops receiving data until
* the UART is enabled.
* This happens when the device failed to enter Deep
* Sleep or it is awaken from Deep Sleep mode.
*/
Cy_SCB_UART_Disable(obj->base, NULL);
status = CY_SYSPM_SUCCESS;
}
}
break;
case CY_SYSPM_CHECK_FAIL:
/* Enable the UART to operate */
Cy_SCB_UART_Enable(obj->base);
status = CY_SYSPM_SUCCESS;
break;
case CY_SYSPM_BEFORE_TRANSITION:
status = CY_SYSPM_SUCCESS;
break;
case CY_SYSPM_AFTER_TRANSITION:
/* Enable the UART to operate */
Cy_SCB_UART_Enable(obj->base);
status = CY_SYSPM_SUCCESS;
break;
default:
break;
}
return status;
}
#endif // DEVICE_SLEEP && DEVICE_LPTICKER
void serial_init(serial_t *obj_in, PinName tx, PinName rx)
{
serial_obj_t *obj = OBJ_P(obj_in);
bool is_stdio = (tx == CY_STDIO_UART_TX) || (rx == CY_STDIO_UART_RX);
if (is_stdio && stdio_uart_inited) {
memcpy(obj_in, &stdio_uart, sizeof(serial_t));
return;
}
{
uint32_t uart = pinmap_peripheral(tx, PinMap_UART_TX);
uart = pinmap_merge(uart, pinmap_peripheral(rx, PinMap_UART_RX));
if (uart != (uint32_t)NC) {
obj->base = (CySCB_Type*)uart;
obj->serial_id = ((UARTName)uart - UART_0) / (UART_1 - UART_0);
obj->pin_tx = tx;
obj->pin_rx = rx;
obj->clock = CY_PIN_CLOCK(pinmap_function(tx, PinMap_UART_TX));
obj->div_num = CY_INVALID_DIVIDER;
obj->data_width = 8;
obj->stop_bits = CY_SCB_UART_STOP_BITS_1;
obj->parity = CY_SCB_UART_PARITY_NONE;
obj->pin_rts = NC;
obj->pin_cts = NC;
serial_init_clock(obj, UART_DEFAULT_BAUDRATE);
serial_init_peripheral(obj);
//Cy_GPIO_Write(Cy_GPIO_PortToAddr(CY_PORT(P13_6)), CY_PIN(P13_6), 1);
serial_init_pins(obj);
//Cy_GPIO_Write(Cy_GPIO_PortToAddr(CY_PORT(P13_6)), CY_PIN(P13_6), 0);
#if DEVICE_SLEEP && DEVICE_LPTICKER && SERIAL_PM_CALLBACK_ENABLED
obj->pm_callback_handler.callback = serial_pm_callback;
obj->pm_callback_handler.type = CY_SYSPM_DEEPSLEEP;
obj->pm_callback_handler.skipMode = 0;
obj->pm_callback_handler.callbackParams = &obj->pm_callback_params;
obj->pm_callback_params.base = obj->base;
obj->pm_callback_params.context = obj;
if (!Cy_SysPm_RegisterCallback(&obj->pm_callback_handler)) {
error("PM callback registration failed!");
}
#endif // DEVICE_SLEEP && DEVICE_LPTICKER
if (is_stdio) {
memcpy(&stdio_uart, obj_in, sizeof(serial_t));
stdio_uart_inited = true;
}
} else {
error("Serial pinout mismatch. Requested pins Rx and Tx can't be used for the same Serial communication.");
}
}
}
void serial_baud(serial_t *obj_in, int baudrate)
{
serial_obj_t *obj = OBJ_P(obj_in);
Cy_SCB_UART_Disable(obj->base, NULL);
serial_init_clock(obj, baudrate);
Cy_SCB_UART_Enable(obj->base);
}
void serial_format(serial_t *obj_in, int data_bits, SerialParity parity, int stop_bits)
{
serial_obj_t *obj = OBJ_P(obj_in);
if ((data_bits >= 5) && (data_bits <= 9)) {
obj->data_width = data_bits;
}
switch (parity) {
case ParityNone:
obj->parity = CY_SCB_UART_PARITY_NONE;
break;
case ParityOdd:
obj->parity = CY_SCB_UART_PARITY_ODD;
break;
case ParityEven:
obj->parity = CY_SCB_UART_PARITY_EVEN;
break;
case ParityForced1:
case ParityForced0:
MBED_ASSERT("Serial parity mode not supported!");
break;
}
switch (stop_bits) {
case 1:
obj->stop_bits = CY_SCB_UART_STOP_BITS_1;
break;
case 2:
obj->stop_bits = CY_SCB_UART_STOP_BITS_2;
break;
case 3:
obj->stop_bits = CY_SCB_UART_STOP_BITS_3;
break;
case 4:
obj->stop_bits = CY_SCB_UART_STOP_BITS_4;
break;
}
Cy_SCB_UART_Disable(obj->base, NULL);
serial_init_peripheral(obj);
}
void serial_putc(serial_t *obj_in, int c)
{
serial_obj_t *obj = OBJ_P(obj_in);
while (!serial_writable(obj_in)) {
// empty
}
Cy_SCB_UART_Put(obj->base, c);
}
int serial_getc(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
while (!serial_readable(obj_in)) {
// empty
}
return Cy_SCB_UART_Get(obj->base);
}
int serial_readable(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
return Cy_SCB_GetNumInRxFifo(obj->base) != 0;
}
int serial_writable(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
return Cy_SCB_GetNumInTxFifo(obj->base) != Cy_SCB_GetFifoSize(obj->base);
}
void serial_clear(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
Cy_SCB_UART_Disable(obj->base, NULL);
Cy_SCB_ClearTxFifo(obj->base);
Cy_SCB_ClearRxFifo(obj->base);
serial_init_peripheral(obj);
}
void serial_break_set(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
/* Cypress SCB does not support transmitting break directly.
* We emulate functionality by switching TX pin to GPIO mode.
*/
GPIO_PRT_Type *port_tx = Cy_GPIO_PortToAddr(CY_PORT(obj->pin_tx));
Cy_GPIO_Pin_FastInit(port_tx, CY_PIN(obj->pin_tx), CY_GPIO_DM_STRONG_IN_OFF, 0, HSIOM_SEL_GPIO);
Cy_GPIO_Write(port_tx, CY_PIN(obj->pin_tx), 0);
}
void serial_break_clear(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
/* Connect TX pin back to SCB, see a comment in serial_break_set() above */
GPIO_PRT_Type *port_tx = Cy_GPIO_PortToAddr(CY_PORT(obj->pin_tx));
int tx_function = pinmap_function(obj->pin_tx, PinMap_UART_TX);
Cy_GPIO_Pin_FastInit(port_tx, CY_PIN(obj->pin_tx), CY_GPIO_DM_STRONG_IN_OFF, 0, CY_PIN_HSIOM(tx_function));
}
void serial_set_flow_control(serial_t *obj_in, FlowControl type, PinName rxflow, PinName txflow)
{
serial_obj_t *obj = OBJ_P(obj_in);
Cy_SCB_UART_Disable(obj->base, NULL);
switch (type) {
case FlowControlNone:
obj->pin_rts = NC;
obj->pin_cts = NC;
break;
case FlowControlRTS:
obj->pin_rts = rxflow;
obj->pin_cts = NC;
break;
case FlowControlCTS:
obj->pin_rts = NC;
obj->pin_cts = txflow;
break;
case FlowControlRTSCTS:
obj->pin_rts = rxflow;
obj->pin_cts = txflow;
break;
}
serial_init_peripheral(obj);
serial_init_flow_pins(obj);
}
#if DEVICE_SERIAL_ASYNCH
void serial_irq_handler(serial_t *obj_in, uart_irq_handler handler, uint32_t id)
{
serial_obj_t *obj = OBJ_P(obj_in);
irq_info_t *info = &irq_info[obj->serial_id];
if (info->irqn != unconnected_IRQn) {
NVIC_DisableIRQ(info->irqn);
}
info->handler = handler;
info->id_arg = id;
serial_irq_setup_channel(obj);
}
void serial_irq_set(serial_t *obj_in, SerialIrq irq, uint32_t enable)
{
serial_obj_t *obj = OBJ_P(obj_in);
switch (irq) {
case RxIrq:
if (enable) {
Cy_SCB_SetRxInterruptMask(obj->base, CY_SCB_RX_INTR_NOT_EMPTY);
} else {
Cy_SCB_SetRxInterruptMask(obj->base, 0);
}
break;
case TxIrq:
if (enable) {
Cy_SCB_SetTxInterruptMask(obj->base, CY_SCB_TX_INTR_LEVEL | CY_SCB_UART_TX_DONE);
} else {
Cy_SCB_SetTxInterruptMask(obj->base, 0);
}
break;
}
}
static void serial_finish_tx_asynch(serial_obj_t *obj)
{
Cy_SCB_SetTxInterruptMask(obj->base, 0);
obj->tx_pending = false;
}
static void serial_finish_rx_asynch(serial_obj_t *obj)
{
Cy_SCB_SetRxInterruptMask(obj->base, 0);
obj->rx_pending = false;
}
int serial_tx_asynch(serial_t *obj_in, const void *tx, size_t tx_length, uint8_t tx_width, uint32_t handler, uint32_t event, DMAUsage hint)
{
serial_obj_t *obj = OBJ_P(obj_in);
const uint8_t *p_buf = tx;
(void)tx_width; // Obsolete argument
(void)hint; // At the moment we do not support DAM transfers, so this parameter gets ignored.
if (obj->tx_pending) {
return 0;
}
obj->tx_events = event;
obj->async_handler = (cy_israddress)handler;
if (serial_irq_setup_channel(obj) < 0) {
return 0;
}
// Write as much as possible into the FIFO first.
while ((tx_length > 0) && Cy_SCB_UART_Put(obj->base, *p_buf)) {
++p_buf;
--tx_length;
}
if (tx_length > 0) {
obj_in->tx_buff.buffer = (void *)p_buf;
obj_in->tx_buff.length = tx_length;
obj_in->tx_buff.pos = 0;
obj->tx_pending = true;
// Enable interrupts to complete transmission.
Cy_SCB_SetTxInterruptMask(obj->base, CY_SCB_TX_INTR_LEVEL | CY_SCB_UART_TX_DONE);
} else {
// Enable interrupt to signal completing of the transmission.
Cy_SCB_SetTxInterruptMask(obj->base, CY_SCB_UART_TX_DONE);
}
return tx_length;
}
void serial_rx_asynch(serial_t *obj_in, void *rx, size_t rx_length, uint8_t rx_width, uint32_t handler, uint32_t event, uint8_t char_match, DMAUsage hint)
{
serial_obj_t *obj = OBJ_P(obj_in);
(void)rx_width; // Obsolete argument
(void)hint; // At the moment we do not support DAM transfers, so this parameter gets ignored.
if (obj->rx_pending || (rx_length == 0)) {
return;
}
obj_in->char_match = char_match;
obj_in->char_found = false;
obj->rx_events = event;
obj_in->rx_buff.buffer = rx;
obj_in->rx_buff.length = rx_length;
obj_in->rx_buff.pos = 0;
obj->async_handler = (cy_israddress)handler;
if (serial_irq_setup_channel(obj) < 0) {
return;
}
obj->rx_pending = true;
// Enable interrupts to start receiving.
Cy_SCB_SetRxInterruptMask(obj->base, CY_SCB_UART_RX_INTR_MASK & ~CY_SCB_RX_INTR_UART_BREAK_DETECT);
}
uint8_t serial_tx_active(serial_t *obj)
{
return obj->serial.tx_pending;
}
uint8_t serial_rx_active(serial_t *obj)
{
return obj->serial.rx_pending;
}
int serial_irq_handler_asynch(serial_t *obj_in)
{
uint32_t cur_events = 0;
uint32_t tx_status;
uint32_t rx_status;
serial_obj_t *obj = OBJ_P(obj_in);
rx_status = Cy_SCB_GetRxInterruptStatusMasked(obj->base);
tx_status = Cy_SCB_GetTxInterruptStatusMasked(obj->base);
if (tx_status & CY_SCB_TX_INTR_LEVEL) {
// FIFO has space available for more TX
uint8_t *ptr = obj_in->tx_buff.buffer;
ptr += obj_in->tx_buff.pos;
while ((obj_in->tx_buff.pos < obj_in->tx_buff.length) &&
Cy_SCB_UART_Put(obj->base, *ptr)) {
++ptr;
++(obj_in->tx_buff.pos);
}
if (obj_in->tx_buff.pos == obj_in->tx_buff.length) {
// No more bytes to follow; check to see if we need to signal completion.
if (obj->tx_events & SERIAL_EVENT_TX_COMPLETE) {
// Disable FIFO interrupt as there are no more bytes to follow.
Cy_SCB_SetTxInterruptMask(obj->base, CY_SCB_UART_TX_DONE);
} else {
// Nothing more to do, mark end of transmission.
serial_finish_tx_asynch(obj);
}
}
}
if (tx_status & CY_SCB_TX_INTR_UART_DONE) {
// Mark end of the transmission.
serial_finish_tx_asynch(obj);
cur_events |= SERIAL_EVENT_TX_COMPLETE & obj->tx_events;
}
Cy_SCB_ClearTxInterrupt(obj->base, tx_status);
if (rx_status & CY_SCB_RX_INTR_OVERFLOW) {
cur_events |= SERIAL_EVENT_RX_OVERRUN_ERROR & obj->rx_events;
}
if (rx_status & CY_SCB_RX_INTR_UART_FRAME_ERROR) {
cur_events |= SERIAL_EVENT_RX_FRAMING_ERROR & obj->rx_events;
}
if (rx_status & CY_SCB_RX_INTR_UART_PARITY_ERROR) {
cur_events |= SERIAL_EVENT_RX_PARITY_ERROR & obj->rx_events;
}
if (rx_status & CY_SCB_RX_INTR_LEVEL) {
uint8_t *ptr = obj_in->rx_buff.buffer;
ptr += obj_in->rx_buff.pos;
uint32_t fifo_cnt = Cy_SCB_UART_GetNumInRxFifo(obj->base);
while ((obj_in->rx_buff.pos < obj_in->rx_buff.length) && fifo_cnt) {
uint32_t c = Cy_SCB_UART_Get(obj->base);
*ptr++ = (uint8_t)c;
++(obj_in->rx_buff.pos);
--fifo_cnt;
// Check for character match condition.
if (obj_in->char_match != SERIAL_RESERVED_CHAR_MATCH) {
if (c == obj_in->char_match) {
obj_in->char_found = true;
cur_events |= SERIAL_EVENT_RX_CHARACTER_MATCH & obj->rx_events;
// Clamp RX.
obj_in->rx_buff.length = obj_in->rx_buff.pos;
break;
}
}
}
if (obj_in->rx_buff.pos == obj_in->rx_buff.length) {
cur_events |= SERIAL_EVENT_RX_COMPLETE & obj->rx_events;
}
}
// Any event should end operation.
if (cur_events & SERIAL_EVENT_RX_ALL) {
serial_finish_rx_asynch(obj);
}
Cy_SCB_ClearRxInterrupt(obj->base, rx_status);
return cur_events;
}
void serial_tx_abort_asynch(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
serial_finish_tx_asynch(obj);
Cy_SCB_UART_ClearTxFifo(obj->base);
}
void serial_rx_abort_asynch(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
serial_finish_rx_asynch(obj);
Cy_SCB_UART_ClearRxFifo(obj->base);
}
#endif // DEVICE_SERIAL_ASYNCH
#endif // DEVICE_SERIAL
|
the_stack_data/152095.c | #include <stdio.h>
struct Student
{
char name[20];
char roll[20];
float subject_marks[20];
float total;
};
struct Subject
{
char name[20];
float total;
};
struct Class
{
struct Student student;
struct Subject subject[20];
};
float students_total[20];
float subjects_total[20];
float student_total;
float subject_total;
float student_highest = 0;
float subject_highest = 0;
int student_highest_index[20];
int subject_highest_index[20];
int student_highest_total_index;
int subject_highest_total_index;
void input_students(struct Class mca[], int n);
void input_subjects(struct Class mca[], int m);
void input_marks(struct Class mca[], int n, int m);
void calculate(struct Class mca[], int n, int m);
void print_results(struct Class mca[], int n, int m);
int main()
{
struct Class mca[20];
int i, j, n, m;
printf("Enter number of students (less than 20): \n");
scanf("%d", &n);
printf("\n");
input_students(mca, n);
printf("Enter number of subjects per student (less than 10): \n");
scanf("%d", &m);
printf("\n");
input_subjects(mca, m);
input_marks(mca, n, m);
calculate(mca, n, m);
print_results(mca, n, m);
}
void input_students(struct Class mca[], int n)
{
int i;
printf("Enter student details: \n");
printf("\n");
for (i = 0; i < n; i++)
{
printf("Enter student %d name: \n", i + 1);
scanf("%s", &mca[i].student.name);
printf("Enter student %d roll: \n", i + 1);
scanf("%s", &mca[i].student.roll);
printf("\n");
}
}
void input_subjects(struct Class mca[], int m)
{
int i;
printf("Enter subject details: \n");
printf("\n");
for (i = 0; i < m; i++)
{
printf("Enter subject %d name: \n", i + 1);
scanf("%s", &mca[i].subject[i].name);
printf("\n");
}
}
void input_marks(struct Class mca[], int n, int m)
{
int i, j;
for (i = 0; i < n; i++)
{
printf("Enter student %d, %s, %s for the following subjects: \n", i + 1, mca[i].student.name, mca[i].student.roll);
for (j = 0; j < m; j++)
{
printf("%s marks: ", mca[j].subject[j].name);
scanf("%f", &mca[i].student.subject_marks[j]);
}
printf("\n");
}
}
void calculate(struct Class mca[], int n, int m)
{
int i, j;
for (i = 0; i < n; i++)
{
student_total = 0;
for (j = 0; j < m; j++)
{
student_total += mca[i].student.subject_marks[j];
}
students_total[i] = student_total;
}
printf("\n");
int high_index;
for (i = 0; i < m; i++)
{
subject_total = 0;
for (j = 0; j < n; j++)
{
subject_total += mca[j].student.subject_marks[i];
if (mca[j].student.subject_marks[i] > student_highest)
{
student_highest = mca[j].student.subject_marks[i];
high_index = j;
}
}
student_highest_index[i] = high_index;
student_highest = 0;
subjects_total[i] = subject_total;
}
// for (i = 0; i < m; i++)
// {
// printf("Student highest index: %d\t", student_highest_index[i]);
// }
// printf("\n");
}
void print_results(struct Class mca[], int n, int m)
{
int i, j;
printf("Total - Marks of Students: \n\n");
for (i = 0; i < n; i++)
{
printf("Marks of %s, Roll: %s\n", mca[i].student.name, mca[i].student.roll);
printf("Total: %f\n", students_total[i]);
printf("Percentage: %f\n", (students_total[i] / (m * 100)) * 100);
printf("\n");
}
printf("Total - Marks of Subjects: \n\n");
for (i = 0; i < m; i++)
{
printf("Marks of %s: \n", mca[i].subject[i].name);
printf("Total: %f\n", subjects_total[i]);
printf("Percentage: %f\n", (subjects_total[i] / (m * 100)) * 100);
printf("\n");
}
printf("Subject wise - Highest: \n\n");
for (i = 0; i < m; i++)
{
printf("Highest in %s is %s\n", mca[i].subject[i].name, mca[student_highest_index[i]].student.name);
}
printf("\n");
printf("Student wise - Overall Highest: \n\n");
float final_highest = 0;
for (i = 0; i < n; i++)
{
if (students_total[i] > final_highest)
{
final_highest = students_total[i];
student_highest_total_index = i;
}
}
printf("%s\n", mca[student_highest_total_index].student.name);
} |
the_stack_data/34512895.c | // RUN: %clang_cc1 -Wall -Werror -triple riscv32 -disable-O0-optnone -emit-llvm -o - %s | opt -S -mem2reg | FileCheck %s
// RUN: %clang_cc1 -Wall -Werror -triple riscv64 -disable-O0-optnone -emit-llvm -o - %s | opt -S -mem2reg | FileCheck %s
void test_eh_return_data_regno() {
// CHECK: store volatile i32 10
// CHECK: store volatile i32 11
volatile int res;
res = __builtin_eh_return_data_regno(0);
res = __builtin_eh_return_data_regno(1);
}
|
the_stack_data/2423.c | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/**
* Benchmark `cos`.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#define NAME "cos"
#define ITERATIONS 1000000
#define REPEATS 3
/**
* Prints the TAP version.
*/
void print_version() {
printf( "TAP version 13\n" );
}
/**
* Prints the TAP summary.
*
* @param total total number of tests
* @param passing total number of passing tests
*/
void print_summary( int total, int passing ) {
printf( "#\n" );
printf( "1..%d\n", total ); // TAP plan
printf( "# total %d\n", total );
printf( "# pass %d\n", passing );
printf( "#\n" );
printf( "# ok\n" );
}
/**
* Prints benchmarks results.
*
* @param elapsed elapsed time in seconds
*/
void print_results( double elapsed ) {
double rate = (double)ITERATIONS / elapsed;
printf( " ---\n" );
printf( " iterations: %d\n", ITERATIONS );
printf( " elapsed: %0.9f\n", elapsed );
printf( " rate: %0.9f\n", rate );
printf( " ...\n" );
}
/**
* Returns a clock time.
*
* @return clock time
*/
double tic() {
struct timeval now;
gettimeofday( &now, NULL );
return (double)now.tv_sec + (double)now.tv_usec/1.0e6;
}
/**
* Generates a random number on the interval [0,1].
*
* @return random number
*/
double rand_double() {
int r = rand();
return (double)r / ( (double)RAND_MAX + 1.0 );
}
/**
* Runs a benchmark.
*
* @return elapsed time in seconds
*/
double benchmark() {
double elapsed;
double x;
double y;
double t;
int i;
t = tic();
for ( i = 0; i < ITERATIONS; i++ ) {
x = ( 20.0*rand_double() ) - 10.0;
y = cos( x );
if ( y != y ) {
printf( "should not return NaN\n" );
break;
}
}
elapsed = tic() - t;
if ( y != y ) {
printf( "should not return NaN\n" );
}
return elapsed;
}
/**
* Main execution sequence.
*/
int main( void ) {
double elapsed;
int i;
// Use the current time to seed the random number generator:
srand( time( NULL ) );
print_version();
for ( i = 0; i < REPEATS; i++ ) {
printf( "# c::%s\n", NAME );
elapsed = benchmark();
print_results( elapsed );
printf( "ok %d benchmark finished\n", i+1 );
}
print_summary( REPEATS, REPEATS );
}
|
the_stack_data/57951684.c | /* { dg-do compile } */
/* { dg-options "-O -ffast-math" } */
_Complex float f (_Complex float a)
{
_Complex float b = a / a;
return b;
}
|
the_stack_data/193892328.c | // autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <sched.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/capability.h>
#include <linux/genetlink.h>
#include <linux/if_addr.h>
#include <linux/if_ether.h>
#include <linux/if_link.h>
#include <linux/if_tun.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/neighbour.h>
#include <linux/net.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/tcp.h>
#include <linux/veth.h>
unsigned long long procid;
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
struct nlmsg {
char* pos;
int nesting;
struct nlattr* nested[8];
char buf[1024];
};
static struct nlmsg nlmsg;
static void netlink_init(struct nlmsg* nlmsg, int typ, int flags,
const void* data, int size)
{
memset(nlmsg, 0, sizeof(*nlmsg));
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_type = typ;
hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
memcpy(hdr + 1, data, size);
nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size);
}
static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data,
int size)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_len = sizeof(*attr) + size;
attr->nla_type = typ;
memcpy(attr + 1, data, size);
nlmsg->pos += NLMSG_ALIGN(attr->nla_len);
}
static void netlink_nest(struct nlmsg* nlmsg, int typ)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_type = typ;
nlmsg->pos += sizeof(*attr);
nlmsg->nested[nlmsg->nesting++] = attr;
}
static void netlink_done(struct nlmsg* nlmsg)
{
struct nlattr* attr = nlmsg->nested[--nlmsg->nesting];
attr->nla_len = nlmsg->pos - (char*)attr;
}
static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type,
int* reply_len)
{
if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting)
exit(1);
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_len = nlmsg->pos - nlmsg->buf;
struct sockaddr_nl addr;
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0,
(struct sockaddr*)&addr, sizeof(addr));
if (n != hdr->nlmsg_len)
exit(1);
n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
if (hdr->nlmsg_type == NLMSG_DONE) {
*reply_len = 0;
return 0;
}
if (n < sizeof(struct nlmsghdr))
exit(1);
if (reply_len && hdr->nlmsg_type == reply_type) {
*reply_len = n;
return 0;
}
if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr))
exit(1);
if (hdr->nlmsg_type != NLMSG_ERROR)
exit(1);
return -((struct nlmsgerr*)(hdr + 1))->error;
}
static int netlink_send(struct nlmsg* nlmsg, int sock)
{
return netlink_send_ext(nlmsg, sock, 0, NULL);
}
static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset,
unsigned int total_len)
{
struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset);
if (offset == total_len || offset + hdr->nlmsg_len > total_len)
return -1;
return hdr->nlmsg_len;
}
static void netlink_add_device_impl(struct nlmsg* nlmsg, const char* type,
const char* name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
netlink_init(nlmsg, RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr,
sizeof(hdr));
if (name)
netlink_attr(nlmsg, IFLA_IFNAME, name, strlen(name));
netlink_nest(nlmsg, IFLA_LINKINFO);
netlink_attr(nlmsg, IFLA_INFO_KIND, type, strlen(type));
}
static void netlink_add_device(struct nlmsg* nlmsg, int sock, const char* type,
const char* name)
{
netlink_add_device_impl(nlmsg, type, name);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_veth(struct nlmsg* nlmsg, int sock, const char* name,
const char* peer)
{
netlink_add_device_impl(nlmsg, "veth", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_nest(nlmsg, VETH_INFO_PEER);
nlmsg->pos += sizeof(struct ifinfomsg);
netlink_attr(nlmsg, IFLA_IFNAME, peer, strlen(peer));
netlink_done(nlmsg);
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_hsr(struct nlmsg* nlmsg, int sock, const char* name,
const char* slave1, const char* slave2)
{
netlink_add_device_impl(nlmsg, "hsr", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
int ifindex1 = if_nametoindex(slave1);
netlink_attr(nlmsg, IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1));
int ifindex2 = if_nametoindex(slave2);
netlink_attr(nlmsg, IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2));
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_linked(struct nlmsg* nlmsg, int sock, const char* type,
const char* name, const char* link)
{
netlink_add_device_impl(nlmsg, type, name);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_vlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link, uint16_t id, uint16_t proto)
{
netlink_add_device_impl(nlmsg, "vlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_VLAN_ID, &id, sizeof(id));
netlink_attr(nlmsg, IFLA_VLAN_PROTOCOL, &proto, sizeof(proto));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_macvlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link)
{
netlink_add_device_impl(nlmsg, "macvlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
uint32_t mode = MACVLAN_MODE_BRIDGE;
netlink_attr(nlmsg, IFLA_MACVLAN_MODE, &mode, sizeof(mode));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_geneve(struct nlmsg* nlmsg, int sock, const char* name,
uint32_t vni, struct in_addr* addr4,
struct in6_addr* addr6)
{
netlink_add_device_impl(nlmsg, "geneve", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_GENEVE_ID, &vni, sizeof(vni));
if (addr4)
netlink_attr(nlmsg, IFLA_GENEVE_REMOTE, addr4, sizeof(*addr4));
if (addr6)
netlink_attr(nlmsg, IFLA_GENEVE_REMOTE6, addr6, sizeof(*addr6));
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
#define IFLA_IPVLAN_FLAGS 2
#define IPVLAN_MODE_L3S 2
#undef IPVLAN_F_VEPA
#define IPVLAN_F_VEPA 2
static void netlink_add_ipvlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link, uint16_t mode, uint16_t flags)
{
netlink_add_device_impl(nlmsg, "ipvlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_IPVLAN_MODE, &mode, sizeof(mode));
netlink_attr(nlmsg, IFLA_IPVLAN_FLAGS, &flags, sizeof(flags));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_device_change(struct nlmsg* nlmsg, int sock,
const char* name, bool up, const char* master,
const void* mac, int macsize,
const char* new_name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
if (up)
hdr.ifi_flags = hdr.ifi_change = IFF_UP;
hdr.ifi_index = if_nametoindex(name);
netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr));
if (new_name)
netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name));
if (master) {
int ifindex = if_nametoindex(master);
netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex));
}
if (macsize)
netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static int netlink_add_addr(struct nlmsg* nlmsg, int sock, const char* dev,
const void* addr, int addrsize)
{
struct ifaddrmsg hdr;
memset(&hdr, 0, sizeof(hdr));
hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6;
hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120;
hdr.ifa_scope = RT_SCOPE_UNIVERSE;
hdr.ifa_index = if_nametoindex(dev);
netlink_init(nlmsg, RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr,
sizeof(hdr));
netlink_attr(nlmsg, IFA_LOCAL, addr, addrsize);
netlink_attr(nlmsg, IFA_ADDRESS, addr, addrsize);
return netlink_send(nlmsg, sock);
}
static void netlink_add_addr4(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in_addr in_addr;
inet_pton(AF_INET, addr, &in_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in_addr, sizeof(in_addr));
(void)err;
}
static void netlink_add_addr6(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in6_addr in6_addr;
inet_pton(AF_INET6, addr, &in6_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in6_addr, sizeof(in6_addr));
(void)err;
}
#define DEVLINK_FAMILY_NAME "devlink"
#define DEVLINK_CMD_PORT_GET 5
#define DEVLINK_ATTR_BUS_NAME 1
#define DEVLINK_ATTR_DEV_NAME 2
#define DEVLINK_ATTR_NETDEV_NAME 7
static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
struct nlattr* attr;
int err, n;
uint16_t id = 0;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME,
strlen(DEVLINK_FAMILY_NAME) + 1);
err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */
return id;
}
static struct nlmsg nlmsg2;
static void initialize_devlink_ports(const char* bus_name, const char* dev_name,
const char* netdev_prefix)
{
struct genlmsghdr genlhdr;
int len, total_len, id, err, offset;
uint16_t netdev_index;
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (rtsock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_PORT_GET;
netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
err = netlink_send_ext(&nlmsg, sock, id, &total_len);
if (err) {
goto error;
}
offset = 0;
netdev_index = 0;
while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) {
struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg.buf + offset + len;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) {
char* port_name;
char netdev_name[IFNAMSIZ];
port_name = (char*)(attr + 1);
snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix,
netdev_index);
netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0,
netdev_name);
break;
}
}
offset += len;
netdev_index++;
}
error:
close(rtsock);
close(sock);
}
#define DEV_IPV4 "172.20.20.%d"
#define DEV_IPV6 "fe80::%02x"
#define DEV_MAC 0x00aaaaaaaaaa
static void netdevsim_add(unsigned int addr, unsigned int port_count)
{
char buf[16];
sprintf(buf, "%u %u", addr, port_count);
if (write_file("/sys/bus/netdevsim/new_device", buf)) {
snprintf(buf, sizeof(buf), "netdevsim%d", addr);
initialize_devlink_ports("netdevsim", buf, "netdevsim");
}
}
#define WG_GENL_NAME "wireguard"
enum wg_cmd {
WG_CMD_GET_DEVICE,
WG_CMD_SET_DEVICE,
};
enum wgdevice_attribute {
WGDEVICE_A_UNSPEC,
WGDEVICE_A_IFINDEX,
WGDEVICE_A_IFNAME,
WGDEVICE_A_PRIVATE_KEY,
WGDEVICE_A_PUBLIC_KEY,
WGDEVICE_A_FLAGS,
WGDEVICE_A_LISTEN_PORT,
WGDEVICE_A_FWMARK,
WGDEVICE_A_PEERS,
};
enum wgpeer_attribute {
WGPEER_A_UNSPEC,
WGPEER_A_PUBLIC_KEY,
WGPEER_A_PRESHARED_KEY,
WGPEER_A_FLAGS,
WGPEER_A_ENDPOINT,
WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
WGPEER_A_LAST_HANDSHAKE_TIME,
WGPEER_A_RX_BYTES,
WGPEER_A_TX_BYTES,
WGPEER_A_ALLOWEDIPS,
WGPEER_A_PROTOCOL_VERSION,
};
enum wgallowedip_attribute {
WGALLOWEDIP_A_UNSPEC,
WGALLOWEDIP_A_FAMILY,
WGALLOWEDIP_A_IPADDR,
WGALLOWEDIP_A_CIDR_MASK,
};
static int netlink_wireguard_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
struct nlattr* attr;
int err, n;
uint16_t id = 0;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, WG_GENL_NAME,
strlen(WG_GENL_NAME) + 1);
err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */
return id;
}
static void netlink_wireguard_setup(void)
{
const char ifname_a[] = "wg0";
const char ifname_b[] = "wg1";
const char ifname_c[] = "wg2";
const char private_a[] =
"\xa0\x5c\xa8\x4f\x6c\x9c\x8e\x38\x53\xe2\xfd\x7a\x70\xae\x0f\xb2\x0f\xa1"
"\x52\x60\x0c\xb0\x08\x45\x17\x4f\x08\x07\x6f\x8d\x78\x43";
const char private_b[] =
"\xb0\x80\x73\xe8\xd4\x4e\x91\xe3\xda\x92\x2c\x22\x43\x82\x44\xbb\x88\x5c"
"\x69\xe2\x69\xc8\xe9\xd8\x35\xb1\x14\x29\x3a\x4d\xdc\x6e";
const char private_c[] =
"\xa0\xcb\x87\x9a\x47\xf5\xbc\x64\x4c\x0e\x69\x3f\xa6\xd0\x31\xc7\x4a\x15"
"\x53\xb6\xe9\x01\xb9\xff\x2f\x51\x8c\x78\x04\x2f\xb5\x42";
const char public_a[] =
"\x97\x5c\x9d\x81\xc9\x83\xc8\x20\x9e\xe7\x81\x25\x4b\x89\x9f\x8e\xd9\x25"
"\xae\x9f\x09\x23\xc2\x3c\x62\xf5\x3c\x57\xcd\xbf\x69\x1c";
const char public_b[] =
"\xd1\x73\x28\x99\xf6\x11\xcd\x89\x94\x03\x4d\x7f\x41\x3d\xc9\x57\x63\x0e"
"\x54\x93\xc2\x85\xac\xa4\x00\x65\xcb\x63\x11\xbe\x69\x6b";
const char public_c[] =
"\xf4\x4d\xa3\x67\xa8\x8e\xe6\x56\x4f\x02\x02\x11\x45\x67\x27\x08\x2f\x5c"
"\xeb\xee\x8b\x1b\xf5\xeb\x73\x37\x34\x1b\x45\x9b\x39\x22";
const uint16_t listen_a = 20001;
const uint16_t listen_b = 20002;
const uint16_t listen_c = 20003;
const uint16_t af_inet = AF_INET;
const uint16_t af_inet6 = AF_INET6;
/* Unused, but useful in case we change this:
const struct sockaddr_in endpoint_a_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_a),
.sin_addr = {htonl(INADDR_LOOPBACK)}};*/
const struct sockaddr_in endpoint_b_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_b),
.sin_addr = {htonl(INADDR_LOOPBACK)}};
const struct sockaddr_in endpoint_c_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_c),
.sin_addr = {htonl(INADDR_LOOPBACK)}};
struct sockaddr_in6 endpoint_a_v6 = {.sin6_family = AF_INET6,
.sin6_port = htons(listen_a)};
endpoint_a_v6.sin6_addr = in6addr_loopback;
/* Unused, but useful in case we change this:
const struct sockaddr_in6 endpoint_b_v6 = {
.sin6_family = AF_INET6,
.sin6_port = htons(listen_b)};
endpoint_b_v6.sin6_addr = in6addr_loopback; */
struct sockaddr_in6 endpoint_c_v6 = {.sin6_family = AF_INET6,
.sin6_port = htons(listen_c)};
endpoint_c_v6.sin6_addr = in6addr_loopback;
const struct in_addr first_half_v4 = {0};
const struct in_addr second_half_v4 = {htonl(128 << 24)};
const struct in6_addr first_half_v6 = {{{0}}};
const struct in6_addr second_half_v6 = {{{0x80}}};
const uint8_t half_cidr = 1;
const uint16_t persistent_keepalives[] = {1, 3, 7, 9, 14, 19};
struct genlmsghdr genlhdr = {.cmd = WG_CMD_SET_DEVICE, .version = 1};
int sock;
int id, err;
sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
id = netlink_wireguard_id_get(&nlmsg, sock);
if (id == -1)
goto error;
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_a, strlen(ifname_a) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_a, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_a, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4,
sizeof(endpoint_b_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[0], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v6,
sizeof(endpoint_c_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[1], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_b, strlen(ifname_b) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_b, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_b, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6,
sizeof(endpoint_a_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[2], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v4,
sizeof(endpoint_c_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[3], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_c, strlen(ifname_c) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_c, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_c, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6,
sizeof(endpoint_a_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[4], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4,
sizeof(endpoint_b_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[5], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
error:
close(sock);
}
static void initialize_netdevices(void)
{
char netdevsim[16];
sprintf(netdevsim, "netdevsim%d", (int)procid);
struct {
const char* type;
const char* dev;
} devtypes[] = {
{"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"},
{"vcan", "vcan0"}, {"bond", "bond0"},
{"team", "team0"}, {"dummy", "dummy0"},
{"nlmon", "nlmon0"}, {"caif", "caif0"},
{"batadv", "batadv0"}, {"vxcan", "vxcan1"},
{"netdevsim", netdevsim}, {"veth", 0},
{"xfrm", "xfrm0"}, {"wireguard", "wg0"},
{"wireguard", "wg1"}, {"wireguard", "wg2"},
};
const char* devmasters[] = {"bridge", "bond", "team", "batadv"};
struct {
const char* name;
int macsize;
bool noipv6;
} devices[] = {
{"lo", ETH_ALEN},
{"sit0", 0},
{"bridge0", ETH_ALEN},
{"vcan0", 0, true},
{"tunl0", 0},
{"gre0", 0},
{"gretap0", ETH_ALEN},
{"ip_vti0", 0},
{"ip6_vti0", 0},
{"ip6tnl0", 0},
{"ip6gre0", 0},
{"ip6gretap0", ETH_ALEN},
{"erspan0", ETH_ALEN},
{"bond0", ETH_ALEN},
{"veth0", ETH_ALEN},
{"veth1", ETH_ALEN},
{"team0", ETH_ALEN},
{"veth0_to_bridge", ETH_ALEN},
{"veth1_to_bridge", ETH_ALEN},
{"veth0_to_bond", ETH_ALEN},
{"veth1_to_bond", ETH_ALEN},
{"veth0_to_team", ETH_ALEN},
{"veth1_to_team", ETH_ALEN},
{"veth0_to_hsr", ETH_ALEN},
{"veth1_to_hsr", ETH_ALEN},
{"hsr0", 0},
{"dummy0", ETH_ALEN},
{"nlmon0", 0},
{"vxcan0", 0, true},
{"vxcan1", 0, true},
{"caif0", ETH_ALEN},
{"batadv0", ETH_ALEN},
{netdevsim, ETH_ALEN},
{"xfrm0", ETH_ALEN},
{"veth0_virt_wifi", ETH_ALEN},
{"veth1_virt_wifi", ETH_ALEN},
{"virt_wifi0", ETH_ALEN},
{"veth0_vlan", ETH_ALEN},
{"veth1_vlan", ETH_ALEN},
{"vlan0", ETH_ALEN},
{"vlan1", ETH_ALEN},
{"macvlan0", ETH_ALEN},
{"macvlan1", ETH_ALEN},
{"ipvlan0", ETH_ALEN},
{"ipvlan1", ETH_ALEN},
{"veth0_macvtap", ETH_ALEN},
{"veth1_macvtap", ETH_ALEN},
{"macvtap0", ETH_ALEN},
{"macsec0", ETH_ALEN},
{"veth0_to_batadv", ETH_ALEN},
{"veth1_to_batadv", ETH_ALEN},
{"batadv_slave_0", ETH_ALEN},
{"batadv_slave_1", ETH_ALEN},
{"geneve0", ETH_ALEN},
{"geneve1", ETH_ALEN},
{"wg0", 0},
{"wg1", 0},
{"wg2", 0},
};
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
unsigned i;
for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++)
netlink_add_device(&nlmsg, sock, devtypes[i].type, devtypes[i].dev);
for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) {
char master[32], slave0[32], veth0[32], slave1[32], veth1[32];
sprintf(slave0, "%s_slave_0", devmasters[i]);
sprintf(veth0, "veth0_to_%s", devmasters[i]);
netlink_add_veth(&nlmsg, sock, slave0, veth0);
sprintf(slave1, "%s_slave_1", devmasters[i]);
sprintf(veth1, "veth1_to_%s", devmasters[i]);
netlink_add_veth(&nlmsg, sock, slave1, veth1);
sprintf(master, "%s0", devmasters[i]);
netlink_device_change(&nlmsg, sock, slave0, false, master, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, slave1, false, master, 0, 0, NULL);
}
netlink_device_change(&nlmsg, sock, "bridge_slave_0", true, 0, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, "bridge_slave_1", true, 0, 0, 0, NULL);
netlink_add_veth(&nlmsg, sock, "hsr_slave_0", "veth0_to_hsr");
netlink_add_veth(&nlmsg, sock, "hsr_slave_1", "veth1_to_hsr");
netlink_add_hsr(&nlmsg, sock, "hsr0", "hsr_slave_0", "hsr_slave_1");
netlink_device_change(&nlmsg, sock, "hsr_slave_0", true, 0, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, "hsr_slave_1", true, 0, 0, 0, NULL);
netlink_add_veth(&nlmsg, sock, "veth0_virt_wifi", "veth1_virt_wifi");
netlink_add_linked(&nlmsg, sock, "virt_wifi", "virt_wifi0",
"veth1_virt_wifi");
netlink_add_veth(&nlmsg, sock, "veth0_vlan", "veth1_vlan");
netlink_add_vlan(&nlmsg, sock, "vlan0", "veth0_vlan", 0, htons(ETH_P_8021Q));
netlink_add_vlan(&nlmsg, sock, "vlan1", "veth0_vlan", 1, htons(ETH_P_8021AD));
netlink_add_macvlan(&nlmsg, sock, "macvlan0", "veth1_vlan");
netlink_add_macvlan(&nlmsg, sock, "macvlan1", "veth1_vlan");
netlink_add_ipvlan(&nlmsg, sock, "ipvlan0", "veth0_vlan", IPVLAN_MODE_L2, 0);
netlink_add_ipvlan(&nlmsg, sock, "ipvlan1", "veth0_vlan", IPVLAN_MODE_L3S,
IPVLAN_F_VEPA);
netlink_add_veth(&nlmsg, sock, "veth0_macvtap", "veth1_macvtap");
netlink_add_linked(&nlmsg, sock, "macvtap", "macvtap0", "veth0_macvtap");
netlink_add_linked(&nlmsg, sock, "macsec", "macsec0", "veth1_macvtap");
char addr[32];
sprintf(addr, DEV_IPV4, 14 + 10);
struct in_addr geneve_addr4;
if (inet_pton(AF_INET, addr, &geneve_addr4) <= 0)
exit(1);
struct in6_addr geneve_addr6;
if (inet_pton(AF_INET6, "fc00::01", &geneve_addr6) <= 0)
exit(1);
netlink_add_geneve(&nlmsg, sock, "geneve0", 0, &geneve_addr4, 0);
netlink_add_geneve(&nlmsg, sock, "geneve1", 1, 0, &geneve_addr6);
netdevsim_add((int)procid, 4);
netlink_wireguard_setup();
for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) {
char addr[32];
sprintf(addr, DEV_IPV4, i + 10);
netlink_add_addr4(&nlmsg, sock, devices[i].name, addr);
if (!devices[i].noipv6) {
sprintf(addr, DEV_IPV6, i + 10);
netlink_add_addr6(&nlmsg, sock, devices[i].name, addr);
}
uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40);
netlink_device_change(&nlmsg, sock, devices[i].name, true, 0, &macaddr,
devices[i].macsize, NULL);
}
close(sock);
}
static void initialize_netdevices_init(void)
{
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
struct {
const char* type;
int macsize;
bool noipv6;
bool noup;
} devtypes[] = {
{"nr", 7, true},
{"rose", 5, true, true},
};
unsigned i;
for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) {
char dev[32], addr[32];
sprintf(dev, "%s%d", devtypes[i].type, (int)procid);
sprintf(addr, "172.30.%d.%d", i, (int)procid + 1);
netlink_add_addr4(&nlmsg, sock, dev, addr);
if (!devtypes[i].noipv6) {
sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1);
netlink_add_addr6(&nlmsg, sock, dev, addr);
}
int macsize = devtypes[i].macsize;
uint64_t macaddr = 0xbbbbbb +
((unsigned long long)i << (8 * (macsize - 2))) +
(procid << (8 * (macsize - 1)));
netlink_device_change(&nlmsg, sock, dev, !devtypes[i].noup, 0, &macaddr,
macsize, NULL);
}
close(sock);
}
static void setup_common()
{
if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) {
}
}
static void loop();
static void sandbox_common()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
setsid();
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = (200 << 20);
setrlimit(RLIMIT_AS, &rlim);
rlim.rlim_cur = rlim.rlim_max = 32 << 20;
setrlimit(RLIMIT_MEMLOCK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 136 << 20;
setrlimit(RLIMIT_FSIZE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 1 << 20;
setrlimit(RLIMIT_STACK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 0;
setrlimit(RLIMIT_CORE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 256;
setrlimit(RLIMIT_NOFILE, &rlim);
if (unshare(CLONE_NEWNS)) {
}
if (unshare(CLONE_NEWIPC)) {
}
if (unshare(0x02000000)) {
}
if (unshare(CLONE_NEWUTS)) {
}
if (unshare(CLONE_SYSVSEM)) {
}
typedef struct {
const char* name;
const char* value;
} sysctl_t;
static const sysctl_t sysctls[] = {
{"/proc/sys/kernel/shmmax", "16777216"},
{"/proc/sys/kernel/shmall", "536870912"},
{"/proc/sys/kernel/shmmni", "1024"},
{"/proc/sys/kernel/msgmax", "8192"},
{"/proc/sys/kernel/msgmni", "1024"},
{"/proc/sys/kernel/msgmnb", "1024"},
{"/proc/sys/kernel/sem", "1024 1048576 500 1024"},
};
unsigned i;
for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++)
write_file(sysctls[i].name, sysctls[i].value);
}
int wait_for_loop(int pid)
{
if (pid < 0)
exit(1);
int status = 0;
while (waitpid(-1, &status, __WALL) != pid) {
}
return WEXITSTATUS(status);
}
static void drop_caps(void)
{
struct __user_cap_header_struct cap_hdr = {};
struct __user_cap_data_struct cap_data[2] = {};
cap_hdr.version = _LINUX_CAPABILITY_VERSION_3;
cap_hdr.pid = getpid();
if (syscall(SYS_capget, &cap_hdr, &cap_data))
exit(1);
const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE);
cap_data[0].effective &= ~drop;
cap_data[0].permitted &= ~drop;
cap_data[0].inheritable &= ~drop;
if (syscall(SYS_capset, &cap_hdr, &cap_data))
exit(1);
}
static int do_sandbox_none(void)
{
if (unshare(CLONE_NEWPID)) {
}
int pid = fork();
if (pid != 0)
return wait_for_loop(pid);
setup_common();
sandbox_common();
drop_caps();
initialize_netdevices_init();
if (unshare(CLONE_NEWNET)) {
}
initialize_netdevices();
loop();
exit(1);
}
uint64_t r[1] = {0xffffffffffffffff};
void loop(void)
{
intptr_t res = 0;
res = syscall(__NR_socket, 2ul, 2ul, 0x88ul);
if (res != -1)
r[0] = res;
memcpy((void*)0x20001880,
"wg0\000\000\000\000\000\000\000\000\000\000\000\000\000", 16);
*(uint32_t*)0x20001890 = 0;
syscall(__NR_ioctl, r[0], 0x8922ul, 0x20001880ul);
}
int main(void)
{
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0);
do_sandbox_none();
return 0;
}
|
the_stack_data/532177.c | /*...................................................................................
Name : Sumit Patidar
Roll no : B15237
Purpose : IC250 assignment 2, question 1
Date : 22.08.2016
.....................................................................................*/
// source code to solve puzzle of TOWER OF HANOI using recursion
#include <stdio.h>
void moveTower(int disks, char A, char B, char C); // move tower from peg A to peg B using peg C
static int count = 0;
int main(){
int disk_quantity;
printf("Enter the number of disks: ");
scanf("%d", &disk_quantity);
printf("\n");
// Make a recursive call to function moveTower
moveTower(disk_quantity, 'A', 'B', 'C');
printf("\nTotal number of moves are %d\n", count);
return 0;
}
void moveTower(int disks, char A, char B, char C)
{
if (disks == 1){
count++;
printf("[%d] Moved disk %d from %c to %c\n",count, disks, A, C);
}
else {
// problem is divided to sub 2 problem
moveTower(disks - 1, A, C, B);
count++;
printf("[%d] Moved disk %d from %c to %c\n",count, disks, A, C);
moveTower(disks - 1, B, A, C);
}
} |
the_stack_data/15820.c | #include <stdio.h>
int main(){
printf("My name is Chase!");
return 0;
} |
the_stack_data/12638214.c | #include <stdio.h>
int main(void){
double x,y;
scanf("%lf%lf",&x,&y);
if(-1<=x && x<=1 && -1<=y && y<=1) puts("Yes");
else puts("No");
return 0;
}
|
the_stack_data/70451383.c | int g_i;
int g_k;
void son_bakis_devam(char dizi[16], char board[4][4][4], int i, int k)
{
if (dizi[i] == '1' && i / 4 == 2 && dizi[i + 4] == '3' )
{
if (board[k][0][3] == 'x' && board[k][1][2] == 'x')
{
board[k][2][0] = 'x' ;
board[k][3][1] = 'x' ;
}
}
else if (dizi[i] == '1' && dizi[i - 4] == '3' && i / 4 == 3)
{
if (board[k][3][3] == 'x' && board[k][2][2] == 'x')
{
board[k][1][0] = 'x' ;
board[k][0][1] = 'x' ;
}
}
}
void son_bakis(char dizi[16], char board[4][4][4])
{
g_i = 0;
while (g_i < 16)
{
g_k = g_i % 4;
if (dizi[g_i] == '1' && g_i / 4 == 0 && dizi[g_i + 4] == '3')
{
if (board[0][g_k][3] == 'x' && board[1][g_k][2] == 'x')
{
board[2][g_k][0] = 'x' ;
board[3][g_k][1] = 'x' ;
}
}
else if (dizi[g_i] == '1' && g_i / 4 == 1 && dizi[g_i - 4] == '3' )
{
if (board[3][g_k][3] == 'x' && board[2][g_k][2] == 'x')
{
board[1][g_k][0] = 'x' ;
board[0][g_k][1] = 'x' ;
}
}
son_bakis_devam(dizi, board, g_i, g_k);
g_i++;
}
}
void son_bakis_2_devam(char dizi[16], char board[4][4][4], int i, int k)
{
if (dizi[i] == '1' && i / 4 == 2 && dizi[i + 4] == '3' )
{
if (board[k][0][3] == 'x' && board[k][1][0] == 'x')
{
board[k][2][2] = 'x' ;
board[k][3][1] = 'x' ;
}
}
else if (dizi[i] == '1' && dizi[i - 4] == '3' && i / 4 == 3)
{
if (board[k][3][3] == 'x' && board[k][2][0] == 'x')
{
board[k][1][2] = 'x' ;
board[k][0][1] = 'x' ;
}
}
}
void son_bakis_2(char dizi[16], char board[4][4][4])
{
g_i = 0;
while (g_i < 16)
{
g_k = g_i % 4;
if (dizi[g_i] == '1' && g_i / 4 == 0 && dizi[g_i + 4] == '3')
{
if (board[0][g_k][3] == 'x' && board[1][g_k][0] == 'x')
{
board[2][g_k][2] = 'x' ;
board[3][g_k][1] = 'x' ;
}
}
else if (dizi[g_i] == '1' && g_i / 4 == 1 && dizi[g_i - 4] == '3')
{
if (board[3][g_k][3] == 'x' && board[2][g_k][0] == 'x')
{
board[1][g_k][2] = 'x' ;
board[0][g_k][1] = 'x' ;
}
}
son_bakis_2_devam(dizi, board, g_i, g_k);
g_i++;
}
}
void son_bakis_3(char dizi[16], char board[4][4][4])
{
int i;
int k;
i = 0;
while (i < 16)
{
k = i % 4;
if (dizi[i] == '2' && i / 4 == 0 && dizi[i + 4] == '2')
{
if (board[2][k][3] == 'x' && board[3][k][2] == 'x')
{
board[0][k][1] = 'x' ;
board[1][k][0] = 'x' ;
}
}
else if (dizi[i] == '2' && i / 4 == 2 && dizi[i + 4] == '2' )
{
if (board[k][2][3] == 'x' && board[k][3][2] == 'x')
{
board[k][0][1] = 'x' ;
board[k][1][0] = 'x' ;
}
}
i++;
}
}
|
the_stack_data/154832072.c | /*
* A simple server in the internet domain using TCP
* The port number is passed as an argument
* Version Original de - http://www.linuxhowtos.org/C_C++/socket.htm
* GCC: gcc -o server sockets_1server.c
* Ej. Uso: ./server 8888
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(const char *msg)
{
printf("%s\n",msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
// Armando la estructura "sockaddr_in"
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
memset((void *) &(serv_addr.sin_zero), '\0', 8); // Poner a cero el resto de la estructura
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
printf("Esperando conexiones...\n");
// Llamado bloqueante a accept()
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
printf("Conexion aceptada!\n");
if (newsockfd < 0)
error("ERROR on accept");
memset((void *) buffer, '\0', 256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Este es su mensaje: %s\n",buffer);
n = write(newsockfd,"Recibí tu mensaje!",18);
if (n < 0) error("ERROR writing to socket");
close(newsockfd);
close(sockfd);
return 0;
}
|
the_stack_data/73575933.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function mul8_163
/// Library = EvoApprox8b
/// Circuit = mul8_163
/// Area (180) = 5274
/// Delay (180) = 4.320
/// Power (180) = 2184.00
/// Area (45) = 385
/// Delay (45) = 1.520
/// Power (45) = 187.60
/// Nodes = 95
/// HD = 329978
/// MAE = 259.08649
/// MSE = 113363.70410
/// MRE = 5.48 %
/// WCE = 1574
/// WCRE = 433 %
/// EP = 98.3 %
uint16_t mul8_163(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 n32;
uint8_t n33;
uint8_t n34;
uint8_t n37;
uint8_t n38;
uint8_t n39;
uint8_t n41;
uint8_t n42;
uint8_t n45;
uint8_t n49;
uint8_t n54;
uint8_t n55;
uint8_t n57;
uint8_t n61;
uint8_t n62;
uint8_t n73;
uint8_t n85;
uint8_t n99;
uint8_t n117;
uint8_t n121;
uint8_t n123;
uint8_t n131;
uint8_t n160;
uint8_t n214;
uint8_t n282;
uint8_t n393;
uint8_t n398;
uint8_t n399;
uint8_t n414;
uint8_t n415;
uint8_t n449;
uint8_t n514;
uint8_t n532;
uint8_t n546;
uint8_t n548;
uint8_t n598;
uint8_t n648;
uint8_t n664;
uint8_t n665;
uint8_t n682;
uint8_t n683;
uint8_t n749;
uint8_t n764;
uint8_t n782;
uint8_t n798;
uint8_t n814;
uint8_t n898;
uint8_t n914;
uint8_t n915;
uint8_t n932;
uint8_t n933;
uint8_t n948;
uint8_t n949;
uint8_t n1014;
uint8_t n1032;
uint8_t n1048;
uint8_t n1064;
uint8_t n1082;
uint8_t n1148;
uint8_t n1164;
uint8_t n1165;
uint8_t n1182;
uint8_t n1183;
uint8_t n1198;
uint8_t n1199;
uint8_t n1214;
uint8_t n1215;
uint8_t n1264;
uint8_t n1282;
uint8_t n1298;
uint8_t n1314;
uint8_t n1321;
uint8_t n1332;
uint8_t n1348;
uint8_t n1364;
uint8_t n1399;
uint8_t n1414;
uint8_t n1415;
uint8_t n1432;
uint8_t n1433;
uint8_t n1448;
uint8_t n1449;
uint8_t n1464;
uint8_t n1465;
uint8_t n1482;
uint8_t n1483;
uint8_t n1532;
uint8_t n1548;
uint8_t n1564;
uint8_t n1582;
uint8_t n1598;
uint8_t n1614;
uint8_t n1632;
uint8_t n1664;
uint8_t n1665;
uint8_t n1682;
uint8_t n1683;
uint8_t n1698;
uint8_t n1699;
uint8_t n1714;
uint8_t n1715;
uint8_t n1732;
uint8_t n1733;
uint8_t n1748;
uint8_t n1749;
uint8_t n1764;
uint8_t n1798;
uint8_t n1814;
uint8_t n1832;
uint8_t n1848;
uint8_t n1864;
uint8_t n1882;
uint8_t n1898;
uint8_t n1914;
uint8_t n1932;
uint8_t n1933;
uint8_t n1948;
uint8_t n1949;
uint8_t n1964;
uint8_t n1965;
uint8_t n1982;
uint8_t n1983;
uint8_t n1998;
uint8_t n1999;
uint8_t n2014;
uint8_t n2015;
n32 = n18 & n12;
n33 = n18 & n12;
n34 = ~(n2 & n20 & n22);
n37 = ~(n12 | n34);
n38 = ~(n6 | n34 | n22);
n39 = ~(n6 | n34 | n22);
n41 = n33 & n28;
n42 = ~((n41 | n0) & n22);
n45 = ~(n2 | n42 | n14);
n49 = ~(n41 & n38);
n54 = ~n49;
n55 = ~n49;
n57 = n38 ^ n55;
n61 = ~(n18 & n20);
n62 = ~(n55 & n24);
n73 = ~(n2 & n28);
n85 = n61;
n99 = ~(n33 & n16);
n117 = n85 | n62;
n121 = ~(n57 & n28);
n123 = ~n117;
n131 = n45 | n39;
n160 = ~((n121 | n54) & n99);
n214 = ~((n123 & n160) | n57);
n282 = (n14 & n18) | (~n14 & n39);
n393 = n214 ^ n38;
n398 = n393 & n32;
n399 = n393 & n32;
n414 = n123 ^ n282;
n415 = n123 & n282;
n449 = ~n73;
n514 = n10 & n20;
n532 = n12 & n20;
n546 = n22;
n548 = n14 & n20;
n598 = n399 & n546;
n648 = n398 | n514;
n664 = n414 ^ n532;
n665 = n414 & n532;
n682 = (n415 ^ n548) ^ n665;
n683 = (n415 & n548) | (n548 & n665) | (n415 & n665);
n749 = n6 & n22;
n764 = n8 & n22;
n782 = n10 & n22;
n798 = n12 & n22;
n814 = n14 & n22;
n898 = n648 | n764;
n914 = n664 ^ n782;
n915 = n664 & n782;
n932 = (n682 ^ n798) ^ n915;
n933 = (n682 & n798) | (n798 & n915) | (n682 & n915);
n948 = (n683 ^ n814) ^ n933;
n949 = (n683 & n814) | (n814 & n933) | (n683 & n933);
n1014 = n6 & n24;
n1032 = n8 & n24;
n1048 = n10 & n24;
n1064 = n12 & n24;
n1082 = n14 & n24;
n1148 = n898 | n1014;
n1164 = n914 ^ n1032;
n1165 = n914 & n1032;
n1182 = (n932 ^ n1048) ^ n1165;
n1183 = (n932 & n1048) | (n1048 & n1165) | (n932 & n1165);
n1198 = (n948 ^ n1064) ^ n1183;
n1199 = (n948 & n1064) | (n1064 & n1183) | (n948 & n1183);
n1214 = (n949 ^ n1082) ^ n1199;
n1215 = (n949 & n1082) | (n1082 & n1199) | (n949 & n1199);
n1264 = n4 & n26;
n1282 = n6 & n26;
n1298 = n8 & n26;
n1314 = n10 & n26;
n1321 = n449 | n1182;
n1332 = n12 & n26;
n1348 = n14 & n26;
n1364 = ~(n73 ^ n598);
n1399 = n1148 | n1264;
n1414 = (n1164 ^ n1282) ^ n1399;
n1415 = (n1164 & n1282) | (n1282 & n1399) | (n1164 & n1399);
n1432 = (n1182 ^ n1298) ^ n1415;
n1433 = (n1182 & n1298) | (n1298 & n1415) | (n1182 & n1415);
n1448 = (n1198 ^ n1314) ^ n1433;
n1449 = (n1198 & n1314) | (n1314 & n1433) | (n1198 & n1433);
n1464 = (n1214 ^ n1332) ^ n1449;
n1465 = (n1214 & n1332) | (n1332 & n1449) | (n1214 & n1449);
n1482 = (n1215 ^ n1348) ^ n1465;
n1483 = (n1215 & n1348) | (n1348 & n1465) | (n1215 & n1465);
n1532 = n4 & n28;
n1548 = n6 & n28;
n1564 = n8 & n28;
n1582 = n10 & n28;
n1598 = n12 & n28;
n1614 = n14 & n28;
n1632 = n1433;
n1664 = n1414 ^ n1532;
n1665 = n1414 & n1532;
n1682 = (n1432 ^ n1548) ^ n1665;
n1683 = (n1432 & n1548) | (n1548 & n1665) | (n1432 & n1665);
n1698 = (n1448 ^ n1564) ^ n1683;
n1699 = (n1448 & n1564) | (n1564 & n1683) | (n1448 & n1683);
n1714 = (n1464 ^ n1582) ^ n1699;
n1715 = (n1464 & n1582) | (n1582 & n1699) | (n1464 & n1699);
n1732 = (n1482 ^ n1598) ^ n1715;
n1733 = (n1482 & n1598) | (n1598 & n1715) | (n1482 & n1715);
n1748 = (n1483 ^ n1614) ^ n1733;
n1749 = (n1483 & n1614) | (n1614 & n1733) | (n1483 & n1733);
n1764 = n0 & n30;
n1798 = n4 & n30;
n1814 = n6 & n30;
n1832 = n8 & n30;
n1848 = n10 & n30;
n1864 = n12 & n30;
n1882 = n14 & n30;
n1898 = n37 ^ n1764;
n1914 = n1664;
n1932 = n1682 ^ n1798;
n1933 = n1682 & n1798;
n1948 = (n1698 ^ n1814) ^ n1933;
n1949 = (n1698 & n1814) | (n1814 & n1933) | (n1698 & n1933);
n1964 = (n1714 ^ n1832) ^ n1949;
n1965 = (n1714 & n1832) | (n1832 & n1949) | (n1714 & n1949);
n1982 = (n1732 ^ n1848) ^ n1965;
n1983 = (n1732 & n1848) | (n1848 & n1965) | (n1732 & n1965);
n1998 = (n1748 ^ n1864) ^ n1983;
n1999 = (n1748 & n1864) | (n1864 & n1983) | (n1748 & n1983);
n2014 = (n1749 ^ n1882) ^ n1999;
n2015 = (n1749 & n1882) | (n1882 & n1999) | (n1749 & n1999);
c |= (n1321 & 0x1) << 0;
c |= (n598 & 0x1) << 1;
c |= (n131 & 0x1) << 2;
c |= (n32 & 0x1) << 3;
c |= (n749 & 0x1) << 4;
c |= (n1364 & 0x1) << 5;
c |= (n1632 & 0x1) << 6;
c |= (n1898 & 0x1) << 7;
c |= (n1914 & 0x1) << 8;
c |= (n1932 & 0x1) << 9;
c |= (n1948 & 0x1) << 10;
c |= (n1964 & 0x1) << 11;
c |= (n1982 & 0x1) << 12;
c |= (n1998 & 0x1) << 13;
c |= (n2014 & 0x1) << 14;
c |= (n2015 & 0x1) << 15;
return c;
}
|
the_stack_data/45468.c | /*P5.11 Program to find the product of digits of any number*/
#include<stdio.h>
int main(void)
{
int n,prod=1,rem;
printf("Enter a number : ");
scanf("%d",&n);
while(n>0)
{
rem = n%10; /*taking last digit of n*/
prod*=rem;
n/=10; /*skipping last digit of n*/
}
printf("Product of digits = %d\n",prod);
return 0;
} |
the_stack_data/665194.c | /* $OpenBSD: blt.c,v 1.1 2005/08/31 20:53:49 kettenis Exp $ */
/*
* Written by Mark Kettenis <[email protected]> 2004 Public Domain
*/
#include <sys/types.h>
#include <sys/mman.h>
#include <assert.h>
#include <stddef.h>
typedef unsigned FbStip;
typedef unsigned FbBits;
typedef int FbStride;
typedef int Bool;
extern void fbBlt (FbBits *, FbStride, int, FbBits *, FbStride, int,
int, int, int, FbBits, int, Bool, Bool);
FbBits map[] = { 0x77ff7700, 0x11335577 };
int
main (void)
{
int pagesize;
FbBits *src;
FbBits *dst;
int srcX, dstX;
int bpp;
int alu = 1;
FbBits pm = 0xffffffff;
pagesize = getpagesize();
src = mmap(NULL, 2 * pagesize, PROT_READ|PROT_WRITE, MAP_ANON, -1, 0);
assert(src);
dst = mmap(NULL, 2 * pagesize, PROT_READ|PROT_WRITE, MAP_ANON, -1, 0);
assert(dst);
mprotect((char *)src + pagesize, pagesize, PROT_NONE);
src = (FbBits *)((char *)src + (pagesize - sizeof map));
memcpy (src, map, sizeof map);
for (bpp = 8; bpp <= 32; bpp += 8)
for (dstX = 0; dstX < 64; dstX += bpp)
for (srcX = 0; srcX < 32; srcX += bpp)
fbBlt(src, 1, srcX, dst, 256, dstX,
(32 - srcX), 2, alu, pm, bpp, 0, 0);
for (bpp = 8; bpp <= 32; bpp += 8)
for (dstX = 0; dstX < 64; dstX += bpp)
for (srcX = 0; srcX < 32; srcX += bpp)
fbBlt(src, 1, srcX, dst, 256, dstX,
(64 - srcX), 1, alu, pm, bpp, 0, 0);
return 0;
}
|
the_stack_data/124813.c | /*
this program can be found at: http://www.thegeekstuff.com/2012/05/c-mutex-examples/?refcom
*/
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
int counter;
void* doSomeThing(void *arg)
{
unsigned long i = 0;
counter += 1;
printf("\n Job %d started\n", counter);
for(i=0; i<(0xFFFFFFFF);i++);
printf("\n Job %d finished\n", counter);
return NULL;
}
int main(void)
{
int i = 0;
int err;
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
} |
the_stack_data/162642813.c | //Program in C to impement merge sort algorithm
#include<stdio.h>
//Iterative function to merge individual list items into a list
//It returns the list sorted in ascending order
int merge(int array[],int lb,int mid,int ub)
{
int i=lb,k=lb;
int newarr[20];
int j=mid+1;
//for comparison of array[i] with array[j]
while(i<=mid&&j<=ub)
{
if(array[i]<array[j])
{
newarr[k]=array[i];
i++;
}
else
{
newarr[k]=array[j];
j++;
}
k++;
}
//if array[i] gets exhausted,add array[j] list items
if(i>mid)
{
newarr[k]=array[j];
j++;
k++;
}
else
{
//if array[j] gets exhausted,add array[i] list items
while(i<=mid)
{
newarr[k]=array[i];
i++;
k++;
}
}
//adding elements to the sorted list
for(k=lb;k<=ub;k++)
{
array[k]=newarr[k];
}
}
//divide list into halves recursively
int mergeSort(int array[],int lb,int ub)
{
if(lb<ub)
{
int mid=(lb+ub)/2;
//dividing lists until a single list item remains
mergeSort(array,lb,mid);
mergeSort(array,mid+1,ub);
//merging into a complete sorted list
merge(array,lb,mid,ub);
}
}
//Utility function to print the sorted array
int printArray(int array[],int lb,int ub)
{
printf(" The required array after Sorting :\n");
for(int i=lb;i<=ub;i++)
{
printf(" %d ",array[i]);
}
}
//Driver program to check the above functions with sample input
int main()
{
int array[]={33,5,997,-4,0,18,7,-58};
int lb=0;
int ub=7;
int mid=(lb+ub)/2;
mergeSort(array,lb,ub);
printArray(array,lb,ub);
return 0;
}
|
the_stack_data/107953611.c | #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>
void *thread_one() {
printf("thread_one:int %d main process,the tid=%lu,pid=%ld\n", getpid(), pthread_self(), syscall(SYS_gettid));
}
void *thread_two() {
printf("thread_two:int %d main process,the tid=%lu,pid=%ld\n", getpid(), pthread_self(), syscall(SYS_gettid));
}
int main(int argc, char *agrv[]) {
pid_t pid;
pthread_t tid_one, tid_two;
if ((pid = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
pthread_create(&tid_one, NULL, (void *)thread_one, NULL);
pthread_join(tid_one, NULL);
} else {
pthread_create(&tid_two, NULL, (void *)thread_two, NULL);
pthread_join(tid_two, NULL);
}
wait(NULL);
}
|
the_stack_data/402480.c | /*
* The alarm() function sets a timer
* to deliver the signal SIGALRM to the calling process
* after the specified number of seconds.
* If an alarm has already been set with alarm()
* but has not been delivered,
* another call to alarm() will supersede the prior call.
* The request alarm(0) voids the current alarm
* and the signal SIGALRM will not be delivered.
*/
#include <stdio.h>
#include <unistd.h>
int main() {
int seconds = alarm(5);
printf("seconds = %d\n", seconds); // 0
sleep(2);
seconds = alarm(2); // non-block
printf("seconds = %d\n", seconds); // 3
while (1) {
}
return 0;
}
|
the_stack_data/50137388.c | /*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2.1 of the GNU Lesser General Public License
as published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307,
USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#pragma ident "@(#) libu/clib/sync.c 92.1 07/01/99 13:42:20"
long
SYNC()
{
return((long)sync());
}
|
the_stack_data/115765248.c | #include <stdio.h>
int main(void)
{
printf("Howdy World!\n");
}
|
the_stack_data/107952599.c | // This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
void main()
{
int a;
while (1) {
a = rand() * rand();
if (a == 41){
ERROR: return;
}
}
return;
}
|
the_stack_data/82668.c | /* Copyright 1992-2019 Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Simple little program that just generates a core dump from inside some
nested function calls. */
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#ifndef __STDC__
#define const /**/
#endif
#define MAPSIZE (8 * 1024)
/* Don't make these automatic vars or we will have to walk back up the
stack to access them. */
char *buf1;
char *buf2;
int coremaker_data = 1; /* In Data section */
int coremaker_bss; /* In BSS section */
const int coremaker_ro = 201; /* In Read-Only Data section */
/* Note that if the mapping fails for any reason, we set buf2
to -1 and the testsuite notices this and reports it as
a failure due to a mapping error. This way we don't have
to test for specific errors when running the core maker. */
void
mmapdata ()
{
int j, fd;
/* Allocate and initialize a buffer that will be used to write
the file that is later mapped in. */
buf1 = (char *) malloc (MAPSIZE);
for (j = 0; j < MAPSIZE; ++j)
{
buf1[j] = j;
}
/* Write the file to map in */
fd = open ("coremmap.data", O_CREAT | O_RDWR, 0666);
if (fd == -1)
{
perror ("coremmap.data open failed");
buf2 = (char *) -1;
return;
}
write (fd, buf1, MAPSIZE);
/* Now map the file into our address space as buf2 */
buf2 = (char *) mmap (0, MAPSIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (buf2 == (char *) -1)
{
perror ("mmap failed");
return;
}
/* Verify that the original data and the mapped data are identical.
If not, we'd rather fail now than when trying to access the mapped
data from the core file. */
for (j = 0; j < MAPSIZE; ++j)
{
if (buf1[j] != buf2[j])
{
fprintf (stderr, "mapped data is incorrect");
buf2 = (char *) -1;
return;
}
}
/* Touch buf2 so kernel writes it out into 'core'. */
buf2[0] = buf1[0];
}
void
func2 ()
{
int coremaker_local[5];
int i;
#ifdef SA_FULLDUMP
/* Force a corefile that includes the data section for AIX. */
{
struct sigaction sa;
sigaction (SIGABRT, (struct sigaction *)0, &sa);
sa.sa_flags |= SA_FULLDUMP;
sigaction (SIGABRT, &sa, (struct sigaction *)0);
}
#endif
/* Make sure that coremaker_local doesn't get optimized away. */
for (i = 0; i < 5; i++)
coremaker_local[i] = i;
coremaker_bss = 0;
for (i = 0; i < 5; i++)
coremaker_bss += coremaker_local[i];
coremaker_data = coremaker_ro + 1;
abort ();
}
void
func1 ()
{
func2 ();
}
int
main (int argc, char **argv)
{
if (argc == 2 && strcmp (argv[1], "sleep") == 0)
{
sleep (60);
return 0;
}
mmapdata ();
func1 ();
return 0;
}
|
the_stack_data/92326871.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i,soma = 0;
for (i = 0; i < argc; i++)
soma += atoi(argv[i]);
printf("Soma: %d\n",soma);
return 0;
}
|
the_stack_data/145452526.c | int removeDuplicates(int* nums, int numsSize)
{
int i;
int length;
int times;
length = -1;
times = 2;
for(i = 0;i < numsSize;i++)
{
if(nums[length] != nums[i])
{
nums[++length] = nums[i];
times = 1;
}
else
{
if(times == 0)
{
continue;
}
nums[++length] = nums[i];
times--;
}
}
return length + 1;
} |
the_stack_data/234517454.c | /*
** This file contains all sources (including headers) to the LEMON
** LALR(1) parser generator. The sources have been combined into a
** single file to make it easy to include LEMON in the source tree
** and Makefile of another program.
**
** The author of this program disclaims copyright.
*/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <assert.h>
#define ISSPACE(X) isspace((unsigned char)(X))
#define ISDIGIT(X) isdigit((unsigned char)(X))
#define ISALNUM(X) isalnum((unsigned char)(X))
#define ISALPHA(X) isalpha((unsigned char)(X))
#define ISUPPER(X) isupper((unsigned char)(X))
#define ISLOWER(X) islower((unsigned char)(X))
#ifndef __WIN32__
# if defined(_WIN32) || defined(WIN32)
# define __WIN32__
# endif
#endif
#ifdef __WIN32__
#ifdef __cplusplus
extern "C" {
#endif
extern int access(const char *path, int mode);
#ifdef __cplusplus
}
#endif
#else
#include <unistd.h>
#endif
/* #define PRIVATE static */
#define PRIVATE
#ifdef TEST
#define MAXRHS 5 /* Set low to exercise exception code */
#else
#define MAXRHS 1000
#endif
extern void memory_error();
static int showPrecedenceConflict = 0;
static char *msort(char*,char**,int(*)(const char*,const char*));
/*
** Compilers are getting increasingly pedantic about type conversions
** as C evolves ever closer to Ada.... To work around the latest problems
** we have to define the following variant of strlen().
*/
#define lemonStrlen(X) ((int)strlen(X))
/*
** Compilers are starting to complain about the use of sprintf() and strcpy(),
** saying they are unsafe. So we define our own versions of those routines too.
**
** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
** The third is a helper routine for vsnprintf() that adds texts to the end of a
** buffer, making sure the buffer is always zero-terminated.
**
** The string formatter is a minimal subset of stdlib sprintf() supporting only
** a few simply conversions:
**
** %d
** %s
** %.*s
**
*/
static void lemon_addtext(
char *zBuf, /* The buffer to which text is added */
int *pnUsed, /* Slots of the buffer used so far */
const char *zIn, /* Text to add */
int nIn, /* Bytes of text to add. -1 to use strlen() */
int iWidth /* Field width. Negative to left justify */
){
if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
if( nIn==0 ) return;
memcpy(&zBuf[*pnUsed], zIn, nIn);
*pnUsed += nIn;
while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
zBuf[*pnUsed] = 0;
}
static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
int i, j, k, c;
int nUsed = 0;
const char *z;
char zTemp[50];
str[0] = 0;
for(i=j=0; (c = zFormat[i])!=0; i++){
if( c=='%' ){
int iWidth = 0;
lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
c = zFormat[++i];
if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
if( c=='-' ) i++;
while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
if( c=='-' ) iWidth = -iWidth;
c = zFormat[i];
}
if( c=='d' ){
int v = va_arg(ap, int);
if( v<0 ){
lemon_addtext(str, &nUsed, "-", 1, iWidth);
v = -v;
}else if( v==0 ){
lemon_addtext(str, &nUsed, "0", 1, iWidth);
}
k = 0;
while( v>0 ){
k++;
zTemp[sizeof(zTemp)-k] = (v%10) + '0';
v /= 10;
}
lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
}else if( c=='s' ){
z = va_arg(ap, const char*);
lemon_addtext(str, &nUsed, z, -1, iWidth);
}else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
i += 2;
k = va_arg(ap, int);
z = va_arg(ap, const char*);
lemon_addtext(str, &nUsed, z, k, iWidth);
}else if( c=='%' ){
lemon_addtext(str, &nUsed, "%", 1, 0);
}else{
fprintf(stderr, "illegal format\n");
exit(1);
}
j = i+1;
}
}
lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
return nUsed;
}
static int lemon_sprintf(char *str, const char *format, ...){
va_list ap;
int rc;
va_start(ap, format);
rc = lemon_vsprintf(str, format, ap);
va_end(ap);
return rc;
}
static void lemon_strcpy(char *dest, const char *src){
while( (*(dest++) = *(src++))!=0 ){}
}
static void lemon_strcat(char *dest, const char *src){
while( *dest ) dest++;
lemon_strcpy(dest, src);
}
/* a few forward declarations... */
struct rule;
struct lemon;
struct action;
static struct action *Action_new(void);
static struct action *Action_sort(struct action *);
/********** From the file "build.h" ************************************/
void FindRulePrecedences(struct lemon*);
void FindFirstSets(struct lemon*);
void FindStates(struct lemon*);
void FindLinks(struct lemon*);
void FindFollowSets(struct lemon*);
void FindActions(struct lemon*);
/********* From the file "configlist.h" *********************************/
void Configlist_init(void);
struct config *Configlist_add(struct rule *, int);
struct config *Configlist_addbasis(struct rule *, int);
void Configlist_closure(struct lemon *);
void Configlist_sort(void);
void Configlist_sortbasis(void);
struct config *Configlist_return(void);
struct config *Configlist_basis(void);
void Configlist_eat(struct config *);
void Configlist_reset(void);
/********* From the file "error.h" ***************************************/
void ErrorMsg(const char *, int,const char *, ...);
/****** From the file "option.h" ******************************************/
enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
struct s_options {
enum option_type type;
const char *label;
char *arg;
const char *message;
};
int OptInit(char**,struct s_options*,FILE*);
int OptNArgs(void);
char *OptArg(int);
void OptErr(int);
void OptPrint(void);
/******** From the file "parse.h" *****************************************/
void Parse(struct lemon *lemp);
/********* From the file "plink.h" ***************************************/
struct plink *Plink_new(void);
void Plink_add(struct plink **, struct config *);
void Plink_copy(struct plink **, struct plink *);
void Plink_delete(struct plink *);
/********** From the file "report.h" *************************************/
void Reprint(struct lemon *);
void ReportOutput(struct lemon *);
void ReportTable(struct lemon *, int, int);
void ReportHeader(struct lemon *);
void CompressTables(struct lemon *);
void ResortStates(struct lemon *);
/********** From the file "set.h" ****************************************/
void SetSize(int); /* All sets will be of size N */
char *SetNew(void); /* A new set for element 0..N */
void SetFree(char*); /* Deallocate a set */
int SetAdd(char*,int); /* Add element to a set */
int SetUnion(char *,char *); /* A <- A U B, thru element N */
#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
/********** From the file "struct.h" *************************************/
/*
** Principal data structures for the LEMON parser generator.
*/
typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
/* Symbols (terminals and nonterminals) of the grammar are stored
** in the following: */
enum symbol_type {
TERMINAL,
NONTERMINAL,
MULTITERMINAL
};
enum e_assoc {
LEFT,
RIGHT,
NONE,
UNK
};
struct symbol {
const char *name; /* Name of the symbol */
int index; /* Index number for this symbol */
enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
struct rule *rule; /* Linked list of rules of this (if an NT) */
struct symbol *fallback; /* fallback token in case this token doesn't parse */
int prec; /* Precedence if defined (-1 otherwise) */
enum e_assoc assoc; /* Associativity if precedence is defined */
char *firstset; /* First-set for all rules of this symbol */
Boolean lambda; /* True if NT and can generate an empty string */
int useCnt; /* Number of times used */
char *destructor; /* Code which executes whenever this symbol is
** popped from the stack during error processing */
int destLineno; /* Line number for start of destructor. Set to
** -1 for duplicate destructors. */
char *datatype; /* The data type of information held by this
** object. Only used if type==NONTERMINAL */
int dtnum; /* The data type number. In the parser, the value
** stack is a union. The .yy%d element of this
** union is the correct data type for this object */
int bContent; /* True if this symbol ever carries content - if
** it is ever more than just syntax */
/* The following fields are used by MULTITERMINALs only */
int nsubsym; /* Number of constituent symbols in the MULTI */
struct symbol **subsym; /* Array of constituent symbols */
};
/* Each production rule in the grammar is stored in the following
** structure. */
struct rule {
struct symbol *lhs; /* Left-hand side of the rule */
const char *lhsalias; /* Alias for the LHS (NULL if none) */
int lhsStart; /* True if left-hand side is the start symbol */
int ruleline; /* Line number for the rule */
int nrhs; /* Number of RHS symbols */
struct symbol **rhs; /* The RHS symbols */
const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
int line; /* Line number at which code begins */
const char *code; /* The code executed when this rule is reduced */
const char *codePrefix; /* Setup code before code[] above */
const char *codeSuffix; /* Breakdown code after code[] above */
struct symbol *precsym; /* Precedence symbol for this rule */
int index; /* An index number for this rule */
int iRule; /* Rule number as used in the generated tables */
Boolean noCode; /* True if this rule has no associated C code */
Boolean codeEmitted; /* True if the code has been emitted already */
Boolean canReduce; /* True if this rule is ever reduced */
Boolean doesReduce; /* Reduce actions occur after optimization */
Boolean neverReduce; /* Reduce is theoretically possible, but prevented
** by actions or other outside implementation */
struct rule *nextlhs; /* Next rule with the same LHS */
struct rule *next; /* Next rule in the global list */
};
/* A configuration is a production rule of the grammar together with
** a mark (dot) showing how much of that rule has been processed so far.
** Configurations also contain a follow-set which is a list of terminal
** symbols which are allowed to immediately follow the end of the rule.
** Every configuration is recorded as an instance of the following: */
enum cfgstatus {
COMPLETE,
INCOMPLETE
};
struct config {
struct rule *rp; /* The rule upon which the configuration is based */
int dot; /* The parse point */
char *fws; /* Follow-set for this configuration only */
struct plink *fplp; /* Follow-set forward propagation links */
struct plink *bplp; /* Follow-set backwards propagation links */
struct state *stp; /* Pointer to state which contains this */
enum cfgstatus status; /* used during followset and shift computations */
struct config *next; /* Next configuration in the state */
struct config *bp; /* The next basis configuration */
};
enum e_action {
SHIFT,
ACCEPT,
REDUCE,
ERROR,
SSCONFLICT, /* A shift/shift conflict */
SRCONFLICT, /* Was a reduce, but part of a conflict */
RRCONFLICT, /* Was a reduce, but part of a conflict */
SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
NOT_USED, /* Deleted by compression */
SHIFTREDUCE /* Shift first, then reduce */
};
/* Every shift or reduce operation is stored as one of the following */
struct action {
struct symbol *sp; /* The look-ahead symbol */
enum e_action type;
union {
struct state *stp; /* The new state, if a shift */
struct rule *rp; /* The rule, if a reduce */
} x;
struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
struct action *next; /* Next action for this state */
struct action *collide; /* Next action with the same hash */
};
/* Each state of the generated parser's finite state machine
** is encoded as an instance of the following structure. */
struct state {
struct config *bp; /* The basis configurations for this state */
struct config *cfp; /* All configurations in this set */
int statenum; /* Sequential number for this state */
struct action *ap; /* List of actions for this state */
int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
int iDfltReduce; /* Default action is to REDUCE by this rule */
struct rule *pDfltReduce;/* The default REDUCE rule. */
int autoReduce; /* True if this is an auto-reduce state */
};
#define NO_OFFSET (-2147483647)
/* A followset propagation link indicates that the contents of one
** configuration followset should be propagated to another whenever
** the first changes. */
struct plink {
struct config *cfp; /* The configuration to which linked */
struct plink *next; /* The next propagate link */
};
/* The state vector for the entire parser generator is recorded as
** follows. (LEMON uses no global variables and makes little use of
** static variables. Fields in the following structure can be thought
** of as begin global variables in the program.) */
struct lemon {
struct state **sorted; /* Table of states sorted by state number */
struct rule *rule; /* List of all rules */
struct rule *startRule; /* First rule */
int nstate; /* Number of states */
int nxstate; /* nstate with tail degenerate states removed */
int nrule; /* Number of rules */
int nruleWithAction; /* Number of rules with actions */
int nsymbol; /* Number of terminal and nonterminal symbols */
int nterminal; /* Number of terminal symbols */
int minShiftReduce; /* Minimum shift-reduce action value */
int errAction; /* Error action value */
int accAction; /* Accept action value */
int noAction; /* No-op action value */
int minReduce; /* Minimum reduce action */
int maxAction; /* Maximum action value of any kind */
struct symbol **symbols; /* Sorted array of pointers to symbols */
int errorcnt; /* Number of errors */
struct symbol *errsym; /* The error symbol */
struct symbol *wildcard; /* Token that matches anything */
char *name; /* Name of the generated parser */
char *arg; /* Declaration of the 3rd argument to parser */
char *ctx; /* Declaration of 2nd argument to constructor */
char *tokentype; /* Type of terminal symbols in the parser stack */
char *vartype; /* The default type of non-terminal symbols */
char *start; /* Name of the start symbol for the grammar */
char *stacksize; /* Size of the parser stack */
char *include; /* Code to put at the start of the C file */
char *error; /* Code to execute when an error is seen */
char *overflow; /* Code to execute on a stack overflow */
char *failure; /* Code to execute on parser failure */
char *accept; /* Code to execute when the parser excepts */
char *extracode; /* Code appended to the generated file */
char *tokendest; /* Code to execute to destroy token data */
char *vardest; /* Code for the default non-terminal destructor */
char *filename; /* Name of the input file */
char *outname; /* Name of the current output file */
char *tokenprefix; /* A prefix added to token names in the .h file */
int nconflict; /* Number of parsing conflicts */
int nactiontab; /* Number of entries in the yy_action[] table */
int nlookaheadtab; /* Number of entries in yy_lookahead[] */
int tablesize; /* Total table size of all tables in bytes */
int basisflag; /* Print only basis configurations */
int printPreprocessed; /* Show preprocessor output on stdout */
int has_fallback; /* True if any %fallback is seen in the grammar */
int nolinenosflag; /* True if #line statements should not be printed */
char *argv0; /* Name of the program */
};
#define MemoryCheck(X) if((X)==0){ \
extern void memory_error(); \
memory_error(); \
}
/**************** From the file "table.h" *********************************/
/*
** All code in this file has been automatically generated
** from a specification in the file
** "table.q"
** by the associative array code building program "aagen".
** Do not edit this file! Instead, edit the specification
** file, then rerun aagen.
*/
/*
** Code for processing tables in the LEMON parser generator.
*/
/* Routines for handling a strings */
const char *Strsafe(const char *);
void Strsafe_init(void);
int Strsafe_insert(const char *);
const char *Strsafe_find(const char *);
/* Routines for handling symbols of the grammar */
struct symbol *Symbol_new(const char *);
int Symbolcmpp(const void *, const void *);
void Symbol_init(void);
int Symbol_insert(struct symbol *, const char *);
struct symbol *Symbol_find(const char *);
struct symbol *Symbol_Nth(int);
int Symbol_count(void);
struct symbol **Symbol_arrayof(void);
/* Routines to manage the state table */
int Configcmp(const char *, const char *);
struct state *State_new(void);
void State_init(void);
int State_insert(struct state *, struct config *);
struct state *State_find(struct config *);
struct state **State_arrayof(void);
/* Routines used for efficiency in Configlist_add */
void Configtable_init(void);
int Configtable_insert(struct config *);
struct config *Configtable_find(struct config *);
void Configtable_clear(int(*)(struct config *));
/****************** From the file "action.c" *******************************/
/*
** Routines processing parser actions in the LEMON parser generator.
*/
/* Allocate a new parser action */
static struct action *Action_new(void){
static struct action *actionfreelist = 0;
struct action *newaction;
if( actionfreelist==0 ){
int i;
int amt = 100;
actionfreelist = (struct action *)calloc(amt, sizeof(struct action));
if( actionfreelist==0 ){
fprintf(stderr,"Unable to allocate memory for a new parser action.");
exit(1);
}
for(i=0; i<amt-1; i++) actionfreelist[i].next = &actionfreelist[i+1];
actionfreelist[amt-1].next = 0;
}
newaction = actionfreelist;
actionfreelist = actionfreelist->next;
return newaction;
}
/* Compare two actions for sorting purposes. Return negative, zero, or
** positive if the first action is less than, equal to, or greater than
** the first
*/
static int actioncmp(
struct action *ap1,
struct action *ap2
){
int rc;
rc = ap1->sp->index - ap2->sp->index;
if( rc==0 ){
rc = (int)ap1->type - (int)ap2->type;
}
if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
rc = ap1->x.rp->index - ap2->x.rp->index;
}
if( rc==0 ){
rc = (int) (ap2 - ap1);
}
return rc;
}
/* Sort parser actions */
static struct action *Action_sort(
struct action *ap
){
ap = (struct action *)msort((char *)ap,(char **)&ap->next,
(int(*)(const char*,const char*))actioncmp);
return ap;
}
void Action_add(
struct action **app,
enum e_action type,
struct symbol *sp,
char *arg
){
struct action *newaction;
newaction = Action_new();
newaction->next = *app;
*app = newaction;
newaction->type = type;
newaction->sp = sp;
newaction->spOpt = 0;
if( type==SHIFT ){
newaction->x.stp = (struct state *)arg;
}else{
newaction->x.rp = (struct rule *)arg;
}
}
/********************** New code to implement the "acttab" module ***********/
/*
** This module implements routines use to construct the yy_action[] table.
*/
/*
** The state of the yy_action table under construction is an instance of
** the following structure.
**
** The yy_action table maps the pair (state_number, lookahead) into an
** action_number. The table is an array of integers pairs. The state_number
** determines an initial offset into the yy_action array. The lookahead
** value is then added to this initial offset to get an index X into the
** yy_action array. If the aAction[X].lookahead equals the value of the
** of the lookahead input, then the value of the action_number output is
** aAction[X].action. If the lookaheads do not match then the
** default action for the state_number is returned.
**
** All actions associated with a single state_number are first entered
** into aLookahead[] using multiple calls to acttab_action(). Then the
** actions for that single state_number are placed into the aAction[]
** array with a single call to acttab_insert(). The acttab_insert() call
** also resets the aLookahead[] array in preparation for the next
** state number.
*/
struct lookahead_action {
int lookahead; /* Value of the lookahead token */
int action; /* Action to take on the given lookahead */
};
typedef struct acttab acttab;
struct acttab {
int nAction; /* Number of used slots in aAction[] */
int nActionAlloc; /* Slots allocated for aAction[] */
struct lookahead_action
*aAction, /* The yy_action[] table under construction */
*aLookahead; /* A single new transaction set */
int mnLookahead; /* Minimum aLookahead[].lookahead */
int mnAction; /* Action associated with mnLookahead */
int mxLookahead; /* Maximum aLookahead[].lookahead */
int nLookahead; /* Used slots in aLookahead[] */
int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
int nterminal; /* Number of terminal symbols */
int nsymbol; /* total number of symbols */
};
/* Return the number of entries in the yy_action table */
#define acttab_lookahead_size(X) ((X)->nAction)
/* The value for the N-th entry in yy_action */
#define acttab_yyaction(X,N) ((X)->aAction[N].action)
/* The value for the N-th entry in yy_lookahead */
#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
/* Free all memory associated with the given acttab */
void acttab_free(acttab *p){
free( p->aAction );
free( p->aLookahead );
free( p );
}
/* Allocate a new acttab structure */
acttab *acttab_alloc(int nsymbol, int nterminal){
acttab *p = (acttab *) calloc( 1, sizeof(*p) );
if( p==0 ){
fprintf(stderr,"Unable to allocate memory for a new acttab.");
exit(1);
}
memset(p, 0, sizeof(*p));
p->nsymbol = nsymbol;
p->nterminal = nterminal;
return p;
}
/* Add a new action to the current transaction set.
**
** This routine is called once for each lookahead for a particular
** state.
*/
void acttab_action(acttab *p, int lookahead, int action){
if( p->nLookahead>=p->nLookaheadAlloc ){
p->nLookaheadAlloc += 25;
p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
if( p->aLookahead==0 ){
fprintf(stderr,"malloc failed\n");
exit(1);
}
}
if( p->nLookahead==0 ){
p->mxLookahead = lookahead;
p->mnLookahead = lookahead;
p->mnAction = action;
}else{
if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
if( p->mnLookahead>lookahead ){
p->mnLookahead = lookahead;
p->mnAction = action;
}
}
p->aLookahead[p->nLookahead].lookahead = lookahead;
p->aLookahead[p->nLookahead].action = action;
p->nLookahead++;
}
/*
** Add the transaction set built up with prior calls to acttab_action()
** into the current action table. Then reset the transaction set back
** to an empty set in preparation for a new round of acttab_action() calls.
**
** Return the offset into the action table of the new transaction.
**
** If the makeItSafe parameter is true, then the offset is chosen so that
** it is impossible to overread the yy_lookaside[] table regardless of
** the lookaside token. This is done for the terminal symbols, as they
** come from external inputs and can contain syntax errors. When makeItSafe
** is false, there is more flexibility in selecting offsets, resulting in
** a smaller table. For non-terminal symbols, which are never syntax errors,
** makeItSafe can be false.
*/
int acttab_insert(acttab *p, int makeItSafe){
int i, j, k, n, end;
assert( p->nLookahead>0 );
/* Make sure we have enough space to hold the expanded action table
** in the worst case. The worst case occurs if the transaction set
** must be appended to the current action table
*/
n = p->nsymbol + 1;
if( p->nAction + n >= p->nActionAlloc ){
int oldAlloc = p->nActionAlloc;
p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
p->aAction = (struct lookahead_action *) realloc( p->aAction,
sizeof(p->aAction[0])*p->nActionAlloc);
if( p->aAction==0 ){
fprintf(stderr,"malloc failed\n");
exit(1);
}
for(i=oldAlloc; i<p->nActionAlloc; i++){
p->aAction[i].lookahead = -1;
p->aAction[i].action = -1;
}
}
/* Scan the existing action table looking for an offset that is a
** duplicate of the current transaction set. Fall out of the loop
** if and when the duplicate is found.
**
** i is the index in p->aAction[] where p->mnLookahead is inserted.
*/
end = makeItSafe ? p->mnLookahead : 0;
for(i=p->nAction-1; i>=end; i--){
if( p->aAction[i].lookahead==p->mnLookahead ){
/* All lookaheads and actions in the aLookahead[] transaction
** must match against the candidate aAction[i] entry. */
if( p->aAction[i].action!=p->mnAction ) continue;
for(j=0; j<p->nLookahead; j++){
k = p->aLookahead[j].lookahead - p->mnLookahead + i;
if( k<0 || k>=p->nAction ) break;
if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
if( p->aLookahead[j].action!=p->aAction[k].action ) break;
}
if( j<p->nLookahead ) continue;
/* No possible lookahead value that is not in the aLookahead[]
** transaction is allowed to match aAction[i] */
n = 0;
for(j=0; j<p->nAction; j++){
if( p->aAction[j].lookahead<0 ) continue;
if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
}
if( n==p->nLookahead ){
break; /* An exact match is found at offset i */
}
}
}
/* If no existing offsets exactly match the current transaction, find an
** an empty offset in the aAction[] table in which we can add the
** aLookahead[] transaction.
*/
if( i<end ){
/* Look for holes in the aAction[] table that fit the current
** aLookahead[] transaction. Leave i set to the offset of the hole.
** If no holes are found, i is left at p->nAction, which means the
** transaction will be appended. */
i = makeItSafe ? p->mnLookahead : 0;
for(; i<p->nActionAlloc - p->mxLookahead; i++){
if( p->aAction[i].lookahead<0 ){
for(j=0; j<p->nLookahead; j++){
k = p->aLookahead[j].lookahead - p->mnLookahead + i;
if( k<0 ) break;
if( p->aAction[k].lookahead>=0 ) break;
}
if( j<p->nLookahead ) continue;
for(j=0; j<p->nAction; j++){
if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
}
if( j==p->nAction ){
break; /* Fits in empty slots */
}
}
}
}
/* Insert transaction set at index i. */
#if 0
printf("Acttab:");
for(j=0; j<p->nLookahead; j++){
printf(" %d", p->aLookahead[j].lookahead);
}
printf(" inserted at %d\n", i);
#endif
for(j=0; j<p->nLookahead; j++){
k = p->aLookahead[j].lookahead - p->mnLookahead + i;
p->aAction[k] = p->aLookahead[j];
if( k>=p->nAction ) p->nAction = k+1;
}
if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
p->nLookahead = 0;
/* Return the offset that is added to the lookahead in order to get the
** index into yy_action of the action */
return i - p->mnLookahead;
}
/*
** Return the size of the action table without the trailing syntax error
** entries.
*/
int acttab_action_size(acttab *p){
int n = p->nAction;
while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
return n;
}
/********************** From the file "build.c" *****************************/
/*
** Routines to construction the finite state machine for the LEMON
** parser generator.
*/
/* Find a precedence symbol of every rule in the grammar.
**
** Those rules which have a precedence symbol coded in the input
** grammar using the "[symbol]" construct will already have the
** rp->precsym field filled. Other rules take as their precedence
** symbol the first RHS symbol with a defined precedence. If there
** are not RHS symbols with a defined precedence, the precedence
** symbol field is left blank.
*/
void FindRulePrecedences(struct lemon *xp)
{
struct rule *rp;
for(rp=xp->rule; rp; rp=rp->next){
if( rp->precsym==0 ){
int i, j;
for(i=0; i<rp->nrhs && rp->precsym==0; i++){
struct symbol *sp = rp->rhs[i];
if( sp->type==MULTITERMINAL ){
for(j=0; j<sp->nsubsym; j++){
if( sp->subsym[j]->prec>=0 ){
rp->precsym = sp->subsym[j];
break;
}
}
}else if( sp->prec>=0 ){
rp->precsym = rp->rhs[i];
}
}
}
}
return;
}
/* Find all nonterminals which will generate the empty string.
** Then go back and compute the first sets of every nonterminal.
** The first set is the set of all terminal symbols which can begin
** a string generated by that nonterminal.
*/
void FindFirstSets(struct lemon *lemp)
{
int i, j;
struct rule *rp;
int progress;
for(i=0; i<lemp->nsymbol; i++){
lemp->symbols[i]->lambda = LEMON_FALSE;
}
for(i=lemp->nterminal; i<lemp->nsymbol; i++){
lemp->symbols[i]->firstset = SetNew();
}
/* First compute all lambdas */
do{
progress = 0;
for(rp=lemp->rule; rp; rp=rp->next){
if( rp->lhs->lambda ) continue;
for(i=0; i<rp->nrhs; i++){
struct symbol *sp = rp->rhs[i];
assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
if( sp->lambda==LEMON_FALSE ) break;
}
if( i==rp->nrhs ){
rp->lhs->lambda = LEMON_TRUE;
progress = 1;
}
}
}while( progress );
/* Now compute all first sets */
do{
struct symbol *s1, *s2;
progress = 0;
for(rp=lemp->rule; rp; rp=rp->next){
s1 = rp->lhs;
for(i=0; i<rp->nrhs; i++){
s2 = rp->rhs[i];
if( s2->type==TERMINAL ){
progress += SetAdd(s1->firstset,s2->index);
break;
}else if( s2->type==MULTITERMINAL ){
for(j=0; j<s2->nsubsym; j++){
progress += SetAdd(s1->firstset,s2->subsym[j]->index);
}
break;
}else if( s1==s2 ){
if( s1->lambda==LEMON_FALSE ) break;
}else{
progress += SetUnion(s1->firstset,s2->firstset);
if( s2->lambda==LEMON_FALSE ) break;
}
}
}
}while( progress );
return;
}
/* Compute all LR(0) states for the grammar. Links
** are added to between some states so that the LR(1) follow sets
** can be computed later.
*/
PRIVATE struct state *getstate(struct lemon *); /* forward reference */
void FindStates(struct lemon *lemp)
{
struct symbol *sp;
struct rule *rp;
Configlist_init();
/* Find the start symbol */
if( lemp->start ){
sp = Symbol_find(lemp->start);
if( sp==0 ){
ErrorMsg(lemp->filename,0,
"The specified start symbol \"%s\" is not "
"in a nonterminal of the grammar. \"%s\" will be used as the start "
"symbol instead.",lemp->start,lemp->startRule->lhs->name);
lemp->errorcnt++;
sp = lemp->startRule->lhs;
}
}else{
sp = lemp->startRule->lhs;
}
/* Make sure the start symbol doesn't occur on the right-hand side of
** any rule. Report an error if it does. (YACC would generate a new
** start symbol in this case.) */
for(rp=lemp->rule; rp; rp=rp->next){
int i;
for(i=0; i<rp->nrhs; i++){
if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
ErrorMsg(lemp->filename,0,
"The start symbol \"%s\" occurs on the "
"right-hand side of a rule. This will result in a parser which "
"does not work properly.",sp->name);
lemp->errorcnt++;
}
}
}
/* The basis configuration set for the first state
** is all rules which have the start symbol as their
** left-hand side */
for(rp=sp->rule; rp; rp=rp->nextlhs){
struct config *newcfp;
rp->lhsStart = 1;
newcfp = Configlist_addbasis(rp,0);
SetAdd(newcfp->fws,0);
}
/* Compute the first state. All other states will be
** computed automatically during the computation of the first one.
** The returned pointer to the first state is not used. */
(void)getstate(lemp);
return;
}
/* Return a pointer to a state which is described by the configuration
** list which has been built from calls to Configlist_add.
*/
PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
PRIVATE struct state *getstate(struct lemon *lemp)
{
struct config *cfp, *bp;
struct state *stp;
/* Extract the sorted basis of the new state. The basis was constructed
** by prior calls to "Configlist_addbasis()". */
Configlist_sortbasis();
bp = Configlist_basis();
/* Get a state with the same basis */
stp = State_find(bp);
if( stp ){
/* A state with the same basis already exists! Copy all the follow-set
** propagation links from the state under construction into the
** preexisting state, then return a pointer to the preexisting state */
struct config *x, *y;
for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
Plink_copy(&y->bplp,x->bplp);
Plink_delete(x->fplp);
x->fplp = x->bplp = 0;
}
cfp = Configlist_return();
Configlist_eat(cfp);
}else{
/* This really is a new state. Construct all the details */
Configlist_closure(lemp); /* Compute the configuration closure */
Configlist_sort(); /* Sort the configuration closure */
cfp = Configlist_return(); /* Get a pointer to the config list */
stp = State_new(); /* A new state structure */
MemoryCheck(stp);
stp->bp = bp; /* Remember the configuration basis */
stp->cfp = cfp; /* Remember the configuration closure */
stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
stp->ap = 0; /* No actions, yet. */
State_insert(stp,stp->bp); /* Add to the state table */
buildshifts(lemp,stp); /* Recursively compute successor states */
}
return stp;
}
/*
** Return true if two symbols are the same.
*/
int same_symbol(struct symbol *a, struct symbol *b)
{
int i;
if( a==b ) return 1;
if( a->type!=MULTITERMINAL ) return 0;
if( b->type!=MULTITERMINAL ) return 0;
if( a->nsubsym!=b->nsubsym ) return 0;
for(i=0; i<a->nsubsym; i++){
if( a->subsym[i]!=b->subsym[i] ) return 0;
}
return 1;
}
/* Construct all successor states to the given state. A "successor"
** state is any state which can be reached by a shift action.
*/
PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
{
struct config *cfp; /* For looping thru the config closure of "stp" */
struct config *bcfp; /* For the inner loop on config closure of "stp" */
struct config *newcfg; /* */
struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
struct state *newstp; /* A pointer to a successor state */
/* Each configuration becomes complete after it contributes to a successor
** state. Initially, all configurations are incomplete */
for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
/* Loop through all configurations of the state "stp" */
for(cfp=stp->cfp; cfp; cfp=cfp->next){
if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
Configlist_reset(); /* Reset the new config set */
sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
/* For every configuration in the state "stp" which has the symbol "sp"
** following its dot, add the same configuration to the basis set under
** construction but with the dot shifted one symbol to the right. */
for(bcfp=cfp; bcfp; bcfp=bcfp->next){
if( bcfp->status==COMPLETE ) continue; /* Already used */
if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
bcfp->status = COMPLETE; /* Mark this config as used */
newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
Plink_add(&newcfg->bplp,bcfp);
}
/* Get a pointer to the state described by the basis configuration set
** constructed in the preceding loop */
newstp = getstate(lemp);
/* The state "newstp" is reached from the state "stp" by a shift action
** on the symbol "sp" */
if( sp->type==MULTITERMINAL ){
int i;
for(i=0; i<sp->nsubsym; i++){
Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
}
}else{
Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
}
}
}
/*
** Construct the propagation links
*/
void FindLinks(struct lemon *lemp)
{
int i;
struct config *cfp, *other;
struct state *stp;
struct plink *plp;
/* Housekeeping detail:
** Add to every propagate link a pointer back to the state to
** which the link is attached. */
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
for(cfp=stp->cfp; cfp; cfp=cfp->next){
cfp->stp = stp;
}
}
/* Convert all backlinks into forward links. Only the forward
** links are used in the follow-set computation. */
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
for(cfp=stp->cfp; cfp; cfp=cfp->next){
for(plp=cfp->bplp; plp; plp=plp->next){
other = plp->cfp;
Plink_add(&other->fplp,cfp);
}
}
}
}
/* Compute all followsets.
**
** A followset is the set of all symbols which can come immediately
** after a configuration.
*/
void FindFollowSets(struct lemon *lemp)
{
int i;
struct config *cfp;
struct plink *plp;
int progress;
int change;
for(i=0; i<lemp->nstate; i++){
for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
cfp->status = INCOMPLETE;
}
}
do{
progress = 0;
for(i=0; i<lemp->nstate; i++){
for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
if( cfp->status==COMPLETE ) continue;
for(plp=cfp->fplp; plp; plp=plp->next){
change = SetUnion(plp->cfp->fws,cfp->fws);
if( change ){
plp->cfp->status = INCOMPLETE;
progress = 1;
}
}
cfp->status = COMPLETE;
}
}
}while( progress );
}
static int resolve_conflict(struct action *,struct action *);
/* Compute the reduce actions, and resolve conflicts.
*/
void FindActions(struct lemon *lemp)
{
int i,j;
struct config *cfp;
struct state *stp;
struct symbol *sp;
struct rule *rp;
/* Add all of the reduce actions
** A reduce action is added for each element of the followset of
** a configuration which has its dot at the extreme right.
*/
for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
stp = lemp->sorted[i];
for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
for(j=0; j<lemp->nterminal; j++){
if( SetFind(cfp->fws,j) ){
/* Add a reduce action to the state "stp" which will reduce by the
** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
}
}
}
}
}
/* Add the accepting token */
if( lemp->start ){
sp = Symbol_find(lemp->start);
if( sp==0 ) sp = lemp->startRule->lhs;
}else{
sp = lemp->startRule->lhs;
}
/* Add to the first state (which is always the starting state of the
** finite state machine) an action to ACCEPT if the lookahead is the
** start nonterminal. */
Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
/* Resolve conflicts */
for(i=0; i<lemp->nstate; i++){
struct action *ap, *nap;
stp = lemp->sorted[i];
/* assert( stp->ap ); */
stp->ap = Action_sort(stp->ap);
for(ap=stp->ap; ap && ap->next; ap=ap->next){
for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
/* The two actions "ap" and "nap" have the same lookahead.
** Figure out which one should be used */
lemp->nconflict += resolve_conflict(ap,nap);
}
}
}
/* Report an error for each rule that can never be reduced. */
for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
for(i=0; i<lemp->nstate; i++){
struct action *ap;
for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
}
}
for(rp=lemp->rule; rp; rp=rp->next){
if( rp->canReduce ) continue;
ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
lemp->errorcnt++;
}
}
/* Resolve a conflict between the two given actions. If the
** conflict can't be resolved, return non-zero.
**
** NO LONGER TRUE:
** To resolve a conflict, first look to see if either action
** is on an error rule. In that case, take the action which
** is not associated with the error rule. If neither or both
** actions are associated with an error rule, then try to
** use precedence to resolve the conflict.
**
** If either action is a SHIFT, then it must be apx. This
** function won't work if apx->type==REDUCE and apy->type==SHIFT.
*/
static int resolve_conflict(
struct action *apx,
struct action *apy
){
struct symbol *spx, *spy;
int errcnt = 0;
assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
if( apx->type==SHIFT && apy->type==SHIFT ){
apy->type = SSCONFLICT;
errcnt++;
}
if( apx->type==SHIFT && apy->type==REDUCE ){
spx = apx->sp;
spy = apy->x.rp->precsym;
if( spy==0 || spx->prec<0 || spy->prec<0 ){
/* Not enough precedence information. */
apy->type = SRCONFLICT;
errcnt++;
}else if( spx->prec>spy->prec ){ /* higher precedence wins */
apy->type = RD_RESOLVED;
}else if( spx->prec<spy->prec ){
apx->type = SH_RESOLVED;
}else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
apy->type = RD_RESOLVED; /* associativity */
}else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
apx->type = SH_RESOLVED;
}else{
assert( spx->prec==spy->prec && spx->assoc==NONE );
apx->type = ERROR;
}
}else if( apx->type==REDUCE && apy->type==REDUCE ){
spx = apx->x.rp->precsym;
spy = apy->x.rp->precsym;
if( spx==0 || spy==0 || spx->prec<0 ||
spy->prec<0 || spx->prec==spy->prec ){
apy->type = RRCONFLICT;
errcnt++;
}else if( spx->prec>spy->prec ){
apy->type = RD_RESOLVED;
}else if( spx->prec<spy->prec ){
apx->type = RD_RESOLVED;
}
}else{
assert(
apx->type==SH_RESOLVED ||
apx->type==RD_RESOLVED ||
apx->type==SSCONFLICT ||
apx->type==SRCONFLICT ||
apx->type==RRCONFLICT ||
apy->type==SH_RESOLVED ||
apy->type==RD_RESOLVED ||
apy->type==SSCONFLICT ||
apy->type==SRCONFLICT ||
apy->type==RRCONFLICT
);
/* The REDUCE/SHIFT case cannot happen because SHIFTs come before
** REDUCEs on the list. If we reach this point it must be because
** the parser conflict had already been resolved. */
}
return errcnt;
}
/********************* From the file "configlist.c" *************************/
/*
** Routines to processing a configuration list and building a state
** in the LEMON parser generator.
*/
static struct config *freelist = 0; /* List of free configurations */
static struct config *current = 0; /* Top of list of configurations */
static struct config **currentend = 0; /* Last on list of configs */
static struct config *basis = 0; /* Top of list of basis configs */
static struct config **basisend = 0; /* End of list of basis configs */
/* Return a pointer to a new configuration */
PRIVATE struct config *newconfig(void){
struct config *newcfg;
if( freelist==0 ){
int i;
int amt = 3;
freelist = (struct config *)calloc( amt, sizeof(struct config) );
if( freelist==0 ){
fprintf(stderr,"Unable to allocate memory for a new configuration.");
exit(1);
}
for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
freelist[amt-1].next = 0;
}
newcfg = freelist;
freelist = freelist->next;
return newcfg;
}
/* The configuration "old" is no longer used */
PRIVATE void deleteconfig(struct config *old)
{
old->next = freelist;
freelist = old;
}
/* Initialized the configuration list builder */
void Configlist_init(void){
current = 0;
currentend = ¤t;
basis = 0;
basisend = &basis;
Configtable_init();
return;
}
/* Initialized the configuration list builder */
void Configlist_reset(void){
current = 0;
currentend = ¤t;
basis = 0;
basisend = &basis;
Configtable_clear(0);
return;
}
/* Add another configuration to the configuration list */
struct config *Configlist_add(
struct rule *rp, /* The rule */
int dot /* Index into the RHS of the rule where the dot goes */
){
struct config *cfp, model;
assert( currentend!=0 );
model.rp = rp;
model.dot = dot;
cfp = Configtable_find(&model);
if( cfp==0 ){
cfp = newconfig();
cfp->rp = rp;
cfp->dot = dot;
cfp->fws = SetNew();
cfp->stp = 0;
cfp->fplp = cfp->bplp = 0;
cfp->next = 0;
cfp->bp = 0;
*currentend = cfp;
currentend = &cfp->next;
Configtable_insert(cfp);
}
return cfp;
}
/* Add a basis configuration to the configuration list */
struct config *Configlist_addbasis(struct rule *rp, int dot)
{
struct config *cfp, model;
assert( basisend!=0 );
assert( currentend!=0 );
model.rp = rp;
model.dot = dot;
cfp = Configtable_find(&model);
if( cfp==0 ){
cfp = newconfig();
cfp->rp = rp;
cfp->dot = dot;
cfp->fws = SetNew();
cfp->stp = 0;
cfp->fplp = cfp->bplp = 0;
cfp->next = 0;
cfp->bp = 0;
*currentend = cfp;
currentend = &cfp->next;
*basisend = cfp;
basisend = &cfp->bp;
Configtable_insert(cfp);
}
return cfp;
}
/* Compute the closure of the configuration list */
void Configlist_closure(struct lemon *lemp)
{
struct config *cfp, *newcfp;
struct rule *rp, *newrp;
struct symbol *sp, *xsp;
int i, dot;
assert( currentend!=0 );
for(cfp=current; cfp; cfp=cfp->next){
rp = cfp->rp;
dot = cfp->dot;
if( dot>=rp->nrhs ) continue;
sp = rp->rhs[dot];
if( sp->type==NONTERMINAL ){
if( sp->rule==0 && sp!=lemp->errsym ){
ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
sp->name);
lemp->errorcnt++;
}
for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
newcfp = Configlist_add(newrp,0);
for(i=dot+1; i<rp->nrhs; i++){
xsp = rp->rhs[i];
if( xsp->type==TERMINAL ){
SetAdd(newcfp->fws,xsp->index);
break;
}else if( xsp->type==MULTITERMINAL ){
int k;
for(k=0; k<xsp->nsubsym; k++){
SetAdd(newcfp->fws, xsp->subsym[k]->index);
}
break;
}else{
SetUnion(newcfp->fws,xsp->firstset);
if( xsp->lambda==LEMON_FALSE ) break;
}
}
if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
}
}
}
return;
}
/* Sort the configuration list */
void Configlist_sort(void){
current = (struct config*)msort((char*)current,(char**)&(current->next),
Configcmp);
currentend = 0;
return;
}
/* Sort the basis configuration list */
void Configlist_sortbasis(void){
basis = (struct config*)msort((char*)current,(char**)&(current->bp),
Configcmp);
basisend = 0;
return;
}
/* Return a pointer to the head of the configuration list and
** reset the list */
struct config *Configlist_return(void){
struct config *old;
old = current;
current = 0;
currentend = 0;
return old;
}
/* Return a pointer to the head of the configuration list and
** reset the list */
struct config *Configlist_basis(void){
struct config *old;
old = basis;
basis = 0;
basisend = 0;
return old;
}
/* Free all elements of the given configuration list */
void Configlist_eat(struct config *cfp)
{
struct config *nextcfp;
for(; cfp; cfp=nextcfp){
nextcfp = cfp->next;
assert( cfp->fplp==0 );
assert( cfp->bplp==0 );
if( cfp->fws ) SetFree(cfp->fws);
deleteconfig(cfp);
}
return;
}
/***************** From the file "error.c" *********************************/
/*
** Code for printing error message.
*/
void ErrorMsg(const char *filename, int lineno, const char *format, ...){
va_list ap;
fprintf(stderr, "%s:%d: ", filename, lineno);
va_start(ap, format);
vfprintf(stderr,format,ap);
va_end(ap);
fprintf(stderr, "\n");
}
/**************** From the file "main.c" ************************************/
/*
** Main program file for the LEMON parser generator.
*/
/* Report an out-of-memory condition and abort. This function
** is used mostly by the "MemoryCheck" macro in struct.h
*/
void memory_error(void){
fprintf(stderr,"Out of memory. Aborting...\n");
exit(1);
}
static int nDefine = 0; /* Number of -D options on the command line */
static char **azDefine = 0; /* Name of the -D macros */
/* This routine is called with the argument to each -D command-line option.
** Add the macro defined to the azDefine array.
*/
static void handle_D_option(char *z){
char **paz;
nDefine++;
azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
if( azDefine==0 ){
fprintf(stderr,"out of memory\n");
exit(1);
}
paz = &azDefine[nDefine-1];
*paz = (char *) malloc( lemonStrlen(z)+1 );
if( *paz==0 ){
fprintf(stderr,"out of memory\n");
exit(1);
}
lemon_strcpy(*paz, z);
for(z=*paz; *z && *z!='='; z++){}
*z = 0;
}
/* Rember the name of the output directory
*/
static char *outputDir = NULL;
static void handle_d_option(char *z){
outputDir = (char *) malloc( lemonStrlen(z)+1 );
if( outputDir==0 ){
fprintf(stderr,"out of memory\n");
exit(1);
}
lemon_strcpy(outputDir, z);
}
static char *user_templatename = NULL;
static void handle_T_option(char *z){
user_templatename = (char *) malloc( lemonStrlen(z)+1 );
if( user_templatename==0 ){
memory_error();
}
lemon_strcpy(user_templatename, z);
}
/* Merge together to lists of rules ordered by rule.iRule */
static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
struct rule *pFirst = 0;
struct rule **ppPrev = &pFirst;
while( pA && pB ){
if( pA->iRule<pB->iRule ){
*ppPrev = pA;
ppPrev = &pA->next;
pA = pA->next;
}else{
*ppPrev = pB;
ppPrev = &pB->next;
pB = pB->next;
}
}
if( pA ){
*ppPrev = pA;
}else{
*ppPrev = pB;
}
return pFirst;
}
/*
** Sort a list of rules in order of increasing iRule value
*/
static struct rule *Rule_sort(struct rule *rp){
unsigned int i;
struct rule *pNext;
struct rule *x[32];
memset(x, 0, sizeof(x));
while( rp ){
pNext = rp->next;
rp->next = 0;
for(i=0; i<sizeof(x)/sizeof(x[0])-1 && x[i]; i++){
rp = Rule_merge(x[i], rp);
x[i] = 0;
}
x[i] = rp;
rp = pNext;
}
rp = 0;
for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
rp = Rule_merge(x[i], rp);
}
return rp;
}
/* forward reference */
static const char *minimum_size_type(int lwr, int upr, int *pnByte);
/* Print a single line of the "Parser Stats" output
*/
static void stats_line(const char *zLabel, int iValue){
int nLabel = lemonStrlen(zLabel);
printf(" %s%.*s %5d\n", zLabel,
35-nLabel, "................................",
iValue);
}
/* The main program. Parse the command line and do it... */
int main(int argc, char **argv){
static int version = 0;
static int rpflag = 0;
static int basisflag = 0;
static int compress = 0;
static int quiet = 0;
static int statistics = 0;
static int mhflag = 0;
static int nolinenosflag = 0;
static int noResort = 0;
static int sqlFlag = 0;
static int printPP = 0;
static struct s_options options[] = {
{OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
{OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
{OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
{OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
{OPT_FLAG, "E", (char*)&printPP, "Print input file after preprocessing."},
{OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
{OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
{OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
{OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
{OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
{OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
{OPT_FLAG, "p", (char*)&showPrecedenceConflict,
"Show conflicts resolved by precedence rules"},
{OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
{OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
{OPT_FLAG, "s", (char*)&statistics,
"Print parser stats to standard output."},
{OPT_FLAG, "S", (char*)&sqlFlag,
"Generate the *.sql file describing the parser tables."},
{OPT_FLAG, "x", (char*)&version, "Print the version number."},
{OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
{OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
{OPT_FLAG,0,0,0}
};
int i;
int exitcode;
struct lemon lem;
struct rule *rp;
(void)argc;
OptInit(argv,options,stderr);
if( version ){
printf("Lemon version 1.0\n");
exit(0);
}
if( OptNArgs()!=1 ){
fprintf(stderr,"Exactly one filename argument is required.\n");
exit(1);
}
memset(&lem, 0, sizeof(lem));
lem.errorcnt = 0;
/* Initialize the machine */
Strsafe_init();
Symbol_init();
State_init();
lem.argv0 = argv[0];
lem.filename = OptArg(0);
lem.basisflag = basisflag;
lem.nolinenosflag = nolinenosflag;
lem.printPreprocessed = printPP;
Symbol_new("$");
/* Parse the input file */
Parse(&lem);
if( lem.printPreprocessed || lem.errorcnt ) exit(lem.errorcnt);
if( lem.nrule==0 ){
fprintf(stderr,"Empty grammar.\n");
exit(1);
}
lem.errsym = Symbol_find("error");
/* Count and index the symbols of the grammar */
Symbol_new("{default}");
lem.nsymbol = Symbol_count();
lem.symbols = Symbol_arrayof();
for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
lem.nsymbol = i - 1;
for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
lem.nterminal = i;
/* Assign sequential rule numbers. Start with 0. Put rules that have no
** reduce action C-code associated with them last, so that the switch()
** statement that selects reduction actions will have a smaller jump table.
*/
for(i=0, rp=lem.rule; rp; rp=rp->next){
rp->iRule = rp->code ? i++ : -1;
}
lem.nruleWithAction = i;
for(rp=lem.rule; rp; rp=rp->next){
if( rp->iRule<0 ) rp->iRule = i++;
}
lem.startRule = lem.rule;
lem.rule = Rule_sort(lem.rule);
/* Generate a reprint of the grammar, if requested on the command line */
if( rpflag ){
Reprint(&lem);
}else{
/* Initialize the size for all follow and first sets */
SetSize(lem.nterminal+1);
/* Find the precedence for every production rule (that has one) */
FindRulePrecedences(&lem);
/* Compute the lambda-nonterminals and the first-sets for every
** nonterminal */
FindFirstSets(&lem);
/* Compute all LR(0) states. Also record follow-set propagation
** links so that the follow-set can be computed later */
lem.nstate = 0;
FindStates(&lem);
lem.sorted = State_arrayof();
/* Tie up loose ends on the propagation links */
FindLinks(&lem);
/* Compute the follow set of every reducible configuration */
FindFollowSets(&lem);
/* Compute the action tables */
FindActions(&lem);
/* Compress the action tables */
if( compress==0 ) CompressTables(&lem);
/* Reorder and renumber the states so that states with fewer choices
** occur at the end. This is an optimization that helps make the
** generated parser tables smaller. */
if( noResort==0 ) ResortStates(&lem);
/* Generate a report of the parser generated. (the "y.output" file) */
if( !quiet ) ReportOutput(&lem);
/* Generate the source code for the parser */
ReportTable(&lem, mhflag, sqlFlag);
/* Produce a header file for use by the scanner. (This step is
** omitted if the "-m" option is used because makeheaders will
** generate the file for us.) */
if( !mhflag ) ReportHeader(&lem);
}
if( statistics ){
printf("Parser statistics:\n");
stats_line("terminal symbols", lem.nterminal);
stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
stats_line("total symbols", lem.nsymbol);
stats_line("rules", lem.nrule);
stats_line("states", lem.nxstate);
stats_line("conflicts", lem.nconflict);
stats_line("action table entries", lem.nactiontab);
stats_line("lookahead table entries", lem.nlookaheadtab);
stats_line("total table size (bytes)", lem.tablesize);
}
if( lem.nconflict > 0 ){
fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
}
/* return 0 on success, 1 on failure. */
exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
exit(exitcode);
return (exitcode);
}
/******************** From the file "msort.c" *******************************/
/*
** A generic merge-sort program.
**
** USAGE:
** Let "ptr" be a pointer to some structure which is at the head of
** a null-terminated list. Then to sort the list call:
**
** ptr = msort(ptr,&(ptr->next),cmpfnc);
**
** In the above, "cmpfnc" is a pointer to a function which compares
** two instances of the structure and returns an integer, as in
** strcmp. The second argument is a pointer to the pointer to the
** second element of the linked list. This address is used to compute
** the offset to the "next" field within the structure. The offset to
** the "next" field must be constant for all structures in the list.
**
** The function returns a new pointer which is the head of the list
** after sorting.
**
** ALGORITHM:
** Merge-sort.
*/
/*
** Return a pointer to the next structure in the linked list.
*/
#define NEXT(A) (*(char**)(((char*)A)+offset))
/*
** Inputs:
** a: A sorted, null-terminated linked list. (May be null).
** b: A sorted, null-terminated linked list. (May be null).
** cmp: A pointer to the comparison function.
** offset: Offset in the structure to the "next" field.
**
** Return Value:
** A pointer to the head of a sorted list containing the elements
** of both a and b.
**
** Side effects:
** The "next" pointers for elements in the lists a and b are
** changed.
*/
static char *merge(
char *a,
char *b,
int (*cmp)(const char*,const char*),
int offset
){
char *ptr, *head;
if( a==0 ){
head = b;
}else if( b==0 ){
head = a;
}else{
if( (*cmp)(a,b)<=0 ){
ptr = a;
a = NEXT(a);
}else{
ptr = b;
b = NEXT(b);
}
head = ptr;
while( a && b ){
if( (*cmp)(a,b)<=0 ){
NEXT(ptr) = a;
ptr = a;
a = NEXT(a);
}else{
NEXT(ptr) = b;
ptr = b;
b = NEXT(b);
}
}
if( a ) NEXT(ptr) = a;
else NEXT(ptr) = b;
}
return head;
}
/*
** Inputs:
** list: Pointer to a singly-linked list of structures.
** next: Pointer to pointer to the second element of the list.
** cmp: A comparison function.
**
** Return Value:
** A pointer to the head of a sorted list containing the elements
** originally in list.
**
** Side effects:
** The "next" pointers for elements in list are changed.
*/
#define LISTSIZE 30
static char *msort(
char *list,
char **next,
int (*cmp)(const char*,const char*)
){
unsigned long offset;
char *ep;
char *set[LISTSIZE];
int i;
offset = (unsigned long)((char*)next - (char*)list);
for(i=0; i<LISTSIZE; i++) set[i] = 0;
while( list ){
ep = list;
list = NEXT(list);
NEXT(ep) = 0;
for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
ep = merge(ep,set[i],cmp,offset);
set[i] = 0;
}
set[i] = ep;
}
ep = 0;
for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
return ep;
}
/************************ From the file "option.c" **************************/
static char **g_argv;
static struct s_options *op;
static FILE *errstream;
#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
/*
** Print the command line with a carrot pointing to the k-th character
** of the n-th field.
*/
static void errline(int n, int k, FILE *err)
{
int spcnt, i;
if( g_argv[0] ) fprintf(err,"%s",g_argv[0]);
spcnt = lemonStrlen(g_argv[0]) + 1;
for(i=1; i<n && g_argv[i]; i++){
fprintf(err," %s",g_argv[i]);
spcnt += lemonStrlen(g_argv[i])+1;
}
spcnt += k;
for(; g_argv[i]; i++) fprintf(err," %s",g_argv[i]);
if( spcnt<20 ){
fprintf(err,"\n%*s^-- here\n",spcnt,"");
}else{
fprintf(err,"\n%*shere --^\n",spcnt-7,"");
}
}
/*
** Return the index of the N-th non-switch argument. Return -1
** if N is out of range.
*/
static int argindex(int n)
{
int i;
int dashdash = 0;
if( g_argv!=0 && *g_argv!=0 ){
for(i=1; g_argv[i]; i++){
if( dashdash || !ISOPT(g_argv[i]) ){
if( n==0 ) return i;
n--;
}
if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
}
}
return -1;
}
static char emsg[] = "Command line syntax error: ";
/*
** Process a flag command line argument.
*/
static int handleflags(int i, FILE *err)
{
int v;
int errcnt = 0;
int j;
for(j=0; op[j].label; j++){
if( strncmp(&g_argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
}
v = g_argv[i][0]=='-' ? 1 : 0;
if( op[j].label==0 ){
if( err ){
fprintf(err,"%sundefined option.\n",emsg);
errline(i,1,err);
}
errcnt++;
}else if( op[j].arg==0 ){
/* Ignore this option */
}else if( op[j].type==OPT_FLAG ){
*((int*)op[j].arg) = v;
}else if( op[j].type==OPT_FFLAG ){
(*(void(*)(int))(op[j].arg))(v);
}else if( op[j].type==OPT_FSTR ){
(*(void(*)(char *))(op[j].arg))(&g_argv[i][2]);
}else{
if( err ){
fprintf(err,"%smissing argument on switch.\n",emsg);
errline(i,1,err);
}
errcnt++;
}
return errcnt;
}
/*
** Process a command line switch which has an argument.
*/
static int handleswitch(int i, FILE *err)
{
int lv = 0;
double dv = 0.0;
char *sv = 0, *end;
char *cp;
int j;
int errcnt = 0;
cp = strchr(g_argv[i],'=');
assert( cp!=0 );
*cp = 0;
for(j=0; op[j].label; j++){
if( strcmp(g_argv[i],op[j].label)==0 ) break;
}
*cp = '=';
if( op[j].label==0 ){
if( err ){
fprintf(err,"%sundefined option.\n",emsg);
errline(i,0,err);
}
errcnt++;
}else{
cp++;
switch( op[j].type ){
case OPT_FLAG:
case OPT_FFLAG:
if( err ){
fprintf(err,"%soption requires an argument.\n",emsg);
errline(i,0,err);
}
errcnt++;
break;
case OPT_DBL:
case OPT_FDBL:
dv = strtod(cp,&end);
if( *end ){
if( err ){
fprintf(err,
"%sillegal character in floating-point argument.\n",emsg);
errline(i,(int)((char*)end-(char*)g_argv[i]),err);
}
errcnt++;
}
break;
case OPT_INT:
case OPT_FINT:
lv = strtol(cp,&end,0);
if( *end ){
if( err ){
fprintf(err,"%sillegal character in integer argument.\n",emsg);
errline(i,(int)((char*)end-(char*)g_argv[i]),err);
}
errcnt++;
}
break;
case OPT_STR:
case OPT_FSTR:
sv = cp;
break;
}
switch( op[j].type ){
case OPT_FLAG:
case OPT_FFLAG:
break;
case OPT_DBL:
*(double*)(op[j].arg) = dv;
break;
case OPT_FDBL:
(*(void(*)(double))(op[j].arg))(dv);
break;
case OPT_INT:
*(int*)(op[j].arg) = lv;
break;
case OPT_FINT:
(*(void(*)(int))(op[j].arg))((int)lv);
break;
case OPT_STR:
*(char**)(op[j].arg) = sv;
break;
case OPT_FSTR:
(*(void(*)(char *))(op[j].arg))(sv);
break;
}
}
return errcnt;
}
int OptInit(char **a, struct s_options *o, FILE *err)
{
int errcnt = 0;
g_argv = a;
op = o;
errstream = err;
if( g_argv && *g_argv && op ){
int i;
for(i=1; g_argv[i]; i++){
if( g_argv[i][0]=='+' || g_argv[i][0]=='-' ){
errcnt += handleflags(i,err);
}else if( strchr(g_argv[i],'=') ){
errcnt += handleswitch(i,err);
}
}
}
if( errcnt>0 ){
fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
OptPrint();
exit(1);
}
return 0;
}
int OptNArgs(void){
int cnt = 0;
int dashdash = 0;
int i;
if( g_argv!=0 && g_argv[0]!=0 ){
for(i=1; g_argv[i]; i++){
if( dashdash || !ISOPT(g_argv[i]) ) cnt++;
if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
}
}
return cnt;
}
char *OptArg(int n)
{
int i;
i = argindex(n);
return i>=0 ? g_argv[i] : 0;
}
void OptErr(int n)
{
int i;
i = argindex(n);
if( i>=0 ) errline(i,0,errstream);
}
void OptPrint(void){
int i;
int max, len;
max = 0;
for(i=0; op[i].label; i++){
len = lemonStrlen(op[i].label) + 1;
switch( op[i].type ){
case OPT_FLAG:
case OPT_FFLAG:
break;
case OPT_INT:
case OPT_FINT:
len += 9; /* length of "<integer>" */
break;
case OPT_DBL:
case OPT_FDBL:
len += 6; /* length of "<real>" */
break;
case OPT_STR:
case OPT_FSTR:
len += 8; /* length of "<string>" */
break;
}
if( len>max ) max = len;
}
for(i=0; op[i].label; i++){
switch( op[i].type ){
case OPT_FLAG:
case OPT_FFLAG:
fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
break;
case OPT_INT:
case OPT_FINT:
fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
(int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
break;
case OPT_DBL:
case OPT_FDBL:
fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
(int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
break;
case OPT_STR:
case OPT_FSTR:
fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
(int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
break;
}
}
}
/*********************** From the file "parse.c" ****************************/
/*
** Input file parser for the LEMON parser generator.
*/
/* The state of the parser */
enum e_state {
INITIALIZE,
WAITING_FOR_DECL_OR_RULE,
WAITING_FOR_DECL_KEYWORD,
WAITING_FOR_DECL_ARG,
WAITING_FOR_PRECEDENCE_SYMBOL,
WAITING_FOR_ARROW,
IN_RHS,
LHS_ALIAS_1,
LHS_ALIAS_2,
LHS_ALIAS_3,
RHS_ALIAS_1,
RHS_ALIAS_2,
PRECEDENCE_MARK_1,
PRECEDENCE_MARK_2,
RESYNC_AFTER_RULE_ERROR,
RESYNC_AFTER_DECL_ERROR,
WAITING_FOR_DESTRUCTOR_SYMBOL,
WAITING_FOR_DATATYPE_SYMBOL,
WAITING_FOR_FALLBACK_ID,
WAITING_FOR_WILDCARD_ID,
WAITING_FOR_CLASS_ID,
WAITING_FOR_CLASS_TOKEN,
WAITING_FOR_TOKEN_NAME
};
struct pstate {
char *filename; /* Name of the input file */
int tokenlineno; /* Linenumber at which current token starts */
int errorcnt; /* Number of errors so far */
char *tokenstart; /* Text of current token */
struct lemon *gp; /* Global state vector */
enum e_state state; /* The state of the parser */
struct symbol *fallback; /* The fallback token */
struct symbol *tkclass; /* Token class symbol */
struct symbol *lhs; /* Left-hand side of current rule */
const char *lhsalias; /* Alias for the LHS */
int nrhs; /* Number of right-hand side symbols seen */
struct symbol *rhs[MAXRHS]; /* RHS symbols */
const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
struct rule *prevrule; /* Previous rule parsed */
const char *declkeyword; /* Keyword of a declaration */
char **declargslot; /* Where the declaration argument should be put */
int insertLineMacro; /* Add #line before declaration insert */
int *decllinenoslot; /* Where to write declaration line number */
enum e_assoc declassoc; /* Assign this association to decl arguments */
int preccounter; /* Assign this precedence to decl arguments */
struct rule *firstrule; /* Pointer to first rule in the grammar */
struct rule *lastrule; /* Pointer to the most recently parsed rule */
};
/* Parse a single token */
static void parseonetoken(struct pstate *psp)
{
const char *x;
x = Strsafe(psp->tokenstart); /* Save the token permanently */
#if 0
printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
x,psp->state);
#endif
switch( psp->state ){
case INITIALIZE:
psp->prevrule = 0;
psp->preccounter = 0;
psp->firstrule = psp->lastrule = 0;
psp->gp->nrule = 0;
/* fall through */
case WAITING_FOR_DECL_OR_RULE:
if( x[0]=='%' ){
psp->state = WAITING_FOR_DECL_KEYWORD;
}else if( ISLOWER(x[0]) ){
psp->lhs = Symbol_new(x);
psp->nrhs = 0;
psp->lhsalias = 0;
psp->state = WAITING_FOR_ARROW;
}else if( x[0]=='{' ){
if( psp->prevrule==0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"There is no prior rule upon which to attach the code "
"fragment which begins on this line.");
psp->errorcnt++;
}else if( psp->prevrule->code!=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Code fragment beginning on this line is not the first "
"to follow the previous rule.");
psp->errorcnt++;
}else if( strcmp(x, "{NEVER-REDUCE")==0 ){
psp->prevrule->neverReduce = 1;
}else{
psp->prevrule->line = psp->tokenlineno;
psp->prevrule->code = &x[1];
psp->prevrule->noCode = 0;
}
}else if( x[0]=='[' ){
psp->state = PRECEDENCE_MARK_1;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Token \"%s\" should be either \"%%\" or a nonterminal name.",
x);
psp->errorcnt++;
}
break;
case PRECEDENCE_MARK_1:
if( !ISUPPER(x[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"The precedence symbol must be a terminal.");
psp->errorcnt++;
}else if( psp->prevrule==0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"There is no prior rule to assign precedence \"[%s]\".",x);
psp->errorcnt++;
}else if( psp->prevrule->precsym!=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Precedence mark on this line is not the first "
"to follow the previous rule.");
psp->errorcnt++;
}else{
psp->prevrule->precsym = Symbol_new(x);
}
psp->state = PRECEDENCE_MARK_2;
break;
case PRECEDENCE_MARK_2:
if( x[0]!=']' ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \"]\" on precedence mark.");
psp->errorcnt++;
}
psp->state = WAITING_FOR_DECL_OR_RULE;
break;
case WAITING_FOR_ARROW:
if( x[0]==':' && x[1]==':' && x[2]=='=' ){
psp->state = IN_RHS;
}else if( x[0]=='(' ){
psp->state = LHS_ALIAS_1;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Expected to see a \":\" following the LHS symbol \"%s\".",
psp->lhs->name);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case LHS_ALIAS_1:
if( ISALPHA(x[0]) ){
psp->lhsalias = x;
psp->state = LHS_ALIAS_2;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"\"%s\" is not a valid alias for the LHS \"%s\"\n",
x,psp->lhs->name);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case LHS_ALIAS_2:
if( x[0]==')' ){
psp->state = LHS_ALIAS_3;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case LHS_ALIAS_3:
if( x[0]==':' && x[1]==':' && x[2]=='=' ){
psp->state = IN_RHS;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \"->\" following: \"%s(%s)\".",
psp->lhs->name,psp->lhsalias);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case IN_RHS:
if( x[0]=='.' ){
struct rule *rp;
rp = (struct rule *)calloc( sizeof(struct rule) +
sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
if( rp==0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Can't allocate enough memory for this rule.");
psp->errorcnt++;
psp->prevrule = 0;
}else{
int i;
rp->ruleline = psp->tokenlineno;
rp->rhs = (struct symbol**)&rp[1];
rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
for(i=0; i<psp->nrhs; i++){
rp->rhs[i] = psp->rhs[i];
rp->rhsalias[i] = psp->alias[i];
if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
}
rp->lhs = psp->lhs;
rp->lhsalias = psp->lhsalias;
rp->nrhs = psp->nrhs;
rp->code = 0;
rp->noCode = 1;
rp->precsym = 0;
rp->index = psp->gp->nrule++;
rp->nextlhs = rp->lhs->rule;
rp->lhs->rule = rp;
rp->next = 0;
if( psp->firstrule==0 ){
psp->firstrule = psp->lastrule = rp;
}else{
psp->lastrule->next = rp;
psp->lastrule = rp;
}
psp->prevrule = rp;
}
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( ISALPHA(x[0]) ){
if( psp->nrhs>=MAXRHS ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Too many symbols on RHS of rule beginning at \"%s\".",
x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}else{
psp->rhs[psp->nrhs] = Symbol_new(x);
psp->alias[psp->nrhs] = 0;
psp->nrhs++;
}
}else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 && ISUPPER(x[1]) ){
struct symbol *msp = psp->rhs[psp->nrhs-1];
if( msp->type!=MULTITERMINAL ){
struct symbol *origsp = msp;
msp = (struct symbol *) calloc(1,sizeof(*msp));
memset(msp, 0, sizeof(*msp));
msp->type = MULTITERMINAL;
msp->nsubsym = 1;
msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
msp->subsym[0] = origsp;
msp->name = origsp->name;
psp->rhs[psp->nrhs-1] = msp;
}
msp->nsubsym++;
msp->subsym = (struct symbol **) realloc(msp->subsym,
sizeof(struct symbol*)*msp->nsubsym);
msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Cannot form a compound containing a non-terminal");
psp->errorcnt++;
}
}else if( x[0]=='(' && psp->nrhs>0 ){
psp->state = RHS_ALIAS_1;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Illegal character on RHS of rule: \"%s\".",x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case RHS_ALIAS_1:
if( ISALPHA(x[0]) ){
psp->alias[psp->nrhs-1] = x;
psp->state = RHS_ALIAS_2;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
x,psp->rhs[psp->nrhs-1]->name);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case RHS_ALIAS_2:
if( x[0]==')' ){
psp->state = IN_RHS;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case WAITING_FOR_DECL_KEYWORD:
if( ISALPHA(x[0]) ){
psp->declkeyword = x;
psp->declargslot = 0;
psp->decllinenoslot = 0;
psp->insertLineMacro = 1;
psp->state = WAITING_FOR_DECL_ARG;
if( strcmp(x,"name")==0 ){
psp->declargslot = &(psp->gp->name);
psp->insertLineMacro = 0;
}else if( strcmp(x,"include")==0 ){
psp->declargslot = &(psp->gp->include);
}else if( strcmp(x,"code")==0 ){
psp->declargslot = &(psp->gp->extracode);
}else if( strcmp(x,"token_destructor")==0 ){
psp->declargslot = &psp->gp->tokendest;
}else if( strcmp(x,"default_destructor")==0 ){
psp->declargslot = &psp->gp->vardest;
}else if( strcmp(x,"token_prefix")==0 ){
psp->declargslot = &psp->gp->tokenprefix;
psp->insertLineMacro = 0;
}else if( strcmp(x,"syntax_error")==0 ){
psp->declargslot = &(psp->gp->error);
}else if( strcmp(x,"parse_accept")==0 ){
psp->declargslot = &(psp->gp->accept);
}else if( strcmp(x,"parse_failure")==0 ){
psp->declargslot = &(psp->gp->failure);
}else if( strcmp(x,"stack_overflow")==0 ){
psp->declargslot = &(psp->gp->overflow);
}else if( strcmp(x,"extra_argument")==0 ){
psp->declargslot = &(psp->gp->arg);
psp->insertLineMacro = 0;
}else if( strcmp(x,"extra_context")==0 ){
psp->declargslot = &(psp->gp->ctx);
psp->insertLineMacro = 0;
}else if( strcmp(x,"token_type")==0 ){
psp->declargslot = &(psp->gp->tokentype);
psp->insertLineMacro = 0;
}else if( strcmp(x,"default_type")==0 ){
psp->declargslot = &(psp->gp->vartype);
psp->insertLineMacro = 0;
}else if( strcmp(x,"stack_size")==0 ){
psp->declargslot = &(psp->gp->stacksize);
psp->insertLineMacro = 0;
}else if( strcmp(x,"start_symbol")==0 ){
psp->declargslot = &(psp->gp->start);
psp->insertLineMacro = 0;
}else if( strcmp(x,"left")==0 ){
psp->preccounter++;
psp->declassoc = LEFT;
psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
}else if( strcmp(x,"right")==0 ){
psp->preccounter++;
psp->declassoc = RIGHT;
psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
}else if( strcmp(x,"nonassoc")==0 ){
psp->preccounter++;
psp->declassoc = NONE;
psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
}else if( strcmp(x,"destructor")==0 ){
psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
}else if( strcmp(x,"type")==0 ){
psp->state = WAITING_FOR_DATATYPE_SYMBOL;
}else if( strcmp(x,"fallback")==0 ){
psp->fallback = 0;
psp->state = WAITING_FOR_FALLBACK_ID;
}else if( strcmp(x,"token")==0 ){
psp->state = WAITING_FOR_TOKEN_NAME;
}else if( strcmp(x,"wildcard")==0 ){
psp->state = WAITING_FOR_WILDCARD_ID;
}else if( strcmp(x,"token_class")==0 ){
psp->state = WAITING_FOR_CLASS_ID;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Unknown declaration keyword: \"%%%s\".",x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Illegal declaration keyword: \"%s\".",x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
break;
case WAITING_FOR_DESTRUCTOR_SYMBOL:
if( !ISALPHA(x[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol name missing after %%destructor keyword");
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
struct symbol *sp = Symbol_new(x);
psp->declargslot = &sp->destructor;
psp->decllinenoslot = &sp->destLineno;
psp->insertLineMacro = 1;
psp->state = WAITING_FOR_DECL_ARG;
}
break;
case WAITING_FOR_DATATYPE_SYMBOL:
if( !ISALPHA(x[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol name missing after %%type keyword");
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
struct symbol *sp = Symbol_find(x);
if((sp) && (sp->datatype)){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol %%type \"%s\" already defined", x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
if (!sp){
sp = Symbol_new(x);
}
psp->declargslot = &sp->datatype;
psp->insertLineMacro = 0;
psp->state = WAITING_FOR_DECL_ARG;
}
}
break;
case WAITING_FOR_PRECEDENCE_SYMBOL:
if( x[0]=='.' ){
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( ISUPPER(x[0]) ){
struct symbol *sp;
sp = Symbol_new(x);
if( sp->prec>=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol \"%s\" has already be given a precedence.",x);
psp->errorcnt++;
}else{
sp->prec = psp->preccounter;
sp->assoc = psp->declassoc;
}
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Can't assign a precedence to \"%s\".",x);
psp->errorcnt++;
}
break;
case WAITING_FOR_DECL_ARG:
if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
const char *zOld, *zNew;
char *zBuf, *z;
int nOld, n, nLine = 0, nNew, nBack;
int addLineMacro;
char zLine[50];
zNew = x;
if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
nNew = lemonStrlen(zNew);
if( *psp->declargslot ){
zOld = *psp->declargslot;
}else{
zOld = "";
}
nOld = lemonStrlen(zOld);
n = nOld + nNew + 20;
addLineMacro = !psp->gp->nolinenosflag
&& psp->insertLineMacro
&& psp->tokenlineno>1
&& (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
if( addLineMacro ){
for(z=psp->filename, nBack=0; *z; z++){
if( *z=='\\' ) nBack++;
}
lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
nLine = lemonStrlen(zLine);
n += nLine + lemonStrlen(psp->filename) + nBack;
}
*psp->declargslot = (char *) realloc(*psp->declargslot, n);
zBuf = *psp->declargslot + nOld;
if( addLineMacro ){
if( nOld && zBuf[-1]!='\n' ){
*(zBuf++) = '\n';
}
memcpy(zBuf, zLine, nLine);
zBuf += nLine;
*(zBuf++) = '"';
for(z=psp->filename; *z; z++){
if( *z=='\\' ){
*(zBuf++) = '\\';
}
*(zBuf++) = *z;
}
*(zBuf++) = '"';
*(zBuf++) = '\n';
}
if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
psp->decllinenoslot[0] = psp->tokenlineno;
}
memcpy(zBuf, zNew, nNew);
zBuf += nNew;
*zBuf = 0;
psp->state = WAITING_FOR_DECL_OR_RULE;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Illegal argument to %%%s: %s",psp->declkeyword,x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
break;
case WAITING_FOR_FALLBACK_ID:
if( x[0]=='.' ){
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( !ISUPPER(x[0]) ){
ErrorMsg(psp->filename, psp->tokenlineno,
"%%fallback argument \"%s\" should be a token", x);
psp->errorcnt++;
}else{
struct symbol *sp = Symbol_new(x);
if( psp->fallback==0 ){
psp->fallback = sp;
}else if( sp->fallback ){
ErrorMsg(psp->filename, psp->tokenlineno,
"More than one fallback assigned to token %s", x);
psp->errorcnt++;
}else{
sp->fallback = psp->fallback;
psp->gp->has_fallback = 1;
}
}
break;
case WAITING_FOR_TOKEN_NAME:
/* Tokens do not have to be declared before use. But they can be
** in order to control their assigned integer number. The number for
** each token is assigned when it is first seen. So by including
**
** %token ONE TWO THREE.
**
** early in the grammar file, that assigns small consecutive values
** to each of the tokens ONE TWO and THREE.
*/
if( x[0]=='.' ){
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( !ISUPPER(x[0]) ){
ErrorMsg(psp->filename, psp->tokenlineno,
"%%token argument \"%s\" should be a token", x);
psp->errorcnt++;
}else{
(void)Symbol_new(x);
}
break;
case WAITING_FOR_WILDCARD_ID:
if( x[0]=='.' ){
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( !ISUPPER(x[0]) ){
ErrorMsg(psp->filename, psp->tokenlineno,
"%%wildcard argument \"%s\" should be a token", x);
psp->errorcnt++;
}else{
struct symbol *sp = Symbol_new(x);
if( psp->gp->wildcard==0 ){
psp->gp->wildcard = sp;
}else{
ErrorMsg(psp->filename, psp->tokenlineno,
"Extra wildcard to token: %s", x);
psp->errorcnt++;
}
}
break;
case WAITING_FOR_CLASS_ID:
if( !ISLOWER(x[0]) ){
ErrorMsg(psp->filename, psp->tokenlineno,
"%%token_class must be followed by an identifier: %s", x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else if( Symbol_find(x) ){
ErrorMsg(psp->filename, psp->tokenlineno,
"Symbol \"%s\" already used", x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
psp->tkclass = Symbol_new(x);
psp->tkclass->type = MULTITERMINAL;
psp->state = WAITING_FOR_CLASS_TOKEN;
}
break;
case WAITING_FOR_CLASS_TOKEN:
if( x[0]=='.' ){
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
struct symbol *msp = psp->tkclass;
msp->nsubsym++;
msp->subsym = (struct symbol **) realloc(msp->subsym,
sizeof(struct symbol*)*msp->nsubsym);
if( !ISUPPER(x[0]) ) x++;
msp->subsym[msp->nsubsym-1] = Symbol_new(x);
}else{
ErrorMsg(psp->filename, psp->tokenlineno,
"%%token_class argument \"%s\" should be a token", x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
break;
case RESYNC_AFTER_RULE_ERROR:
/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
** break; */
case RESYNC_AFTER_DECL_ERROR:
if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
break;
}
}
/* The text in the input is part of the argument to an %ifdef or %ifndef.
** Evaluate the text as a boolean expression. Return true or false.
*/
static int eval_preprocessor_boolean(char *z, int lineno){
int neg = 0;
int res = 0;
int okTerm = 1;
int i;
for(i=0; z[i]!=0; i++){
if( ISSPACE(z[i]) ) continue;
if( z[i]=='!' ){
if( !okTerm ) goto pp_syntax_error;
neg = !neg;
continue;
}
if( z[i]=='|' && z[i+1]=='|' ){
if( okTerm ) goto pp_syntax_error;
if( res ) return 1;
i++;
okTerm = 1;
continue;
}
if( z[i]=='&' && z[i+1]=='&' ){
if( okTerm ) goto pp_syntax_error;
if( !res ) return 0;
i++;
okTerm = 1;
continue;
}
if( z[i]=='(' ){
int k;
int n = 1;
if( !okTerm ) goto pp_syntax_error;
for(k=i+1; z[k]; k++){
if( z[k]==')' ){
n--;
if( n==0 ){
z[k] = 0;
res = eval_preprocessor_boolean(&z[i+1], -1);
z[k] = ')';
if( res<0 ){
i = i-res;
goto pp_syntax_error;
}
i = k;
break;
}
}else if( z[k]=='(' ){
n++;
}else if( z[k]==0 ){
i = k;
goto pp_syntax_error;
}
}
if( neg ){
res = !res;
neg = 0;
}
okTerm = 0;
continue;
}
if( ISALPHA(z[i]) ){
int j, k, n;
if( !okTerm ) goto pp_syntax_error;
for(k=i+1; ISALNUM(z[k]) || z[k]=='_'; k++){}
n = k - i;
res = 0;
for(j=0; j<nDefine; j++){
if( strncmp(azDefine[j],&z[i],n)==0 && azDefine[j][n]==0 ){
res = 1;
break;
}
}
i = k-1;
if( neg ){
res = !res;
neg = 0;
}
okTerm = 0;
continue;
}
goto pp_syntax_error;
}
return res;
pp_syntax_error:
if( lineno>0 ){
fprintf(stderr, "%%if syntax error on line %d.\n", lineno);
fprintf(stderr, " %.*s <-- syntax error here\n", i+1, z);
exit(1);
}else{
return -(i+1);
}
}
/* Run the preprocessor over the input file text. The global variables
** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
** comments them out. Text in between is also commented out as appropriate.
*/
static void preprocess_input(char *z){
int i, j, k;
int exclude = 0;
int start = 0;
int lineno = 1;
int start_lineno = 1;
for(i=0; z[i]; i++){
if( z[i]=='\n' ) lineno++;
if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
if( exclude ){
exclude--;
if( exclude==0 ){
for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
}
}
for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
}else if( strncmp(&z[i],"%else",5)==0 && ISSPACE(z[i+5]) ){
if( exclude==1){
exclude = 0;
for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
}else if( exclude==0 ){
exclude = 1;
start = i;
start_lineno = lineno;
}
for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
}else if( strncmp(&z[i],"%ifdef ",7)==0
|| strncmp(&z[i],"%if ",4)==0
|| strncmp(&z[i],"%ifndef ",8)==0 ){
if( exclude ){
exclude++;
}else{
int isNot;
int iBool;
for(j=i; z[j] && !ISSPACE(z[j]); j++){}
iBool = j;
isNot = (j==i+7);
while( z[j] && z[j]!='\n' ){ j++; }
k = z[j];
z[j] = 0;
exclude = eval_preprocessor_boolean(&z[iBool], lineno);
z[j] = k;
if( !isNot ) exclude = !exclude;
if( exclude ){
start = i;
start_lineno = lineno;
}
}
for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
}
}
if( exclude ){
fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
exit(1);
}
}
/* In spite of its name, this function is really a scanner. It read
** in the entire input file (all at once) then tokenizes it. Each
** token is passed to the function "parseonetoken" which builds all
** the appropriate data structures in the global state vector "gp".
*/
void Parse(struct lemon *gp)
{
struct pstate ps;
FILE *fp;
char *filebuf;
unsigned int filesize;
int lineno;
int c;
char *cp, *nextcp;
int startline = 0;
memset(&ps, '\0', sizeof(ps));
ps.gp = gp;
ps.filename = gp->filename;
ps.errorcnt = 0;
ps.state = INITIALIZE;
/* Begin by reading the input file */
fp = fopen(ps.filename,"rb");
if( fp==0 ){
ErrorMsg(ps.filename,0,"Can't open this file for reading.");
gp->errorcnt++;
return;
}
fseek(fp,0,2);
filesize = ftell(fp);
rewind(fp);
filebuf = (char *)malloc( filesize+1 );
if( filesize>100000000 || filebuf==0 ){
ErrorMsg(ps.filename,0,"Input file too large.");
free(filebuf);
gp->errorcnt++;
fclose(fp);
return;
}
if( fread(filebuf,1,filesize,fp)!=filesize ){
ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
filesize);
free(filebuf);
gp->errorcnt++;
fclose(fp);
return;
}
fclose(fp);
filebuf[filesize] = 0;
/* Make an initial pass through the file to handle %ifdef and %ifndef */
preprocess_input(filebuf);
if( gp->printPreprocessed ){
printf("%s\n", filebuf);
return;
}
/* Now scan the text of the input file */
lineno = 1;
for(cp=filebuf; (c= *cp)!=0; ){
if( c=='\n' ) lineno++; /* Keep track of the line number */
if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
cp+=2;
while( (c= *cp)!=0 && c!='\n' ) cp++;
continue;
}
if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
cp+=2;
while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
if( c=='\n' ) lineno++;
cp++;
}
if( c ) cp++;
continue;
}
ps.tokenstart = cp; /* Mark the beginning of the token */
ps.tokenlineno = lineno; /* Linenumber on which token begins */
if( c=='\"' ){ /* String literals */
cp++;
while( (c= *cp)!=0 && c!='\"' ){
if( c=='\n' ) lineno++;
cp++;
}
if( c==0 ){
ErrorMsg(ps.filename,startline,
"String starting on this line is not terminated before "
"the end of the file.");
ps.errorcnt++;
nextcp = cp;
}else{
nextcp = cp+1;
}
}else if( c=='{' ){ /* A block of C code */
int level;
cp++;
for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
if( c=='\n' ) lineno++;
else if( c=='{' ) level++;
else if( c=='}' ) level--;
else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
int prevc;
cp = &cp[2];
prevc = 0;
while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
if( c=='\n' ) lineno++;
prevc = c;
cp++;
}
}else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
cp = &cp[2];
while( (c= *cp)!=0 && c!='\n' ) cp++;
if( c ) lineno++;
}else if( c=='\'' || c=='\"' ){ /* String a character literals */
int startchar, prevc;
startchar = c;
prevc = 0;
for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
if( c=='\n' ) lineno++;
if( prevc=='\\' ) prevc = 0;
else prevc = c;
}
}
}
if( c==0 ){
ErrorMsg(ps.filename,ps.tokenlineno,
"C code starting on this line is not terminated before "
"the end of the file.");
ps.errorcnt++;
nextcp = cp;
}else{
nextcp = cp+1;
}
}else if( ISALNUM(c) ){ /* Identifiers */
while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
nextcp = cp;
}else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
cp += 3;
nextcp = cp;
}else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
cp += 2;
while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
nextcp = cp;
}else{ /* All other (one character) operators */
cp++;
nextcp = cp;
}
c = *cp;
*cp = 0; /* Null terminate the token */
parseonetoken(&ps); /* Parse the token */
*cp = (char)c; /* Restore the buffer */
cp = nextcp;
}
free(filebuf); /* Release the buffer after parsing */
gp->rule = ps.firstrule;
gp->errorcnt = ps.errorcnt;
}
/*************************** From the file "plink.c" *********************/
/*
** Routines processing configuration follow-set propagation links
** in the LEMON parser generator.
*/
static struct plink *plink_freelist = 0;
/* Allocate a new plink */
struct plink *Plink_new(void){
struct plink *newlink;
if( plink_freelist==0 ){
int i;
int amt = 100;
plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
if( plink_freelist==0 ){
fprintf(stderr,
"Unable to allocate memory for a new follow-set propagation link.\n");
exit(1);
}
for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
plink_freelist[amt-1].next = 0;
}
newlink = plink_freelist;
plink_freelist = plink_freelist->next;
return newlink;
}
/* Add a plink to a plink list */
void Plink_add(struct plink **plpp, struct config *cfp)
{
struct plink *newlink;
newlink = Plink_new();
newlink->next = *plpp;
*plpp = newlink;
newlink->cfp = cfp;
}
/* Transfer every plink on the list "from" to the list "to" */
void Plink_copy(struct plink **to, struct plink *from)
{
struct plink *nextpl;
while( from ){
nextpl = from->next;
from->next = *to;
*to = from;
from = nextpl;
}
}
/* Delete every plink on the list */
void Plink_delete(struct plink *plp)
{
struct plink *nextpl;
while( plp ){
nextpl = plp->next;
plp->next = plink_freelist;
plink_freelist = plp;
plp = nextpl;
}
}
/*********************** From the file "report.c" **************************/
/*
** Procedures for generating reports and tables in the LEMON parser generator.
*/
/* Generate a filename with the given suffix. Space to hold the
** name comes from malloc() and must be freed by the calling
** function.
*/
PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
{
char *name;
char *cp;
char *filename = lemp->filename;
int sz;
if( outputDir ){
cp = strrchr(filename, '/');
if( cp ) filename = cp + 1;
}
sz = lemonStrlen(filename);
sz += lemonStrlen(suffix);
if( outputDir ) sz += lemonStrlen(outputDir) + 1;
sz += 5;
name = (char*)malloc( sz );
if( name==0 ){
fprintf(stderr,"Can't allocate space for a filename.\n");
exit(1);
}
name[0] = 0;
if( outputDir ){
lemon_strcpy(name, outputDir);
lemon_strcat(name, "/");
}
lemon_strcat(name,filename);
cp = strrchr(name,'.');
if( cp ) *cp = 0;
lemon_strcat(name,suffix);
return name;
}
/* Open a file with a name based on the name of the input file,
** but with a different (specified) suffix, and return a pointer
** to the stream */
PRIVATE FILE *file_open(
struct lemon *lemp,
const char *suffix,
const char *mode
){
FILE *fp;
if( lemp->outname ) free(lemp->outname);
lemp->outname = file_makename(lemp, suffix);
fp = fopen(lemp->outname,mode);
if( fp==0 && *mode=='w' ){
fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
lemp->errorcnt++;
return 0;
}
return fp;
}
/* Print the text of a rule
*/
void rule_print(FILE *out, struct rule *rp){
int i, j;
fprintf(out, "%s",rp->lhs->name);
/* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
fprintf(out," ::=");
for(i=0; i<rp->nrhs; i++){
struct symbol *sp = rp->rhs[i];
if( sp->type==MULTITERMINAL ){
fprintf(out," %s", sp->subsym[0]->name);
for(j=1; j<sp->nsubsym; j++){
fprintf(out,"|%s", sp->subsym[j]->name);
}
}else{
fprintf(out," %s", sp->name);
}
/* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
}
}
/* Duplicate the input file without comments and without actions
** on rules */
void Reprint(struct lemon *lemp)
{
struct rule *rp;
struct symbol *sp;
int i, j, maxlen, len, ncolumns, skip;
printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
maxlen = 10;
for(i=0; i<lemp->nsymbol; i++){
sp = lemp->symbols[i];
len = lemonStrlen(sp->name);
if( len>maxlen ) maxlen = len;
}
ncolumns = 76/(maxlen+5);
if( ncolumns<1 ) ncolumns = 1;
skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
for(i=0; i<skip; i++){
printf("//");
for(j=i; j<lemp->nsymbol; j+=skip){
sp = lemp->symbols[j];
assert( sp->index==j );
printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
}
printf("\n");
}
for(rp=lemp->rule; rp; rp=rp->next){
rule_print(stdout, rp);
printf(".");
if( rp->precsym ) printf(" [%s]",rp->precsym->name);
/* if( rp->code ) printf("\n %s",rp->code); */
printf("\n");
}
}
/* Print a single rule.
*/
void RulePrint(FILE *fp, struct rule *rp, int iCursor){
struct symbol *sp;
int i, j;
fprintf(fp,"%s ::=",rp->lhs->name);
for(i=0; i<=rp->nrhs; i++){
if( i==iCursor ) fprintf(fp," *");
if( i==rp->nrhs ) break;
sp = rp->rhs[i];
if( sp->type==MULTITERMINAL ){
fprintf(fp," %s", sp->subsym[0]->name);
for(j=1; j<sp->nsubsym; j++){
fprintf(fp,"|%s",sp->subsym[j]->name);
}
}else{
fprintf(fp," %s", sp->name);
}
}
}
/* Print the rule for a configuration.
*/
void ConfigPrint(FILE *fp, struct config *cfp){
RulePrint(fp, cfp->rp, cfp->dot);
}
/* #define TEST */
#if 0
/* Print a set */
PRIVATE void SetPrint(out,set,lemp)
FILE *out;
char *set;
struct lemon *lemp;
{
int i;
char *spacer;
spacer = "";
fprintf(out,"%12s[","");
for(i=0; i<lemp->nterminal; i++){
if( SetFind(set,i) ){
fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
spacer = " ";
}
}
fprintf(out,"]\n");
}
/* Print a plink chain */
PRIVATE void PlinkPrint(out,plp,tag)
FILE *out;
struct plink *plp;
char *tag;
{
while( plp ){
fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
ConfigPrint(out,plp->cfp);
fprintf(out,"\n");
plp = plp->next;
}
}
#endif
/* Print an action to the given file descriptor. Return FALSE if
** nothing was actually printed.
*/
int PrintAction(
struct action *ap, /* The action to print */
FILE *fp, /* Print the action here */
int indent /* Indent by this amount */
){
int result = 1;
switch( ap->type ){
case SHIFT: {
struct state *stp = ap->x.stp;
fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
break;
}
case REDUCE: {
struct rule *rp = ap->x.rp;
fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
RulePrint(fp, rp, -1);
break;
}
case SHIFTREDUCE: {
struct rule *rp = ap->x.rp;
fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
RulePrint(fp, rp, -1);
break;
}
case ACCEPT:
fprintf(fp,"%*s accept",indent,ap->sp->name);
break;
case ERROR:
fprintf(fp,"%*s error",indent,ap->sp->name);
break;
case SRCONFLICT:
case RRCONFLICT:
fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
indent,ap->sp->name,ap->x.rp->iRule);
break;
case SSCONFLICT:
fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
indent,ap->sp->name,ap->x.stp->statenum);
break;
case SH_RESOLVED:
if( showPrecedenceConflict ){
fprintf(fp,"%*s shift %-7d -- dropped by precedence",
indent,ap->sp->name,ap->x.stp->statenum);
}else{
result = 0;
}
break;
case RD_RESOLVED:
if( showPrecedenceConflict ){
fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
indent,ap->sp->name,ap->x.rp->iRule);
}else{
result = 0;
}
break;
case NOT_USED:
result = 0;
break;
}
if( result && ap->spOpt ){
fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
}
return result;
}
/* Generate the "*.out" log file */
void ReportOutput(struct lemon *lemp)
{
int i, n;
struct state *stp;
struct config *cfp;
struct action *ap;
struct rule *rp;
FILE *fp;
fp = file_open(lemp,".out","wb");
if( fp==0 ) return;
for(i=0; i<lemp->nxstate; i++){
stp = lemp->sorted[i];
fprintf(fp,"State %d:\n",stp->statenum);
if( lemp->basisflag ) cfp=stp->bp;
else cfp=stp->cfp;
while( cfp ){
char buf[20];
if( cfp->dot==cfp->rp->nrhs ){
lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
fprintf(fp," %5s ",buf);
}else{
fprintf(fp," ");
}
ConfigPrint(fp,cfp);
fprintf(fp,"\n");
#if 0
SetPrint(fp,cfp->fws,lemp);
PlinkPrint(fp,cfp->fplp,"To ");
PlinkPrint(fp,cfp->bplp,"From");
#endif
if( lemp->basisflag ) cfp=cfp->bp;
else cfp=cfp->next;
}
fprintf(fp,"\n");
for(ap=stp->ap; ap; ap=ap->next){
if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
}
fprintf(fp,"\n");
}
fprintf(fp, "----------------------------------------------------\n");
fprintf(fp, "Symbols:\n");
fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
for(i=0; i<lemp->nsymbol; i++){
int j;
struct symbol *sp;
sp = lemp->symbols[i];
fprintf(fp, " %3d: %s", i, sp->name);
if( sp->type==NONTERMINAL ){
fprintf(fp, ":");
if( sp->lambda ){
fprintf(fp, " <lambda>");
}
for(j=0; j<lemp->nterminal; j++){
if( sp->firstset && SetFind(sp->firstset, j) ){
fprintf(fp, " %s", lemp->symbols[j]->name);
}
}
}
if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
fprintf(fp, "\n");
}
fprintf(fp, "----------------------------------------------------\n");
fprintf(fp, "Syntax-only Symbols:\n");
fprintf(fp, "The following symbols never carry semantic content.\n\n");
for(i=n=0; i<lemp->nsymbol; i++){
int w;
struct symbol *sp = lemp->symbols[i];
if( sp->bContent ) continue;
w = (int)strlen(sp->name);
if( n>0 && n+w>75 ){
fprintf(fp,"\n");
n = 0;
}
if( n>0 ){
fprintf(fp, " ");
n++;
}
fprintf(fp, "%s", sp->name);
n += w;
}
if( n>0 ) fprintf(fp, "\n");
fprintf(fp, "----------------------------------------------------\n");
fprintf(fp, "Rules:\n");
for(rp=lemp->rule; rp; rp=rp->next){
fprintf(fp, "%4d: ", rp->iRule);
rule_print(fp, rp);
fprintf(fp,".");
if( rp->precsym ){
fprintf(fp," [%s precedence=%d]",
rp->precsym->name, rp->precsym->prec);
}
fprintf(fp,"\n");
}
fclose(fp);
return;
}
/* Search for the file "name" which is in the same directory as
** the executable */
PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
{
const char *pathlist;
char *pathbufptr = 0;
char *pathbuf = 0;
char *path,*cp;
char c;
#ifdef __WIN32__
cp = strrchr(argv0,'\\');
#else
cp = strrchr(argv0,'/');
#endif
if( cp ){
c = *cp;
*cp = 0;
path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
*cp = c;
}else{
pathlist = getenv("PATH");
if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
if( (pathbuf != 0) && (path!=0) ){
pathbufptr = pathbuf;
lemon_strcpy(pathbuf, pathlist);
while( *pathbuf ){
cp = strchr(pathbuf,':');
if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
c = *cp;
*cp = 0;
lemon_sprintf(path,"%s/%s",pathbuf,name);
*cp = c;
if( c==0 ) pathbuf[0] = 0;
else pathbuf = &cp[1];
if( access(path,modemask)==0 ) break;
}
}
free(pathbufptr);
}
return path;
}
/* Given an action, compute the integer value for that action
** which is to be put in the action table of the generated machine.
** Return negative if no action should be generated.
*/
PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
{
int act;
switch( ap->type ){
case SHIFT: act = ap->x.stp->statenum; break;
case SHIFTREDUCE: {
/* Since a SHIFT is inherient after a prior REDUCE, convert any
** SHIFTREDUCE action with a nonterminal on the LHS into a simple
** REDUCE action: */
if( ap->sp->index>=lemp->nterminal && ( !lemp->errsym || ap->sp->index!=lemp->errsym->index )){
act = lemp->minReduce + ap->x.rp->iRule;
}else{
act = lemp->minShiftReduce + ap->x.rp->iRule;
}
break;
}
case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
case ERROR: act = lemp->errAction; break;
case ACCEPT: act = lemp->accAction; break;
default: act = -1; break;
}
return act;
}
#define LINESIZE 1000
/* The next cluster of routines are for reading the template file
** and writing the results to the generated parser */
/* The first function transfers data from "in" to "out" until
** a line is seen which begins with "%%". The line number is
** tracked.
**
** if name!=0, then any word that begin with "Parse" is changed to
** begin with *name instead.
*/
PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
{
int i, iStart;
char line[LINESIZE];
while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
(*lineno)++;
iStart = 0;
if( name ){
for(i=0; line[i]; i++){
if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
&& (i==0 || !ISALPHA(line[i-1]))
){
if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
fprintf(out,"%s",name);
i += 4;
iStart = i+1;
}
}
}
fprintf(out,"%s",&line[iStart]);
}
}
/* Skip forward past the header of the template file to the first "%%"
*/
PRIVATE void tplt_skip_header(FILE *in, int *lineno)
{
char line[LINESIZE];
while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
(*lineno)++;
}
}
/* The next function finds the template file and opens it, returning
** a pointer to the opened file. */
PRIVATE FILE *tplt_open(struct lemon *lemp)
{
static char templatename[] = "lempar.c";
char buf[1000];
FILE *in;
char *tpltname;
char *toFree = 0;
char *cp;
/* first, see if user specified a template filename on the command line. */
if (user_templatename != 0) {
if( access(user_templatename,004)==-1 ){
fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
user_templatename);
lemp->errorcnt++;
return 0;
}
in = fopen(user_templatename,"rb");
if( in==0 ){
fprintf(stderr,"Can't open the template file \"%s\".\n",
user_templatename);
lemp->errorcnt++;
return 0;
}
return in;
}
cp = strrchr(lemp->filename,'.');
if( cp ){
lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
}else{
lemon_sprintf(buf,"%s.lt",lemp->filename);
}
if( access(buf,004)==0 ){
tpltname = buf;
}else if( access(templatename,004)==0 ){
tpltname = templatename;
}else{
toFree = tpltname = pathsearch(lemp->argv0,templatename,0);
}
if( tpltname==0 ){
fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
templatename);
lemp->errorcnt++;
return 0;
}
in = fopen(tpltname,"rb");
if( in==0 ){
fprintf(stderr,"Can't open the template file \"%s\".\n",tpltname);
lemp->errorcnt++;
}
free(toFree);
return in;
}
/* Print a #line directive line to the output file. */
PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
{
fprintf(out,"#line %d \"",lineno);
while( *filename ){
if( *filename == '\\' ) putc('\\',out);
putc(*filename,out);
filename++;
}
fprintf(out,"\"\n");
}
/* Print a string to the file and keep the linenumber up to date */
PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
{
if( str==0 ) return;
while( *str ){
putc(*str,out);
if( *str=='\n' ) (*lineno)++;
str++;
}
if( str[-1]!='\n' ){
putc('\n',out);
(*lineno)++;
}
if (!lemp->nolinenosflag) {
(*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
}
return;
}
/*
** The following routine emits code for the destructor for the
** symbol sp
*/
void emit_destructor_code(
FILE *out,
struct symbol *sp,
struct lemon *lemp,
int *lineno
){
char *cp = 0;
if( sp->type==TERMINAL ){
cp = lemp->tokendest;
if( cp==0 ) return;
fprintf(out,"{\n"); (*lineno)++;
}else if( sp->destructor ){
cp = sp->destructor;
fprintf(out,"{\n"); (*lineno)++;
if( !lemp->nolinenosflag ){
(*lineno)++;
tplt_linedir(out,sp->destLineno,lemp->filename);
}
}else if( lemp->vardest ){
cp = lemp->vardest;
if( cp==0 ) return;
fprintf(out,"{\n"); (*lineno)++;
}else{
assert( 0 ); /* Cannot happen */
}
for(; *cp; cp++){
if( *cp=='$' && cp[1]=='$' ){
fprintf(out,"(yypminor->yy%d)",sp->dtnum);
cp++;
continue;
}
if( *cp=='\n' ) (*lineno)++;
fputc(*cp,out);
}
fprintf(out,"\n"); (*lineno)++;
if (!lemp->nolinenosflag) {
(*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
}
fprintf(out,"}\n"); (*lineno)++;
return;
}
/*
** Return TRUE (non-zero) if the given symbol has a destructor.
*/
int has_destructor(struct symbol *sp, struct lemon *lemp)
{
int ret;
if( sp->type==TERMINAL ){
ret = lemp->tokendest!=0;
}else{
ret = lemp->vardest!=0 || sp->destructor!=0;
}
return ret;
}
/*
** Append text to a dynamically allocated string. If zText is 0 then
** reset the string to be empty again. Always return the complete text
** of the string (which is overwritten with each call).
**
** n bytes of zText are stored. If n==0 then all of zText up to the first
** \000 terminator is stored. zText can contain up to two instances of
** %d. The values of p1 and p2 are written into the first and second
** %d.
**
** If n==-1, then the previous character is overwritten.
*/
PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
static char empty[1] = { 0 };
static char *z = 0;
static int alloced = 0;
static int used = 0;
int c;
char zInt[40];
if( zText==0 ){
if( used==0 && z!=0 ) z[0] = 0;
used = 0;
return z;
}
if( n<=0 ){
if( n<0 ){
used += n;
assert( used>=0 );
}
n = lemonStrlen(zText);
}
if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
alloced = n + sizeof(zInt)*2 + used + 200;
z = (char *) realloc(z, alloced);
}
if( z==0 ) return empty;
while( n-- > 0 ){
c = *(zText++);
if( c=='%' && n>0 && zText[0]=='d' ){
lemon_sprintf(zInt, "%d", p1);
p1 = p2;
lemon_strcpy(&z[used], zInt);
used += lemonStrlen(&z[used]);
zText++;
n--;
}else{
z[used++] = (char)c;
}
}
z[used] = 0;
return z;
}
/*
** Write and transform the rp->code string so that symbols are expanded.
** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
**
** Return 1 if the expanded code requires that "yylhsminor" local variable
** to be defined.
*/
PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
char *cp, *xp;
int i;
int rc = 0; /* True if yylhsminor is used */
int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
char lhsused = 0; /* True if the LHS element has been used */
char lhsdirect; /* True if LHS writes directly into stack */
char used[MAXRHS]; /* True for each RHS element which is used */
char zLhs[50]; /* Convert the LHS symbol into this string */
char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
for(i=0; i<rp->nrhs; i++) used[i] = 0;
lhsused = 0;
if( rp->code==0 ){
static char newlinestr[2] = { '\n', '\0' };
rp->code = newlinestr;
rp->line = rp->ruleline;
rp->noCode = 1;
}else{
rp->noCode = 0;
}
if( rp->nrhs==0 ){
/* If there are no RHS symbols, then writing directly to the LHS is ok */
lhsdirect = 1;
}else if( rp->rhsalias[0]==0 ){
/* The left-most RHS symbol has no value. LHS direct is ok. But
** we have to call the destructor on the RHS symbol first. */
lhsdirect = 1;
if( has_destructor(rp->rhs[0],lemp) ){
append_str(0,0,0,0);
append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
rp->rhs[0]->index,1-rp->nrhs);
rp->codePrefix = Strsafe(append_str(0,0,0,0));
rp->noCode = 0;
}
}else if( rp->lhsalias==0 ){
/* There is no LHS value symbol. */
lhsdirect = 1;
}else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
/* The LHS symbol and the left-most RHS symbol are the same, so
** direct writing is allowed */
lhsdirect = 1;
lhsused = 1;
used[0] = 1;
if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
ErrorMsg(lemp->filename,rp->ruleline,
"%s(%s) and %s(%s) share the same label but have "
"different datatypes.",
rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
lemp->errorcnt++;
}
}else{
lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
rp->lhsalias, rp->rhsalias[0]);
zSkip = strstr(rp->code, zOvwrt);
if( zSkip!=0 ){
/* The code contains a special comment that indicates that it is safe
** for the LHS label to overwrite left-most RHS label. */
lhsdirect = 1;
}else{
lhsdirect = 0;
}
}
if( lhsdirect ){
sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
}else{
rc = 1;
sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
}
append_str(0,0,0,0);
/* This const cast is wrong but harmless, if we're careful. */
for(cp=(char *)rp->code; *cp; cp++){
if( cp==zSkip ){
append_str(zOvwrt,0,0,0);
cp += lemonStrlen(zOvwrt)-1;
dontUseRhs0 = 1;
continue;
}
if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
char saved;
for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
saved = *xp;
*xp = 0;
if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
append_str(zLhs,0,0,0);
cp = xp;
lhsused = 1;
}else{
for(i=0; i<rp->nrhs; i++){
if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
if( i==0 && dontUseRhs0 ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label %s used after '%s'.",
rp->rhsalias[0], zOvwrt);
lemp->errorcnt++;
}else if( cp!=rp->code && cp[-1]=='@' ){
/* If the argument is of the form @X then substituted
** the token number of X, not the value of X */
append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
}else{
struct symbol *sp = rp->rhs[i];
int dtnum;
if( sp->type==MULTITERMINAL ){
dtnum = sp->subsym[0]->dtnum;
}else{
dtnum = sp->dtnum;
}
append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
}
cp = xp;
used[i] = 1;
break;
}
}
}
*xp = saved;
}
append_str(cp, 1, 0, 0);
} /* End loop */
/* Main code generation completed */
cp = append_str(0,0,0,0);
if( cp && cp[0] ) rp->code = Strsafe(cp);
append_str(0,0,0,0);
/* Check to make sure the LHS has been used */
if( rp->lhsalias && !lhsused ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label \"%s\" for \"%s(%s)\" is never used.",
rp->lhsalias,rp->lhs->name,rp->lhsalias);
lemp->errorcnt++;
}
/* Generate destructor code for RHS minor values which are not referenced.
** Generate error messages for unused labels and duplicate labels.
*/
for(i=0; i<rp->nrhs; i++){
if( rp->rhsalias[i] ){
if( i>0 ){
int j;
if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
ErrorMsg(lemp->filename,rp->ruleline,
"%s(%s) has the same label as the LHS but is not the left-most "
"symbol on the RHS.",
rp->rhs[i]->name, rp->rhsalias[i]);
lemp->errorcnt++;
}
for(j=0; j<i; j++){
if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label %s used for multiple symbols on the RHS of a rule.",
rp->rhsalias[i]);
lemp->errorcnt++;
break;
}
}
}
if( !used[i] ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label %s for \"%s(%s)\" is never used.",
rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
lemp->errorcnt++;
}
}else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
rp->rhs[i]->index,i-rp->nrhs+1);
}
}
/* If unable to write LHS values directly into the stack, write the
** saved LHS value now. */
if( lhsdirect==0 ){
append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
append_str(zLhs, 0, 0, 0);
append_str(";\n", 0, 0, 0);
}
/* Suffix code generation complete */
cp = append_str(0,0,0,0);
if( cp && cp[0] ){
rp->codeSuffix = Strsafe(cp);
rp->noCode = 0;
}
return rc;
}
/*
** Generate code which executes when the rule "rp" is reduced. Write
** the code to "out". Make sure lineno stays up-to-date.
*/
PRIVATE void emit_code(
FILE *out,
struct rule *rp,
struct lemon *lemp,
int *lineno
){
const char *cp;
/* Setup code prior to the #line directive */
if( rp->codePrefix && rp->codePrefix[0] ){
fprintf(out, "{%s", rp->codePrefix);
for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
}
/* Generate code to do the reduce action */
if( rp->code ){
if( !lemp->nolinenosflag ){
(*lineno)++;
tplt_linedir(out,rp->line,lemp->filename);
}
fprintf(out,"{%s",rp->code);
for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
fprintf(out,"}\n"); (*lineno)++;
if( !lemp->nolinenosflag ){
(*lineno)++;
tplt_linedir(out,*lineno,lemp->outname);
}
}
/* Generate breakdown code that occurs after the #line directive */
if( rp->codeSuffix && rp->codeSuffix[0] ){
fprintf(out, "%s", rp->codeSuffix);
for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
}
if( rp->codePrefix ){
fprintf(out, "}\n"); (*lineno)++;
}
return;
}
/*
** Print the definition of the union used for the parser's data stack.
** This union contains fields for every possible data type for tokens
** and nonterminals. In the process of computing and printing this
** union, also set the ".dtnum" field of every terminal and nonterminal
** symbol.
*/
void print_stack_union(
FILE *out, /* The output stream */
struct lemon *lemp, /* The main info structure for this parser */
int *plineno, /* Pointer to the line number */
int mhflag /* True if generating makeheaders output */
){
int lineno = *plineno; /* The line number of the output */
char **types; /* A hash table of datatypes */
int arraysize; /* Size of the "types" array */
int maxdtlength; /* Maximum length of any ".datatype" field. */
char *stddt; /* Standardized name for a datatype */
int i,j; /* Loop counters */
unsigned hash; /* For hashing the name of a type */
const char *name; /* Name of the parser */
/* Allocate and initialize types[] and allocate stddt[] */
arraysize = lemp->nsymbol * 2;
types = (char**)calloc( arraysize, sizeof(char*) );
if( types==0 ){
fprintf(stderr,"Out of memory.\n");
exit(1);
}
for(i=0; i<arraysize; i++) types[i] = 0;
maxdtlength = 0;
if( lemp->vartype ){
maxdtlength = lemonStrlen(lemp->vartype);
}
for(i=0; i<lemp->nsymbol; i++){
int len;
struct symbol *sp = lemp->symbols[i];
if( sp->datatype==0 ) continue;
len = lemonStrlen(sp->datatype);
if( len>maxdtlength ) maxdtlength = len;
}
stddt = (char*)malloc( maxdtlength*2 + 1 );
if( stddt==0 ){
fprintf(stderr,"Out of memory.\n");
exit(1);
}
/* Build a hash table of datatypes. The ".dtnum" field of each symbol
** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
** used for terminal symbols. If there is no %default_type defined then
** 0 is also used as the .dtnum value for nonterminals which do not specify
** a datatype using the %type directive.
*/
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
char *cp;
if( sp==lemp->errsym ){
sp->dtnum = arraysize+1;
continue;
}
if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
sp->dtnum = 0;
continue;
}
cp = sp->datatype;
if( cp==0 ) cp = lemp->vartype;
j = 0;
while( ISSPACE(*cp) ) cp++;
while( *cp ) stddt[j++] = *cp++;
while( j>0 && ISSPACE(stddt[j-1]) ) j--;
stddt[j] = 0;
if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
sp->dtnum = 0;
continue;
}
hash = 0;
for(j=0; stddt[j]; j++){
hash = hash*53 + stddt[j];
}
hash = (hash & 0x7fffffff)%arraysize;
while( types[hash] ){
if( strcmp(types[hash],stddt)==0 ){
sp->dtnum = hash + 1;
break;
}
hash++;
if( hash>=(unsigned)arraysize ) hash = 0;
}
if( types[hash]==0 ){
sp->dtnum = hash + 1;
types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
if( types[hash]==0 ){
fprintf(stderr,"Out of memory.\n");
exit(1);
}
lemon_strcpy(types[hash],stddt);
}
}
/* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
name = lemp->name ? lemp->name : "Parse";
lineno = *plineno;
if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
fprintf(out,"#define %sTOKENTYPE %s\n",name,
lemp->tokentype?lemp->tokentype:"void*"); lineno++;
if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
fprintf(out,"typedef union {\n"); lineno++;
fprintf(out," int yyinit;\n"); lineno++;
fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
for(i=0; i<arraysize; i++){
if( types[i]==0 ) continue;
fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
free(types[i]);
}
if( lemp->errsym && lemp->errsym->useCnt ){
fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
}
free(stddt);
free(types);
fprintf(out,"} YYMINORTYPE;\n"); lineno++;
*plineno = lineno;
}
/*
** Return the name of a C datatype able to represent values between
** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
** for that type (1, 2, or 4) into *pnByte.
*/
static const char *minimum_size_type(int lwr, int upr, int *pnByte){
const char *zType = "int";
int nByte = 4;
if( lwr>=0 ){
if( upr<=255 ){
zType = "unsigned char";
nByte = 1;
}else if( upr<65535 ){
zType = "unsigned short int";
nByte = 2;
}else{
zType = "unsigned int";
nByte = 4;
}
}else if( lwr>=-127 && upr<=127 ){
zType = "signed char";
nByte = 1;
}else if( lwr>=-32767 && upr<32767 ){
zType = "short";
nByte = 2;
}
if( pnByte ) *pnByte = nByte;
return zType;
}
/*
** Each state contains a set of token transaction and a set of
** nonterminal transactions. Each of these sets makes an instance
** of the following structure. An array of these structures is used
** to order the creation of entries in the yy_action[] table.
*/
struct axset {
struct state *stp; /* A pointer to a state */
int isTkn; /* True to use tokens. False for non-terminals */
int nAction; /* Number of actions */
int iOrder; /* Original order of action sets */
};
/*
** Compare to axset structures for sorting purposes
*/
static int axset_compare(const void *a, const void *b){
struct axset *p1 = (struct axset*)a;
struct axset *p2 = (struct axset*)b;
int c;
c = p2->nAction - p1->nAction;
if( c==0 ){
c = p1->iOrder - p2->iOrder;
}
assert( c!=0 || p1==p2 );
return c;
}
/*
** Write text on "out" that describes the rule "rp".
*/
static void writeRuleText(FILE *out, struct rule *rp){
int j;
fprintf(out,"%s ::=", rp->lhs->name);
for(j=0; j<rp->nrhs; j++){
struct symbol *sp = rp->rhs[j];
if( sp->type!=MULTITERMINAL ){
fprintf(out," %s", sp->name);
}else{
int k;
fprintf(out," %s", sp->subsym[0]->name);
for(k=1; k<sp->nsubsym; k++){
fprintf(out,"|%s",sp->subsym[k]->name);
}
}
}
}
/* Generate C source code for the parser */
void ReportTable(
struct lemon *lemp,
int mhflag, /* Output in makeheaders format if true */
int sqlFlag /* Generate the *.sql file too */
){
FILE *out, *in, *sql;
char line[LINESIZE];
int lineno;
struct state *stp;
struct action *ap;
struct rule *rp;
struct acttab *pActtab;
int i, j, n, sz;
int nLookAhead;
int szActionType; /* sizeof(YYACTIONTYPE) */
int szCodeType; /* sizeof(YYCODETYPE) */
const char *name;
int mnTknOfst, mxTknOfst;
int mnNtOfst, mxNtOfst;
struct axset *ax;
char *prefix;
lemp->minShiftReduce = lemp->nstate;
lemp->errAction = lemp->minShiftReduce + lemp->nrule;
lemp->accAction = lemp->errAction + 1;
lemp->noAction = lemp->accAction + 1;
lemp->minReduce = lemp->noAction + 1;
lemp->maxAction = lemp->minReduce + lemp->nrule;
in = tplt_open(lemp);
if( in==0 ) return;
out = file_open(lemp,".c","wb");
if( out==0 ){
fclose(in);
return;
}
if( sqlFlag==0 ){
sql = 0;
}else{
sql = file_open(lemp, ".sql", "wb");
if( sql==0 ){
fclose(in);
fclose(out);
return;
}
fprintf(sql,
"BEGIN;\n"
"CREATE TABLE symbol(\n"
" id INTEGER PRIMARY KEY,\n"
" name TEXT NOT NULL,\n"
" isTerminal BOOLEAN NOT NULL,\n"
" fallback INTEGER REFERENCES symbol"
" DEFERRABLE INITIALLY DEFERRED\n"
");\n"
);
for(i=0; i<lemp->nsymbol; i++){
fprintf(sql,
"INSERT INTO symbol(id,name,isTerminal,fallback)"
"VALUES(%d,'%s',%s",
i, lemp->symbols[i]->name,
i<lemp->nterminal ? "TRUE" : "FALSE"
);
if( lemp->symbols[i]->fallback ){
fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index);
}else{
fprintf(sql, ",NULL);\n");
}
}
fprintf(sql,
"CREATE TABLE rule(\n"
" ruleid INTEGER PRIMARY KEY,\n"
" lhs INTEGER REFERENCES symbol(id),\n"
" txt TEXT\n"
");\n"
"CREATE TABLE rulerhs(\n"
" ruleid INTEGER REFERENCES rule(ruleid),\n"
" pos INTEGER,\n"
" sym INTEGER REFERENCES symbol(id)\n"
");\n"
);
for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
assert( i==rp->iRule );
fprintf(sql,
"INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'",
rp->iRule, rp->lhs->index
);
writeRuleText(sql, rp);
fprintf(sql,"');\n");
for(j=0; j<rp->nrhs; j++){
struct symbol *sp = rp->rhs[j];
if( sp->type!=MULTITERMINAL ){
fprintf(sql,
"INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
i,j,sp->index
);
}else{
int k;
for(k=0; k<sp->nsubsym; k++){
fprintf(sql,
"INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
i,j,sp->subsym[k]->index
);
}
}
}
}
fprintf(sql, "COMMIT;\n");
}
lineno = 1;
fprintf(out,
"/* This file is automatically generated by Lemon from input grammar\n"
"** source file \"%s\". */\n", lemp->filename); lineno += 2;
/* The first %include directive begins with a C-language comment,
** then skip over the header comment of the template file
*/
if( lemp->include==0 ) lemp->include = "";
for(i=0; ISSPACE(lemp->include[i]); i++){
if( lemp->include[i]=='\n' ){
lemp->include += i+1;
i = -1;
}
}
if( lemp->include[0]=='/' ){
tplt_skip_header(in,&lineno);
}else{
tplt_xfer(lemp->name,in,out,&lineno);
}
/* Generate the include code, if any */
tplt_print(out,lemp,lemp->include,&lineno);
if( mhflag ){
char *incName = file_makename(lemp, ".h");
fprintf(out,"#include \"%s\"\n", incName); lineno++;
free(incName);
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate #defines for all tokens */
if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
else prefix = "";
if( mhflag ){
fprintf(out,"#if INTERFACE\n"); lineno++;
}else{
fprintf(out,"#ifndef %s%s\n", prefix, lemp->symbols[1]->name);
}
for(i=1; i<lemp->nterminal; i++){
fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
lineno++;
}
fprintf(out,"#endif\n"); lineno++;
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the defines */
fprintf(out,"#define YYCODETYPE %s\n",
minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
fprintf(out,"#define YYACTIONTYPE %s\n",
minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
if( lemp->wildcard ){
fprintf(out,"#define YYWILDCARD %d\n",
lemp->wildcard->index); lineno++;
}
print_stack_union(out,lemp,&lineno,mhflag);
fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
if( lemp->stacksize ){
fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
}else{
fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
}
fprintf(out, "#endif\n"); lineno++;
if( mhflag ){
fprintf(out,"#if INTERFACE\n"); lineno++;
}
name = lemp->name ? lemp->name : "Parse";
if( lemp->arg && lemp->arg[0] ){
i = lemonStrlen(lemp->arg);
while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
name,lemp->arg,&lemp->arg[i]); lineno++;
fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
name,&lemp->arg[i],&lemp->arg[i]); lineno++;
}else{
fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
fprintf(out,"#define %sARG_STORE\n",name); lineno++;
}
if( lemp->ctx && lemp->ctx[0] ){
i = lemonStrlen(lemp->ctx);
while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
name,lemp->ctx,&lemp->ctx[i]); lineno++;
fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
}else{
fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
}
if( mhflag ){
fprintf(out,"#endif\n"); lineno++;
}
if( lemp->errsym && lemp->errsym->useCnt ){
fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
}
if( lemp->has_fallback ){
fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
}
/* Compute the action table, but do not output it yet. The action
** table must be computed before generating the YYNSTATE macro because
** we need to know how many states can be eliminated.
*/
ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
if( ax==0 ){
fprintf(stderr,"malloc failed\n");
exit(1);
}
for(i=0; i<lemp->nxstate; i++){
stp = lemp->sorted[i];
ax[i*2].stp = stp;
ax[i*2].isTkn = 1;
ax[i*2].nAction = stp->nTknAct;
ax[i*2+1].stp = stp;
ax[i*2+1].isTkn = 0;
ax[i*2+1].nAction = stp->nNtAct;
}
mxTknOfst = mnTknOfst = 0;
mxNtOfst = mnNtOfst = 0;
/* In an effort to minimize the action table size, use the heuristic
** of placing the largest action sets first */
for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
stp = ax[i].stp;
if( ax[i].isTkn ){
for(ap=stp->ap; ap; ap=ap->next){
int action;
if( ap->sp->index>=lemp->nterminal ) continue;
action = compute_action(lemp, ap);
if( action<0 ) continue;
acttab_action(pActtab, ap->sp->index, action);
}
stp->iTknOfst = acttab_insert(pActtab, 1);
if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
}else{
for(ap=stp->ap; ap; ap=ap->next){
int action;
if( ap->sp->index<lemp->nterminal ) continue;
if( ap->sp->index==lemp->nsymbol ) continue;
action = compute_action(lemp, ap);
if( action<0 ) continue;
acttab_action(pActtab, ap->sp->index, action);
}
stp->iNtOfst = acttab_insert(pActtab, 0);
if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
}
#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
{ int jj, nn;
for(jj=nn=0; jj<pActtab->nAction; jj++){
if( pActtab->aAction[jj].action<0 ) nn++;
}
printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
ax[i].nAction, pActtab->nAction, nn);
}
#endif
}
free(ax);
/* Mark rules that are actually used for reduce actions after all
** optimizations have been applied
*/
for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
for(i=0; i<lemp->nxstate; i++){
for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
ap->x.rp->doesReduce = 1;
}
}
}
/* Finish rendering the constants now that the action table has
** been computed */
fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
fprintf(out,"#define YYNRULE_WITH_ACTION %d\n",lemp->nruleWithAction);
lineno++;
fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
i = lemp->minShiftReduce;
fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
i += lemp->nrule;
fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
i = lemp->minReduce + lemp->nrule;
fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
tplt_xfer(lemp->name,in,out,&lineno);
/* Now output the action table and its associates:
**
** yy_action[] A single table containing all actions.
** yy_lookahead[] A table containing the lookahead for each entry in
** yy_action. Used to detect hash collisions.
** yy_shift_ofst[] For each state, the offset into yy_action for
** shifting terminals.
** yy_reduce_ofst[] For each state, the offset into yy_action for
** shifting non-terminals after a reduce.
** yy_default[] Default action for each state.
*/
/* Output the yy_action table */
lemp->nactiontab = n = acttab_action_size(pActtab);
lemp->tablesize += n*szActionType;
fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
for(i=j=0; i<n; i++){
int action = acttab_yyaction(pActtab, i);
if( action<0 ) action = lemp->noAction;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", action);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the yy_lookahead table */
lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
lemp->tablesize += n*szCodeType;
fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
for(i=j=0; i<n; i++){
int la = acttab_yylookahead(pActtab, i);
if( la<0 ) la = lemp->nsymbol;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", la);
if( j==9 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
/* Add extra entries to the end of the yy_lookahead[] table so that
** yy_shift_ofst[]+iToken will always be a valid index into the array,
** even for the largest possible value of yy_shift_ofst[] and iToken. */
nLookAhead = lemp->nterminal + lemp->nactiontab;
while( i<nLookAhead ){
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", lemp->nterminal);
if( j==9 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
i++;
}
if( j>0 ){ fprintf(out, "\n"); lineno++; }
fprintf(out, "};\n"); lineno++;
/* Output the yy_shift_ofst[] table */
n = lemp->nxstate;
while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
fprintf(out, "static const %s yy_shift_ofst[] = {\n",
minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
lineno++;
lemp->tablesize += n*sz;
for(i=j=0; i<n; i++){
int ofst;
stp = lemp->sorted[i];
ofst = stp->iTknOfst;
if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", ofst);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the yy_reduce_ofst[] table */
n = lemp->nxstate;
while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
lemp->tablesize += n*sz;
for(i=j=0; i<n; i++){
int ofst;
stp = lemp->sorted[i];
ofst = stp->iNtOfst;
if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", ofst);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the default action table */
fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
n = lemp->nxstate;
lemp->tablesize += n*szActionType;
for(i=j=0; i<n; i++){
stp = lemp->sorted[i];
if( j==0 ) fprintf(out," /* %5d */ ", i);
if( stp->iDfltReduce<0 ){
fprintf(out, " %4d,", lemp->errAction);
}else{
fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
}
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the table of fallback tokens.
*/
if( lemp->has_fallback ){
int mx = lemp->nterminal - 1;
/* 2019-08-28: Generate fallback entries for every token to avoid
** having to do a range check on the index */
/* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
lemp->tablesize += (mx+1)*szCodeType;
for(i=0; i<=mx; i++){
struct symbol *p = lemp->symbols[i];
if( p->fallback==0 ){
fprintf(out, " 0, /* %10s => nothing */\n", p->name);
}else{
fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
p->name, p->fallback->name);
}
lineno++;
}
}
tplt_xfer(lemp->name, in, out, &lineno);
/* Generate a table containing the symbolic name of every symbol
*/
for(i=0; i<lemp->nsymbol; i++){
lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate a table containing a text string that describes every
** rule in the rule set of the grammar. This information is used
** when tracing REDUCE actions.
*/
for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
assert( rp->iRule==i );
fprintf(out," /* %3d */ \"", i);
writeRuleText(out, rp);
fprintf(out,"\",\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes every time a symbol is popped from
** the stack while processing errors or while destroying the parser.
** (In other words, generate the %destructor actions)
*/
if( lemp->tokendest ){
int once = 1;
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
if( sp==0 || sp->type!=TERMINAL ) continue;
if( once ){
fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
once = 0;
}
fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
}
for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
if( i<lemp->nsymbol ){
emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
}
if( lemp->vardest ){
struct symbol *dflt_sp = 0;
int once = 1;
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
if( sp==0 || sp->type==TERMINAL ||
sp->index<=0 || sp->destructor!=0 ) continue;
if( once ){
fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
once = 0;
}
fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
dflt_sp = sp;
}
if( dflt_sp!=0 ){
emit_destructor_code(out,dflt_sp,lemp,&lineno);
}
fprintf(out," break;\n"); lineno++;
}
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
if( sp->destLineno<0 ) continue; /* Already emitted */
fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
/* Combine duplicate destructors into a single case */
for(j=i+1; j<lemp->nsymbol; j++){
struct symbol *sp2 = lemp->symbols[j];
if( sp2 && sp2->type!=TERMINAL && sp2->destructor
&& sp2->dtnum==sp->dtnum
&& strcmp(sp->destructor,sp2->destructor)==0 ){
fprintf(out," case %d: /* %s */\n",
sp2->index, sp2->name); lineno++;
sp2->destLineno = -1; /* Avoid emitting this destructor again */
}
}
emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes whenever the parser stack overflows */
tplt_print(out,lemp,lemp->overflow,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the tables of rule information. yyRuleInfoLhs[] and
** yyRuleInfoNRhs[].
**
** Note: This code depends on the fact that rules are number
** sequentially beginning with 0.
*/
for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
rule_print(out, rp);
fprintf(out," */\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
rule_print(out, rp);
fprintf(out," */\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which execution during each REDUCE action */
i = 0;
for(rp=lemp->rule; rp; rp=rp->next){
i += translate_code(lemp, rp);
}
if( i ){
fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
}
/* First output rules other than the default: rule */
for(rp=lemp->rule; rp; rp=rp->next){
struct rule *rp2; /* Other rules with the same action */
if( rp->codeEmitted ) continue;
if( rp->noCode ){
/* No C code actions, so this will be part of the "default:" rule */
continue;
}
fprintf(out," case %d: /* ", rp->iRule);
writeRuleText(out, rp);
fprintf(out, " */\n"); lineno++;
for(rp2=rp->next; rp2; rp2=rp2->next){
if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
&& rp2->codeSuffix==rp->codeSuffix ){
fprintf(out," case %d: /* ", rp2->iRule);
writeRuleText(out, rp2);
fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
rp2->codeEmitted = 1;
}
}
emit_code(out,rp,lemp,&lineno);
fprintf(out," break;\n"); lineno++;
rp->codeEmitted = 1;
}
/* Finally, output the default: rule. We choose as the default: all
** empty actions. */
fprintf(out," default:\n"); lineno++;
for(rp=lemp->rule; rp; rp=rp->next){
if( rp->codeEmitted ) continue;
assert( rp->noCode );
fprintf(out," /* (%d) ", rp->iRule);
writeRuleText(out, rp);
if( rp->neverReduce ){
fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
rp->iRule); lineno++;
}else if( rp->doesReduce ){
fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
}else{
fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
rp->iRule); lineno++;
}
}
fprintf(out," break;\n"); lineno++;
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes if a parse fails */
tplt_print(out,lemp,lemp->failure,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes when a syntax error occurs */
tplt_print(out,lemp,lemp->error,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes when the parser accepts its input */
tplt_print(out,lemp,lemp->accept,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Append any addition code the user desires */
tplt_print(out,lemp,lemp->extracode,&lineno);
acttab_free(pActtab);
fclose(in);
fclose(out);
if( sql ) fclose(sql);
return;
}
/* Generate a header file for the parser */
void ReportHeader(struct lemon *lemp)
{
FILE *out, *in;
const char *prefix;
char line[LINESIZE];
char pattern[LINESIZE];
int i;
if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
else prefix = "";
in = file_open(lemp,".h","rb");
if( in ){
int nextChar;
for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
lemon_sprintf(pattern,"#define %s%-30s %3d\n",
prefix,lemp->symbols[i]->name,i);
if( strcmp(line,pattern) ) break;
}
nextChar = fgetc(in);
fclose(in);
if( i==lemp->nterminal && nextChar==EOF ){
/* No change in the file. Don't rewrite it. */
return;
}
}
out = file_open(lemp,".h","wb");
if( out ){
for(i=1; i<lemp->nterminal; i++){
fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
}
fclose(out);
}
return;
}
/* Reduce the size of the action tables, if possible, by making use
** of defaults.
**
** In this version, we take the most frequent REDUCE action and make
** it the default. Except, there is no default if the wildcard token
** is a possible look-ahead.
*/
void CompressTables(struct lemon *lemp)
{
struct state *stp;
struct action *ap, *ap2, *nextap;
struct rule *rp, *rp2, *rbest;
int nbest, n;
int i;
int usesWildcard;
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
nbest = 0;
rbest = 0;
usesWildcard = 0;
for(ap=stp->ap; ap; ap=ap->next){
if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
usesWildcard = 1;
}
if( ap->type!=REDUCE ) continue;
rp = ap->x.rp;
if( rp->lhsStart ) continue;
if( rp==rbest ) continue;
n = 1;
for(ap2=ap->next; ap2; ap2=ap2->next){
if( ap2->type!=REDUCE ) continue;
rp2 = ap2->x.rp;
if( rp2==rbest ) continue;
if( rp2==rp ) n++;
}
if( n>nbest ){
nbest = n;
rbest = rp;
}
}
/* Do not make a default if the number of rules to default
** is not at least 1 or if the wildcard token is a possible
** lookahead.
*/
if( nbest<1 || usesWildcard ) continue;
/* Combine matching REDUCE actions into a single default */
for(ap=stp->ap; ap; ap=ap->next){
if( ap->type==REDUCE && ap->x.rp==rbest ) break;
}
assert( ap );
ap->sp = Symbol_new("{default}");
for(ap=ap->next; ap; ap=ap->next){
if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
}
stp->ap = Action_sort(stp->ap);
for(ap=stp->ap; ap; ap=ap->next){
if( ap->type==SHIFT ) break;
if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
}
if( ap==0 ){
stp->autoReduce = 1;
stp->pDfltReduce = rbest;
}
}
/* Make a second pass over all states and actions. Convert
** every action that is a SHIFT to an autoReduce state into
** a SHIFTREDUCE action.
*/
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
for(ap=stp->ap; ap; ap=ap->next){
struct state *pNextState;
if( ap->type!=SHIFT ) continue;
pNextState = ap->x.stp;
if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
ap->type = SHIFTREDUCE;
ap->x.rp = pNextState->pDfltReduce;
}
}
}
/* If a SHIFTREDUCE action specifies a rule that has a single RHS term
** (meaning that the SHIFTREDUCE will land back in the state where it
** started) and if there is no C-code associated with the reduce action,
** then we can go ahead and convert the action to be the same as the
** action for the RHS of the rule.
*/
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
for(ap=stp->ap; ap; ap=nextap){
nextap = ap->next;
if( ap->type!=SHIFTREDUCE ) continue;
rp = ap->x.rp;
if( rp->noCode==0 ) continue;
if( rp->nrhs!=1 ) continue;
#if 1
/* Only apply this optimization to non-terminals. It would be OK to
** apply it to terminal symbols too, but that makes the parser tables
** larger. */
if( ap->sp->index<lemp->nterminal ) continue;
#endif
/* If we reach this point, it means the optimization can be applied */
nextap = ap;
for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
assert( ap2!=0 );
ap->spOpt = ap2->sp;
ap->type = ap2->type;
ap->x = ap2->x;
}
}
}
/*
** Compare two states for sorting purposes. The smaller state is the
** one with the most non-terminal actions. If they have the same number
** of non-terminal actions, then the smaller is the one with the most
** token actions.
*/
static int stateResortCompare(const void *a, const void *b){
const struct state *pA = *(const struct state**)a;
const struct state *pB = *(const struct state**)b;
int n;
n = pB->nNtAct - pA->nNtAct;
if( n==0 ){
n = pB->nTknAct - pA->nTknAct;
if( n==0 ){
n = pB->statenum - pA->statenum;
}
}
assert( n!=0 );
return n;
}
/*
** Renumber and resort states so that states with fewer choices
** occur at the end. Except, keep state 0 as the first state.
*/
void ResortStates(struct lemon *lemp)
{
int i;
struct state *stp;
struct action *ap;
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
stp->nTknAct = stp->nNtAct = 0;
stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
stp->iTknOfst = NO_OFFSET;
stp->iNtOfst = NO_OFFSET;
for(ap=stp->ap; ap; ap=ap->next){
int iAction = compute_action(lemp,ap);
if( iAction>=0 ){
if( ap->sp->index<lemp->nterminal ){
stp->nTknAct++;
}else if( ap->sp->index<lemp->nsymbol ){
stp->nNtAct++;
}else{
assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
stp->iDfltReduce = iAction;
}
}
}
}
qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
stateResortCompare);
for(i=0; i<lemp->nstate; i++){
lemp->sorted[i]->statenum = i;
}
lemp->nxstate = lemp->nstate;
while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
lemp->nxstate--;
}
}
/***************** From the file "set.c" ************************************/
/*
** Set manipulation routines for the LEMON parser generator.
*/
static int size = 0;
/* Set the set size */
void SetSize(int n)
{
size = n+1;
}
/* Allocate a new set */
char *SetNew(void){
char *s;
s = (char*)calloc( size, 1);
if( s==0 ){
memory_error();
}
return s;
}
/* Deallocate a set */
void SetFree(char *s)
{
free(s);
}
/* Add a new element to the set. Return TRUE if the element was added
** and FALSE if it was already there. */
int SetAdd(char *s, int e)
{
int rv;
assert( e>=0 && e<size );
rv = s[e];
s[e] = 1;
return !rv;
}
/* Add every element of s2 to s1. Return TRUE if s1 changes. */
int SetUnion(char *s1, char *s2)
{
int i, progress;
progress = 0;
for(i=0; i<size; i++){
if( s2[i]==0 ) continue;
if( s1[i]==0 ){
progress = 1;
s1[i] = 1;
}
}
return progress;
}
/********************** From the file "table.c" ****************************/
/*
** All code in this file has been automatically generated
** from a specification in the file
** "table.q"
** by the associative array code building program "aagen".
** Do not edit this file! Instead, edit the specification
** file, then rerun aagen.
*/
/*
** Code for processing tables in the LEMON parser generator.
*/
PRIVATE unsigned strhash(const char *x)
{
unsigned h = 0;
while( *x ) h = h*13 + *(x++);
return h;
}
/* Works like strdup, sort of. Save a string in malloced memory, but
** keep strings in a table so that the same string is not in more
** than one place.
*/
const char *Strsafe(const char *y)
{
const char *z;
char *cpy;
if( y==0 ) return 0;
z = Strsafe_find(y);
if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
lemon_strcpy(cpy,y);
z = cpy;
Strsafe_insert(z);
}
MemoryCheck(z);
return z;
}
/* There is one instance of the following structure for each
** associative array of type "x1".
*/
struct s_x1 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x1node *tbl; /* The data stored here */
struct s_x1node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x1".
*/
typedef struct s_x1node {
const char *data; /* The data */
struct s_x1node *next; /* Next entry with the same hash */
struct s_x1node **from; /* Previous link */
} x1node;
/* There is only one instance of the array, which is the following */
static struct s_x1 *x1a;
/* Allocate a new associative array */
void Strsafe_init(void){
if( x1a ) return;
x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
if( x1a ){
x1a->size = 1024;
x1a->count = 0;
x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
if( x1a->tbl==0 ){
free(x1a);
x1a = 0;
}else{
int i;
x1a->ht = (x1node**)&(x1a->tbl[1024]);
for(i=0; i<1024; i++) x1a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Strsafe_insert(const char *data)
{
x1node *np;
unsigned h;
unsigned ph;
if( x1a==0 ) return 0;
ph = strhash(data);
h = ph & (x1a->size-1);
np = x1a->ht[h];
while( np ){
if( strcmp(np->data,data)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x1a->count>=x1a->size ){
/* Need to make the hash table bigger */
int i,arrSize;
struct s_x1 array;
array.size = arrSize = x1a->size*2;
array.count = x1a->count;
array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x1node**)&(array.tbl[arrSize]);
for(i=0; i<arrSize; i++) array.ht[i] = 0;
for(i=0; i<x1a->count; i++){
x1node *oldnp, *newnp;
oldnp = &(x1a->tbl[i]);
h = strhash(oldnp->data) & (arrSize-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x1a->tbl);
*x1a = array;
}
/* Insert the new data */
h = ph & (x1a->size-1);
np = &(x1a->tbl[x1a->count++]);
np->data = data;
if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
np->next = x1a->ht[h];
x1a->ht[h] = np;
np->from = &(x1a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
const char *Strsafe_find(const char *key)
{
unsigned h;
x1node *np;
if( x1a==0 ) return 0;
h = strhash(key) & (x1a->size-1);
np = x1a->ht[h];
while( np ){
if( strcmp(np->data,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Return a pointer to the (terminal or nonterminal) symbol "x".
** Create a new symbol if this is the first time "x" has been seen.
*/
struct symbol *Symbol_new(const char *x)
{
struct symbol *sp;
sp = Symbol_find(x);
if( sp==0 ){
sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
MemoryCheck(sp);
sp->name = Strsafe(x);
sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
sp->rule = 0;
sp->fallback = 0;
sp->prec = -1;
sp->assoc = UNK;
sp->firstset = 0;
sp->lambda = LEMON_FALSE;
sp->destructor = 0;
sp->destLineno = 0;
sp->datatype = 0;
sp->useCnt = 0;
Symbol_insert(sp,sp->name);
}
sp->useCnt++;
return sp;
}
/* Compare two symbols for sorting purposes. Return negative,
** zero, or positive if a is less then, equal to, or greater
** than b.
**
** Symbols that begin with upper case letters (terminals or tokens)
** must sort before symbols that begin with lower case letters
** (non-terminals). And MULTITERMINAL symbols (created using the
** %token_class directive) must sort at the very end. Other than
** that, the order does not matter.
**
** We find experimentally that leaving the symbols in their original
** order (the order they appeared in the grammar file) gives the
** smallest parser tables in SQLite.
*/
int Symbolcmpp(const void *_a, const void *_b)
{
const struct symbol *a = *(const struct symbol **) _a;
const struct symbol *b = *(const struct symbol **) _b;
int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
return i1==i2 ? a->index - b->index : i1 - i2;
}
/* There is one instance of the following structure for each
** associative array of type "x2".
*/
struct s_x2 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x2node *tbl; /* The data stored here */
struct s_x2node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x2".
*/
typedef struct s_x2node {
struct symbol *data; /* The data */
const char *key; /* The key */
struct s_x2node *next; /* Next entry with the same hash */
struct s_x2node **from; /* Previous link */
} x2node;
/* There is only one instance of the array, which is the following */
static struct s_x2 *x2a;
/* Allocate a new associative array */
void Symbol_init(void){
if( x2a ) return;
x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
if( x2a ){
x2a->size = 128;
x2a->count = 0;
x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
if( x2a->tbl==0 ){
free(x2a);
x2a = 0;
}else{
int i;
x2a->ht = (x2node**)&(x2a->tbl[128]);
for(i=0; i<128; i++) x2a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Symbol_insert(struct symbol *data, const char *key)
{
x2node *np;
unsigned h;
unsigned ph;
if( x2a==0 ) return 0;
ph = strhash(key);
h = ph & (x2a->size-1);
np = x2a->ht[h];
while( np ){
if( strcmp(np->key,key)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x2a->count>=x2a->size ){
/* Need to make the hash table bigger */
int i,arrSize;
struct s_x2 array;
array.size = arrSize = x2a->size*2;
array.count = x2a->count;
array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x2node**)&(array.tbl[arrSize]);
for(i=0; i<arrSize; i++) array.ht[i] = 0;
for(i=0; i<x2a->count; i++){
x2node *oldnp, *newnp;
oldnp = &(x2a->tbl[i]);
h = strhash(oldnp->key) & (arrSize-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->key = oldnp->key;
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x2a->tbl);
*x2a = array;
}
/* Insert the new data */
h = ph & (x2a->size-1);
np = &(x2a->tbl[x2a->count++]);
np->key = key;
np->data = data;
if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
np->next = x2a->ht[h];
x2a->ht[h] = np;
np->from = &(x2a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
struct symbol *Symbol_find(const char *key)
{
unsigned h;
x2node *np;
if( x2a==0 ) return 0;
h = strhash(key) & (x2a->size-1);
np = x2a->ht[h];
while( np ){
if( strcmp(np->key,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Return the n-th data. Return NULL if n is out of range. */
struct symbol *Symbol_Nth(int n)
{
struct symbol *data;
if( x2a && n>0 && n<=x2a->count ){
data = x2a->tbl[n-1].data;
}else{
data = 0;
}
return data;
}
/* Return the size of the array */
int Symbol_count()
{
return x2a ? x2a->count : 0;
}
/* Return an array of pointers to all data in the table.
** The array is obtained from malloc. Return NULL if memory allocation
** problems, or if the array is empty. */
struct symbol **Symbol_arrayof()
{
struct symbol **array;
int i,arrSize;
if( x2a==0 ) return 0;
arrSize = x2a->count;
array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
if( array ){
for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
}
return array;
}
/* Compare two configurations */
int Configcmp(const char *_a,const char *_b)
{
const struct config *a = (struct config *) _a;
const struct config *b = (struct config *) _b;
int x;
x = a->rp->index - b->rp->index;
if( x==0 ) x = a->dot - b->dot;
return x;
}
/* Compare two states */
PRIVATE int statecmp(struct config *a, struct config *b)
{
int rc;
for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
rc = a->rp->index - b->rp->index;
if( rc==0 ) rc = a->dot - b->dot;
}
if( rc==0 ){
if( a ) rc = 1;
if( b ) rc = -1;
}
return rc;
}
/* Hash a state */
PRIVATE unsigned statehash(struct config *a)
{
unsigned h=0;
while( a ){
h = h*571 + a->rp->index*37 + a->dot;
a = a->bp;
}
return h;
}
/* Allocate a new state structure */
struct state *State_new()
{
struct state *newstate;
newstate = (struct state *)calloc(1, sizeof(struct state) );
MemoryCheck(newstate);
return newstate;
}
/* There is one instance of the following structure for each
** associative array of type "x3".
*/
struct s_x3 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x3node *tbl; /* The data stored here */
struct s_x3node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x3".
*/
typedef struct s_x3node {
struct state *data; /* The data */
struct config *key; /* The key */
struct s_x3node *next; /* Next entry with the same hash */
struct s_x3node **from; /* Previous link */
} x3node;
/* There is only one instance of the array, which is the following */
static struct s_x3 *x3a;
/* Allocate a new associative array */
void State_init(void){
if( x3a ) return;
x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
if( x3a ){
x3a->size = 128;
x3a->count = 0;
x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
if( x3a->tbl==0 ){
free(x3a);
x3a = 0;
}else{
int i;
x3a->ht = (x3node**)&(x3a->tbl[128]);
for(i=0; i<128; i++) x3a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int State_insert(struct state *data, struct config *key)
{
x3node *np;
unsigned h;
unsigned ph;
if( x3a==0 ) return 0;
ph = statehash(key);
h = ph & (x3a->size-1);
np = x3a->ht[h];
while( np ){
if( statecmp(np->key,key)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x3a->count>=x3a->size ){
/* Need to make the hash table bigger */
int i,arrSize;
struct s_x3 array;
array.size = arrSize = x3a->size*2;
array.count = x3a->count;
array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x3node**)&(array.tbl[arrSize]);
for(i=0; i<arrSize; i++) array.ht[i] = 0;
for(i=0; i<x3a->count; i++){
x3node *oldnp, *newnp;
oldnp = &(x3a->tbl[i]);
h = statehash(oldnp->key) & (arrSize-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->key = oldnp->key;
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x3a->tbl);
*x3a = array;
}
/* Insert the new data */
h = ph & (x3a->size-1);
np = &(x3a->tbl[x3a->count++]);
np->key = key;
np->data = data;
if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
np->next = x3a->ht[h];
x3a->ht[h] = np;
np->from = &(x3a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
struct state *State_find(struct config *key)
{
unsigned h;
x3node *np;
if( x3a==0 ) return 0;
h = statehash(key) & (x3a->size-1);
np = x3a->ht[h];
while( np ){
if( statecmp(np->key,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Return an array of pointers to all data in the table.
** The array is obtained from malloc. Return NULL if memory allocation
** problems, or if the array is empty. */
struct state **State_arrayof(void)
{
struct state **array;
int i,arrSize;
if( x3a==0 ) return 0;
arrSize = x3a->count;
array = (struct state **)calloc(arrSize, sizeof(struct state *));
if( array ){
for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
}
return array;
}
/* Hash a configuration */
PRIVATE unsigned confighash(struct config *a)
{
unsigned h=0;
h = h*571 + a->rp->index*37 + a->dot;
return h;
}
/* There is one instance of the following structure for each
** associative array of type "x4".
*/
struct s_x4 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x4node *tbl; /* The data stored here */
struct s_x4node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x4".
*/
typedef struct s_x4node {
struct config *data; /* The data */
struct s_x4node *next; /* Next entry with the same hash */
struct s_x4node **from; /* Previous link */
} x4node;
/* There is only one instance of the array, which is the following */
static struct s_x4 *x4a;
/* Allocate a new associative array */
void Configtable_init(void){
if( x4a ) return;
x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
if( x4a ){
x4a->size = 64;
x4a->count = 0;
x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
if( x4a->tbl==0 ){
free(x4a);
x4a = 0;
}else{
int i;
x4a->ht = (x4node**)&(x4a->tbl[64]);
for(i=0; i<64; i++) x4a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Configtable_insert(struct config *data)
{
x4node *np;
unsigned h;
unsigned ph;
if( x4a==0 ) return 0;
ph = confighash(data);
h = ph & (x4a->size-1);
np = x4a->ht[h];
while( np ){
if( Configcmp((const char *) np->data,(const char *) data)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x4a->count>=x4a->size ){
/* Need to make the hash table bigger */
int i,arrSize;
struct s_x4 array;
array.size = arrSize = x4a->size*2;
array.count = x4a->count;
array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x4node**)&(array.tbl[arrSize]);
for(i=0; i<arrSize; i++) array.ht[i] = 0;
for(i=0; i<x4a->count; i++){
x4node *oldnp, *newnp;
oldnp = &(x4a->tbl[i]);
h = confighash(oldnp->data) & (arrSize-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x4a->tbl);
*x4a = array;
}
/* Insert the new data */
h = ph & (x4a->size-1);
np = &(x4a->tbl[x4a->count++]);
np->data = data;
if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
np->next = x4a->ht[h];
x4a->ht[h] = np;
np->from = &(x4a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
struct config *Configtable_find(struct config *key)
{
int h;
x4node *np;
if( x4a==0 ) return 0;
h = confighash(key) & (x4a->size-1);
np = x4a->ht[h];
while( np ){
if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Remove all data from the table. Pass each data to the function "f"
** as it is removed. ("f" may be null to avoid this step.) */
void Configtable_clear(int(*f)(struct config *))
{
int i;
if( x4a==0 || x4a->count==0 ) return;
if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
x4a->count = 0;
return;
}
|
the_stack_data/92324469.c | /*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
/* Declarations for string types */
#define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \
IMPLEMENT_ASN1_TYPE(sname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(sname, sname, sname) \
sname *sname##_new(void) \
{ \
return ASN1_STRING_type_new(V_##sname); \
} \
void sname##_free(sname *x) \
{ \
ASN1_STRING_free(x); \
}
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_OCTET_STRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_INTEGER)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_ENUMERATED)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_BIT_STRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UTF8STRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_PRINTABLESTRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_T61STRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_IA5STRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_GENERALSTRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UTCTIME)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_GENERALIZEDTIME)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_VISIBLESTRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UNIVERSALSTRING)
IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_BMPSTRING)
IMPLEMENT_ASN1_TYPE(ASN1_NULL)
IMPLEMENT_ASN1_FUNCTIONS(ASN1_NULL)
IMPLEMENT_ASN1_TYPE(ASN1_OBJECT)
IMPLEMENT_ASN1_TYPE(ASN1_ANY)
/* Just swallow an ASN1_SEQUENCE in an ASN1_STRING */
IMPLEMENT_ASN1_TYPE(ASN1_SEQUENCE)
IMPLEMENT_ASN1_FUNCTIONS_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE)
/* Multistring types */
IMPLEMENT_ASN1_MSTRING(ASN1_PRINTABLE, B_ASN1_PRINTABLE)
IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE)
IMPLEMENT_ASN1_MSTRING(DISPLAYTEXT, B_ASN1_DISPLAYTEXT)
IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT)
IMPLEMENT_ASN1_MSTRING(DIRECTORYSTRING, B_ASN1_DIRECTORYSTRING)
IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING)
/* Three separate BOOLEAN type: normal, DEFAULT TRUE and DEFAULT FALSE */
IMPLEMENT_ASN1_TYPE_ex(ASN1_BOOLEAN, ASN1_BOOLEAN, -1)
IMPLEMENT_ASN1_TYPE_ex(ASN1_TBOOLEAN, ASN1_BOOLEAN, 1)
IMPLEMENT_ASN1_TYPE_ex(ASN1_FBOOLEAN, ASN1_BOOLEAN, 0)
/* Special, OCTET STRING with indefinite length constructed support */
IMPLEMENT_ASN1_TYPE_ex(ASN1_OCTET_STRING_NDEF, ASN1_OCTET_STRING, ASN1_TFLG_NDEF)
ASN1_ITEM_TEMPLATE(ASN1_SEQUENCE_ANY) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, ASN1_SEQUENCE_ANY, ASN1_ANY)
ASN1_ITEM_TEMPLATE_END(ASN1_SEQUENCE_ANY)
ASN1_ITEM_TEMPLATE(ASN1_SET_ANY) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, ASN1_SET_ANY, ASN1_ANY)
ASN1_ITEM_TEMPLATE_END(ASN1_SET_ANY)
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY)
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(ASN1_SEQUENCE_ANY, ASN1_SET_ANY, ASN1_SET_ANY)
|
the_stack_data/190769057.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
void error_handling(char *message);
int main(int argc, char *argv[])
{
int serv_sock, clnt_sock;
char message[BUF_SIZE];
int str_len, i;
struct sockaddr_in serv_adr;
struct sockaddr_in clnt_adr;
socklen_t clnt_adr_sz;
if(argc!=2) {
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock==-1)
error_handling("socket() error");
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(atoi(argv[1]));
int optval = 1;
setsockopt(serv_sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
if(bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr))==-1)
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
clnt_adr_sz=sizeof(clnt_adr);
for(i=0; i<5; i++)
{
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz);
if(clnt_sock==-1)
error_handling("accept() error");
else
printf("Connected client %d \n", i+1);
while((str_len=read(clnt_sock, message, BUF_SIZE))!=0){
printf("after read\n");
printf("Read Message from Client: %s", message);
message[str_len] = 0;
}
printf("read 0000\n");
}
close(clnt_sock);
close(serv_sock);
return 0;
}
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
} |
the_stack_data/127783.c | // WARNING: The files in this directory have not been extensively tested
// and may be incorrect. --JTB
void main() {
int d = 1;
int s = 1;
int N = 10;
for(int t = 0; t < N; t++) {
if (s == 1) {
d = - d;
s = d * d;
} else {
d = 5;
s = d * d;
}
}
__VERIFIER_assert(s == 1);
__VERIFIER_print_hull(d);
}
|
the_stack_data/148579354.c | #include <printf.h>
int main(void) {
printf("Printing int=%u, long=%lu, str=\"%s\"\n", 12345, 12345678, "Hello");
return 0;
}
|
the_stack_data/1050427.c | /* */
#include <regex.h>
int main(void){return 0;}
|
the_stack_data/47870.c | #include <stdlib.h>
#include <stdio.h>
#include <locale.h>
int Somapares(int v[], int tam,int soma){
if (tam < 30){
if(v[tam] % 2 == 0){
soma = soma + v[tam];
}
tam++;
Somapares(v, tam, soma);
} else{
return soma;
}
}
int main()
{
setlocale(LC_ALL,"portuguese");
srand(time(NULL));
int vetor[30], i, total, j=0, k=0;
for(i=0; i<30; i++){
vetor[i]= rand() % 11;
}
for(i=0; i<30; i++){
printf("%d ", vetor[i]);
}
total = Somapares(vetor, j, k);
printf("\nA soma dos números pares é: %d ", total);
return 0;
} |
the_stack_data/100141783.c | /**
* Do Your Job and I'll Do Mine 1.
*
* By walking through this example you’ll learn:
* - How to use thread_detach().
* - How to wait detached thread using shared variable.
*
*/
#include <stdio.h>
#include <stdatomic.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/wait.h>
#define NUM_WORKERS 3
#define NUM_PERSONAL_TASK 3
#define NUM_TOTAL_TASK (NUM_WORKERS * NUM_PERSONAL_TASK)
static _Atomic int cnt_task = NUM_TOTAL_TASK;
void do_job(char* actor);
void go_home(char* actor);
void* worker(void* arg);
void* boss(void* arg);
int main(int argc, char* argv[])
{
pthread_t tid;
int status;
status = pthread_create(&tid, NULL, boss, NULL);
if (status != 0)
{
printf("WTF?");
return -1;
}
pthread_join(tid, NULL);
// OBJECT: The main thread should not be exited until all `worker`s have finished.
//
// HINT: The `main` thread cannot wait for `worker` threads detached by `boos`.
// HINT: Is there any information about remaining tasks that can be
// referenced in the `main` thread?
while (cnt_task > 0)
;
return 0;
}
void do_job(char* actor){
cnt_task--;
printf("[%s] working...\n", actor);
}
void go_home(char* actor){
printf("[%s] So long suckers!\n", actor);
}
void* worker(void* arg)
{
char act[20];
sprintf(act, "%s%d", "worker", (int)arg);
for(int i = 0; i < NUM_PERSONAL_TASK; i++)
{
sleep(1);
do_job(act);
}
pthread_exit(NULL);
}
void* boss(void* arg)
{
pthread_t tid;
int status;
for(int i = 0; i < NUM_WORKERS; i++)
{
status = pthread_create(&tid, NULL, worker, i);
if (status != 0)
{
printf("WTF?");
return -1;
}
pthread_detach(tid);
}
go_home("like a boss");
pthread_exit(NULL);
}
|
the_stack_data/247019249.c | /*Program to find the elements which are largest in the column
and smallest in the row of matrix.*/
void main()
{
int A[50][50],small[50],large[50];
unsigned int i,j,m,n;
clrscr();
//i and j are the loop controllers
//m and n are the number of rows and columns respectively
printf("Enter the number of rows and columns respectively : ");
scanf("%u%u",&m,&n);
if(m>50||n>50)
{
printf("Sorry, Array size too large!");
goto end;
}
printf("Enter the elements of the matrix -\n");
for(i=0;i<m;i++)
{
printf("Enter the elements of row %u : ",i+1);
for(j=0;j<n;j++)
scanf("%d",&A[i][j]);
}
for(i=0;i<50;i++)
{
small[i]=32767;
large[i]=-32768;
}
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
if(A[i][j]<small[i])
small[i]=A[i][j];
if(A[i][j]>large[j])
large[j]=A[i][j];
}
printf("\nThe smallest element of\n");
for(i=0;i<m;i++)
printf("Row %u : %d\n",i+1,small[i]);
printf("\nThe largest element of\n");
for(j=0;j<n;j++)
printf("Column %u : %d\n",j+1,large[j]);
end:
printf("\nPress any key.....");
getch();
} |
the_stack_data/176843.c | // Time complexity : O(N)
#include <stdio.h>
#include<string.h>
void main() {
int n,c,k,space=1;
n=10;
space = n-1;
for(k=1;k<=n;k++){
for(c=1;c<=space;c++)
printf(" ");
space--;
for(c=1;c<=2*k-1;c++)
printf("*");
printf("\n");
}
space =1;
for(k=1;k<=n-1;k++){
for (c=1;c<=space;c++)
printf(" ");
space++;
for(c=1;c<=2*(n-k)-1; c++)
printf("*\n");
}
}
|
the_stack_data/17438.c | #include <stdio.h>
long long decimal_to_binary(int n)
{
int remainder = 0;
int i = 1;
long long b_num = 0;
while (n != 0)
{
remainder = n % 2;
printf("%d\n", remainder);
n = n / 2;
b_num += remainder * i;
i *= 10;
}
printf("%lld\n", b_num);
return b_num;
}
int main(void)
{
int onscreen_box = 0;
int mask_transparency = 1;
int mask_fill_colour = 3;
int mask_show_border = 1;
int mask_border_colour = 2;
int mask_border_style = 2;
onscreen_box = onscreen_box | (mask_transparency << 13);
onscreen_box = onscreen_box | (mask_fill_colour << 12);
onscreen_box = onscreen_box | (mask_show_border << 6);
onscreen_box = onscreen_box | (mask_border_colour << 5);
onscreen_box = onscreen_box | (mask_border_style << 2);
printf("%d\n", onscreen_box);
printf("%lld\n", decimal_to_binary(onscreen_box));
return 0;
}
|
the_stack_data/34511705.c | #include <stdlib.h>
#define A( i,j ) a[ (j)*lda + (i) ]
void random_matrix( int m, int n, float *a, int lda )
{
double drand48();
int i,j;
for ( i=0; i<m; i++ )
for ( j=0; j<n; j++ )
#if 1
A( i,j ) = 2.0 * (float)drand48( ) - 1.0;
#else
A( i, j) = (j-i) % 2;
#endif
}
|
the_stack_data/610682.c | #include<openssl/md5.h>
#include<stdio.h>
#include<string.h>
void main( int argc, char * argv[] )
{
unsigned char md5_sun[ 16 ];
int i;
if( argc < 2 ){
return;
}
MD5( argv[ 1 ], strlen( argv[ 1 ] ), md5_sun );
for( i = 0; i < sizeof( md5_sun ); i++ ){
printf( "%02x", md5_sun[ i ]);
}
printf( "\n" );
}
|
the_stack_data/257026.c | #include <fnmatch.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
/* On OS4 Console use pattern like **.info */
int main(int argc, char *argv[]) {
char *pattern;
DIR *dir;
struct dirent *entry;
int ret;
if (!argv[1] || !argv[2]) {
printf("Usage readdir_fnmatch PATTERN DIR\n");
return -1;
}
dir = opendir(argv[2]);
pattern = argv[1];
if (dir != NULL) {
while ((entry = readdir(dir)) != NULL) {
ret = fnmatch(pattern, entry->d_name, FNM_PATHNAME | FNM_PERIOD);
if (ret == 0) {
printf("%s MATCH\n", entry->d_name);
} else if (ret == FNM_NOMATCH) {
printf("%s DOESN'T MATCH\n", entry->d_name);
continue;
} else {
printf("error file=%s\n", entry->d_name);
}
}
closedir(dir);
} else {
printf("Cannot open dir %s\n", argv[2]);
}
return 0;
}
|
the_stack_data/82949788.c | int main() {
int a[5];
int i;
for (i = 0; i < 5; i++) {
a[i] = i;
}
int s = 0;
for (i = 0; i < 5; i++) {
s += a[i];
}
int s2 = 0;
int *pa = a;
for (i = 0; i < 5; i++) {
s2 += *(pa++);
}
return s == s2;
}
|
the_stack_data/139547.c | extern void abort (void);
/* Since GCC 5 folds symbol address comparison, assuming each symbol has
different address, &foo == &bar is always false for GCC 5. Use
check_ptr_eq to check if two functions are the same. */
void
check_ptr_eq (void (*f1) (void), void (*f2) (void))
{
if (f1 != f2)
abort ();
}
|
the_stack_data/1180496.c | int cvec_njobs = 6;
void cvec_set_njobs(int v) { cvec_njobs = v; }
|
the_stack_data/337999.c | #include <stdio.h>
int main(void) {
int ratingCounters[11], i, response;
for ( i = 1; i <= 10; ++i )
ratingCounters[i] = 0;
printf ( "Enter your responses\n" );
for ( i = 1; i <= 20; ++i ) {
scanf ("%i", &response);
if ( response < 1 || response > 10 )
printf ( "Bad response: %i\n", response);
else
++ratingCounters[response];
}
printf ( "\n\nRating Number of Responses\n" );
printf ( "------ -------------------\n" );
for ( i = 1; i <= 10; ++i )
printf ( "%4i%14i\n", i, ratingCounters[i] );
return 0;
}
|
the_stack_data/379715.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
int main(int argc, char **argv) {
//seed random number generator
// Q2b: get the number of threads to run with from agrv and
// add OpenMP API code to set number of threads here
double start;// = omp_get_wtime();
double end;
int Nthreads = atoi(argv[0]);
omp_set_num_threads(Nthreads);
struct drand48_data *drandData;
drandData = (struct drand48_data*) malloc(Nthreads*sizeof(struct drand48_data));
// Q2c: add an OpenMP parallel region here, wherein each thread initializes
// one entry in drandData using srand48_r and seed based on thread number
#pragma omp parallel
{
int rank = omp_get_thread_num();
long int seed = rank;
srand48_r(seed, drandData + rank);
}
//long int seed = 0;
long long int Ntrials = 10000000;
//need running tallies
long long int Ntotal=0;
long long int Ncircle=0;
start = omp_get_wtime();
#pragma omp parallel for reduction(+ : Ncircle)
for (long long int n=0; n<Ntrials; n++) {
double rand1;
double rand2;
//gererate two random numbers (use the thread id to offset drandData)
drand48_r(drandData+0, &rand1);
drand48_r(drandData+0, &rand2);
double x = -1 + 2*rand1; //shift to [-1,1]
double y = -1 + 2*rand2;
//check if its in the circle
if (sqrt(x*x+y*y)<=1) Ncircle++;
Ntotal++;
if (n%100 ==0) {
double pi = 4.0*Ncircle/ (double) (n);
//printf("Our estimate of pi is %g \n", pi);
}
//end = omp_get_wtime();
}
//end = omp_get_wtime()-start;
//printf("The total time was %f\n",end);
double pi = 4.0*Ncircle/ (double) (Ntotal);
printf("Our final estimate of pi is %g \n", pi);
free(drandData);
end = omp_get_wtime() - start;
printf("The total time was %f\n", end);
//free(drandData);
return 0;
}
|
the_stack_data/153256.c | /* This file was automatically generated by CasADi.
The CasADi copyright holders make no ownership claim of its contents. */
#ifdef __cplusplus
extern "C" {
#endif
/* How to prefix internal symbols */
#ifdef CODEGEN_PREFIX
#define NAMESPACE_CONCAT(NS, ID) _NAMESPACE_CONCAT(NS, ID)
#define _NAMESPACE_CONCAT(NS, ID) NS ## ID
#define CASADI_PREFIX(ID) NAMESPACE_CONCAT(CODEGEN_PREFIX, ID)
#else
#define CASADI_PREFIX(ID) crane_nx9_phi_jac_y_uhat_ ## ID
#endif
#include <math.h>
#ifndef casadi_real
#define casadi_real double
#endif
#ifndef casadi_int
#define casadi_int int
#endif
/* Add prefix to internal symbols */
#define casadi_f0 CASADI_PREFIX(f0)
#define casadi_s0 CASADI_PREFIX(s0)
#define casadi_s1 CASADI_PREFIX(s1)
#define casadi_s2 CASADI_PREFIX(s2)
/* Symbol visibility in DLLs */
#ifndef CASADI_SYMBOL_EXPORT
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
#if defined(STATIC_LINKED)
#define CASADI_SYMBOL_EXPORT
#else
#define CASADI_SYMBOL_EXPORT __declspec(dllexport)
#endif
#elif defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
#define CASADI_SYMBOL_EXPORT __attribute__ ((visibility ("default")))
#else
#define CASADI_SYMBOL_EXPORT
#endif
#endif
static const casadi_int casadi_s0[8] = {4, 1, 0, 4, 0, 1, 2, 3};
static const casadi_int casadi_s1[5] = {1, 1, 0, 1, 0};
static const casadi_int casadi_s2[11] = {1, 4, 0, 1, 2, 3, 4, 0, 0, 0, 0};
/* crane_nx9_phi_jac_y_uhat:(i0[4],i1)->(o0[1x4],o1) */
static int casadi_f0(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, void* mem) {
casadi_real a0, a1, a2, a3, a4, a5, a6, a7, a8, a9;
a0=4.7418203070092001e-02;
a1=arg[1] ? arg[1][0] : 0;
a1=(a0*a1);
a2=arg[0] ? arg[0][2] : 0;
a3=cos(a2);
a4=(a1*a3);
a5=9.8100000000000005e+00;
a6=sin(a2);
a6=(a5*a6);
a4=(a4+a6);
a6=2.;
a7=arg[0] ? arg[0][1] : 0;
a7=(a6*a7);
a8=arg[0] ? arg[0][3] : 0;
a9=(a7*a8);
a4=(a4+a9);
a9=arg[0] ? arg[0][0] : 0;
a4=(a4/a9);
a4=(a4/a9);
if (res[0]!=0) res[0][0]=a4;
a8=(a8/a9);
a6=(a6*a8);
a6=(-a6);
if (res[0]!=0) res[0][1]=a6;
a6=sin(a2);
a1=(a1/a9);
a6=(a6*a1);
a2=cos(a2);
a5=(a5/a9);
a2=(a2*a5);
a6=(a6-a2);
if (res[0]!=0) res[0][2]=a6;
a7=(a7/a9);
a7=(-a7);
if (res[0]!=0) res[0][3]=a7;
a0=(a0*a3);
a0=(a0/a9);
a0=(-a0);
if (res[1]!=0) res[1][0]=a0;
return 0;
}
CASADI_SYMBOL_EXPORT int crane_nx9_phi_jac_y_uhat(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, void* mem){
return casadi_f0(arg, res, iw, w, mem);
}
CASADI_SYMBOL_EXPORT void crane_nx9_phi_jac_y_uhat_incref(void) {
}
CASADI_SYMBOL_EXPORT void crane_nx9_phi_jac_y_uhat_decref(void) {
}
CASADI_SYMBOL_EXPORT casadi_int crane_nx9_phi_jac_y_uhat_n_in(void) { return 2;}
CASADI_SYMBOL_EXPORT casadi_int crane_nx9_phi_jac_y_uhat_n_out(void) { return 2;}
CASADI_SYMBOL_EXPORT const char* crane_nx9_phi_jac_y_uhat_name_in(casadi_int i){
switch (i) {
case 0: return "i0";
case 1: return "i1";
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const char* crane_nx9_phi_jac_y_uhat_name_out(casadi_int i){
switch (i) {
case 0: return "o0";
case 1: return "o1";
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const casadi_int* crane_nx9_phi_jac_y_uhat_sparsity_in(casadi_int i) {
switch (i) {
case 0: return casadi_s0;
case 1: return casadi_s1;
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const casadi_int* crane_nx9_phi_jac_y_uhat_sparsity_out(casadi_int i) {
switch (i) {
case 0: return casadi_s2;
case 1: return casadi_s1;
default: return 0;
}
}
CASADI_SYMBOL_EXPORT int crane_nx9_phi_jac_y_uhat_work(casadi_int *sz_arg, casadi_int* sz_res, casadi_int *sz_iw, casadi_int *sz_w) {
if (sz_arg) *sz_arg = 2;
if (sz_res) *sz_res = 2;
if (sz_iw) *sz_iw = 0;
if (sz_w) *sz_w = 0;
return 0;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
|
the_stack_data/193892263.c | #include <stdio.h>
int main(void)
{
int N, K;
scanf("%d %d", &N, &K);
int i;
int q[1000000];
for(i=1;i<=N;i++)
q[i-1] = i;
printf("<");
int ch = 0;
int r = 0, f = N;
while(ch < N-1)
{
for(i=0;i<K-1;i++)
q[f++] = q[r++];
printf("%d, ", q[r]);
ch++;
r++;
}
printf("%d", q[f-1]);
printf(">\n");
return 0;
}
|
the_stack_data/54825137.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int glub(char S1[32], char S2[32])
{
int i, lbig, lmin, maxlen;
char sbig[32], smin[32], s1[32], s2[32];
strcpy(s1, S1); // поэтому здесь копируем
strcpy(s2, S2); // и здесь
if (strlen(s1) > strlen(s2)){
strcpy(sbig, s1);
strcpy(smin, s2);
}
else {
strcpy(sbig, s2);
strcpy(smin, s1);
}
lmin = strlen(smin);
if (strstr(sbig, smin) != NULL)return lmin;
lbig = strlen(sbig);
for (i = 1, maxlen = 0; i<lmin; i++){
strcpy(s1, smin);
s1[i] = 0;
strcpy(s2, sbig + lbig - i);
if (strcmp(s1, s2) == 0)maxlen = i;
strcpy(s1, sbig);
s1[i] = 0;
strcpy(s2, smin + lmin - i);
if (strcmp(s1, s2) == 0)maxlen = i;
}
return maxlen;
}
int perebor(char sl[10][32], int n, char ch[10][32], int g)
{
int i, G, Gcur;
char s[32];
if (g == n){
for (i = 0, G = 0; i<g - 1; i++)
G += glub(ch[i], ch[i + 1]);
return G;
}
for (i = 0, G = 0; i<n; i++){
if (!strlen(sl[i]))continue;
strcpy(s, sl[i]);
strcpy(sl[i], "");
strcpy(ch[g], s);
Gcur = perebor(sl, n, ch, g + 1);
if (Gcur > G)G = Gcur;
strcpy(sl[i], s);
}
return G;
}
int main()
{
int n, i, j, maxlen;
char s[32];
char sl[10][32], ch[10][32];
scanf("%d", &n);
for (i = 0, maxlen = 0; i<n; i++){
scanf("%s", &s);
maxlen += strlen(s);
strcpy(sl[i], s);
strcpy(ch[i], "");
}
printf("%d", maxlen - perebor(sl, n, ch, 0));
} |
the_stack_data/70450140.c | #define _GNU_SOURCE
#define _LARGEFILE64_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <endian.h>
#include <linux/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#define B 1048576
uint64_t init_magic=0x0000420281861253;
uint32_t request_magic=0x25609513;
uint32_t reply_magic=0x67446698;
int fd=-1;
char rbuf[B]={'\0'};
int s,s2;
struct sockaddr_in my_addr;
void err(char *m){fprintf(stderr,m);if(fd!=-1){close(fd);}exit(1);}
#define E(x) if(-1==x){err(strerror(errno));}
void w(void *b,size_t l){int i; for(i=0;i<l;i+=write(fd,b+i,l-i));}
void r(void *b,size_t l){int i; for(i=0;i<l;i+=read(fd,b+i,l-i));}
void W(void *b,size_t l){int i; for(i=0;i<l;i+=write(s2,b+i,l-i));}
void R(void *b,size_t l){int i=0; while(i<l){ int j=read(s2,b+i,l-i); if(j==0){exit(0);} i+=j;}}
void in4(uint32_t *x){*x=be32toh(*x);}
void in8(uint64_t *x){*x=be64toh(*x);}
int64_t clip(int64_t x){return x > B ? B : x;}
int main(int argc, char **argv){
if(argc<2){err("Need a file to serve\n");}
if(argc<3){err("Need a port\n");}
fd=open(argv[1],O_RDWR|O_SYNC); if(-1==fd){err("Couldn't open file\n");};
int port=atoi(argv[2]);
s = socket(AF_INET, SOCK_STREAM, 0);
E(s);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(&(my_addr.sin_zero), '\0', 8);
E(bind(s, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)));
E(listen(s,0));
s2 = accept(s,NULL,NULL);
E(s2);
int y=1,n=0;
E(setsockopt(s2, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(y) ));
E(setsockopt(s2, IPPROTO_TCP, TCP_NODELAY, &y, sizeof(y) ));
off64_t size=lseek64(fd,0,SEEK_END);__be64 wsz=htobe64(size);
__be64 wmag=htobe64(init_magic); __be32 rmag=htobe32(reply_magic);
W("NBDMAGIC",8);W(&wmag,8);W(&wsz,8); int i; for(i=0;i<128;i++){W("\0",1);}
while(1){
uint32_t m,t,l;char h[8];uint64_t f;
R(&m,4);R(&t,4);R(h,8);R(&f,8);R(&l,4);
in4(&m);in4(&t);in8(&f);in4(&l);
if(m == request_magic && f < (uint64_t)1<<63 && l+f <= size){
int64_t ll=l;
lseek64(fd,f,SEEK_SET);
if(t==0){
E( setsockopt(s2, IPPROTO_TCP, TCP_CORK, &y, sizeof(y) ));
W(&rmag,4);W("\0\0\0\0",4);W(h,8);
for(;ll>0;ll-=B){r(rbuf,clip(ll));W(rbuf,clip(ll));}
E( setsockopt(s2, IPPROTO_TCP, TCP_CORK, &n, sizeof(y) ));
} else if(t==1){
for(;ll>0;ll-=B){R(rbuf,clip(ll));w(rbuf,clip(ll));}
W(&rmag,4);W("\0\0\0\0",4);W(h,8);
}
} else {
W(&rmag,4);W("\1\0\0\0",4);W(h,8);
}
}
return 0;
}
|
the_stack_data/2568.c | #include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <pthread.h>
#define SIZE 100000
struct argument{
int v[SIZE];
int u[SIZE];
int start_pos;
int end_pos;
int ret;
};
void *compute(void *arg){
struct argument *a = (struct argument *)arg;
a->ret = 0;
for(int i = a->start_pos; i < a->end_pos; i++){
a->ret += a->u[i] * a->v[i];
}
return NULL;
}
int main(int argc, char *argv[]) {
srand(time(0));
pthread_t tids[4];
int v[SIZE];
int u[SIZE];
int dotproduct = 0;
int thread_dotproduct = 0;
struct argument a[4];
for (int i = 0; i < SIZE; i++) {
v[i] = rand() % 1000 - 500;
u[i] = rand() % 1000 - 500;
for(int j = 0; j < 4; j++){
a[j].v[i] = v[i];
a[j].u[i] = u[i];
}
dotproduct += u[i] * v[i];
}
for(int i = 0; i < 4; i++){
tids[i] = i;
a[i].start_pos = (SIZE * i)/4;
a[i].end_pos = (SIZE * (i + 1))/4;
pthread_create(&tids[i], NULL, compute, (void *)&a[i]);
}
for(int i = 0; i < 4; i++){
pthread_join(tids[i], NULL);
}
for(int i = 0; i < 4; i++){
thread_dotproduct += a[i].ret;
}
printf("Ground truth dot product: %d\n", dotproduct);
// TODO: Implement your thread solution here
printf("Test with 4 threads\n");
printf("Thread dot product: %d\n", thread_dotproduct);
return 0;
} |
the_stack_data/192331934.c | #include <stdio.h>
#include <stdlib.h>
void parouimpar()
{
int A;
scanf("%d", &A);
if(A % 2 == 0)
{
printf("par");
}
else
{
printf("impar");
}
}
int main()
{
parouimpar();
return 0;
}
|
the_stack_data/57950447.c | #include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
/* Delete the database file if it exists */
remove("test.db");
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stdout, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "CREATE TABLE COMPANY(" \
"ID INT PRIMARY KEY NOT NULL," \
"NAME TEXT NOT NULL," \
"AGE INT NOT NULL," \
"ADDRESS CHAR(50)," \
"SALARY REAL );";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Table created successfully\n");
}
sqlite3_close(db);
return 0;
} |
the_stack_data/82723.c | #include <stdio.h>
int main(int argc, char const *argv[])
{
for (int i = 0; i < 10; i++)
{
printf("%d\n", i);
if (i == 7)
{
break;
}
}
return 0;
}
|
the_stack_data/115765303.c | const char http_http[8] =
/* "http://" */
{0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, };
const char http_200[5] =
/* "200 " */
{0x32, 0x30, 0x30, 0x20, };
const char http_301[5] =
/* "301 " */
{0x33, 0x30, 0x31, 0x20, };
const char http_302[5] =
/* "302 " */
{0x33, 0x30, 0x32, 0x20, };
const char http_get[5] =
/* "GET " */
{0x47, 0x45, 0x54, 0x20, };
const char http_10[9] =
/* "HTTP/1.0" */
{0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x30, };
const char http_11[9] =
/* "HTTP/1.1" */
{0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, };
const char http_content_type[15] =
/* "content-type: " */
{0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3a, 0x20, };
const char http_location[11] =
/* "location: " */
{0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, };
const char http_host[7] =
/* "Host: " */
{0x48, 0x6f, 0x73, 0x74, 0x3a, 0x20, };
const char http_crnl[3] =
/* "\r\n" */
{0xd, 0xa, };
const char http_index_htm[11] =
/* "/index.htm" */
{0x2f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x68, 0x74, 0x6d, };
const char http_index_html[12] =
/* "/index.html" */
{0x2f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x68, 0x74, 0x6d, 0x6c, };
const char http_404_html[10] =
/* "/404.html" */
{0x2f, 0x34, 0x30, 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, };
const char http_referer[9] =
/* "Referer:" */
{0x52, 0x65, 0x66, 0x65, 0x72, 0x65, 0x72, 0x3a, };
const char http_header_200[85] =
/* "HTTP/1.0 200 OK\r\nServer: Contiki/2.6 http://www.contiki-os.org/\r\nConnection: close\r\n" */
{0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x30, 0x20, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0xd, 0xa, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x69, 0x6b, 0x69, 0x2f, 0x32, 0x2e, 0x36, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x69, 0x6b, 0x69, 0x2d, 0x6f, 0x73, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0xd, 0xa, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0xd, 0xa, };
const char http_header_404[92] =
/* "HTTP/1.0 404 Not found\r\nServer: Contiki/2.6 http://www.contiki-os.org/\r\nConnection: close\r\n" */
{0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x30, 0x20, 0x34, 0x30, 0x34, 0x20, 0x4e, 0x6f, 0x74, 0x20, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0xd, 0xa, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x69, 0x6b, 0x69, 0x2f, 0x32, 0x2e, 0x36, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x69, 0x6b, 0x69, 0x2d, 0x6f, 0x73, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0xd, 0xa, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0xd, 0xa, };
const char http_content_type_plain[29] =
/* "Content-type: text/plain\r\n\r\n" */
{0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c, 0x61, 0x69, 0x6e, 0xd, 0xa, 0xd, 0xa, };
const char http_content_type_html[28] =
/* "Content-type: text/html\r\n\r\n" */
{0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0xd, 0xa, 0xd, 0xa, };
const char http_content_type_css [27] =
/* "Content-type: text/css\r\n\r\n" */
{0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x63, 0x73, 0x73, 0xd, 0xa, 0xd, 0xa, };
const char http_content_type_text[28] =
/* "Content-type: text/text\r\n\r\n" */
{0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x74, 0x65, 0x78, 0x74, 0xd, 0xa, 0xd, 0xa, };
const char http_content_type_png [28] =
/* "Content-type: image/png\r\n\r\n" */
{0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0xd, 0xa, 0xd, 0xa, };
const char http_content_type_gif [28] =
/* "Content-type: image/gif\r\n\r\n" */
{0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x67, 0x69, 0x66, 0xd, 0xa, 0xd, 0xa, };
const char http_content_type_jpg [29] =
/* "Content-type: image/jpeg\r\n\r\n" */
{0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x6a, 0x70, 0x65, 0x67, 0xd, 0xa, 0xd, 0xa, };
const char http_content_type_binary[43] =
/* "Content-type: application/octet-stream\r\n\r\n" */
{0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x6f, 0x63, 0x74, 0x65, 0x74, 0x2d, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0xd, 0xa, 0xd, 0xa, };
const char http_html[6] =
/* ".html" */
{0x2e, 0x68, 0x74, 0x6d, 0x6c, };
const char http_shtml[7] =
/* ".shtml" */
{0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, };
const char http_htm[5] =
/* ".htm" */
{0x2e, 0x68, 0x74, 0x6d, };
const char http_css[5] =
/* ".css" */
{0x2e, 0x63, 0x73, 0x73, };
const char http_png[5] =
/* ".png" */
{0x2e, 0x70, 0x6e, 0x67, };
const char http_gif[5] =
/* ".gif" */
{0x2e, 0x67, 0x69, 0x66, };
const char http_jpg[5] =
/* ".jpg" */
{0x2e, 0x6a, 0x70, 0x67, };
const char http_text[6] =
/* ".text" */
{0x2e, 0x74, 0x65, 0x78, 0x74, };
const char http_txt[5] =
/* ".txt" */
{0x2e, 0x74, 0x78, 0x74, };
|
the_stack_data/122016721.c | # include <stdio.h>
# include <ctype.h>
int main(){
int i=0,c1=0,c2=0,c3=0,c4=0,c5=0,c6=0;
char ch,str[100];
printf("Input A String: ");
ch=getchar();
while(ch!='\n'){
str[i]=ch;
i=i+1;
ch=getchar();
}
str[i]='\0';
printf("%s\n",str);
for(i=0;str[i]!='\0';i++){
if(isalpha(str[i])){
c1=c1+1;
if(isupper(str[i]))
c2=c2+1;
else
c3=c3+1;
}
else if(isdigit(str[i]))
c4=c4+1;
else if(str[i]==' ')
c5=c5+1;
else
c6=c6+1;
}
printf("Total number of alphabets: %d\n",c1);
printf("Number of uppercase alphabets: %d\n",c2);
printf("Number of lowercase alphabets: %d\n",c3);
printf("Number of digits: %d\n",c4);
printf("Number of punctuation mark: %d\n",c6);
printf("Number of spaces: %d\n",c5);
return 0;
} |
the_stack_data/45523.c | #include <stdio.h>
const char * TEXT = "#include <stdio.h>%c%cconst char * TEXT = %c%s%c;%c%cint main(){%c%c//Prints own source code and injects newlines(10), horizontal tabs(9) and apostrophes(34)%c%cprintf(TEXT, 10, 10, 34, TEXT, 34, 10, 10, 10, 9, 10, 9, 10, 9, 10, 10);%c%creturn 0;%c}%c";
int main(){
//Prints own source code and injects newlines(10), horizontal tabs(9) and apostrophes(34)
printf(TEXT, 10, 10, 34, TEXT, 34, 10, 10, 10, 9, 10, 9, 10, 9, 10, 10);
return 0;
}
|
the_stack_data/62265.c | /* Verify that mergeable strings are used in the CU DIE. */
/* { dg-do compile } */
/* { dg-require-effective-target string_merging } */
/* { dg-options "-O2 -gdwarf-2 -dA" } */
/* { dg-final { scan-assembler "DW_AT_producer: \"GNU C" } } */
/* { dg-final { scan-assembler-not "GNU C\[^\\n\\r\]*DW_AT_producer" } } */
void func (void)
{
}
|
the_stack_data/642799.c | //Palette created using Mollusk's PAGfxConverter
const unsigned short title_bg3_Pal[244] __attribute__ ((aligned (4))) = {
64543, 32768, 33792, 34816, 35840, 37888, 37889, 38913, 38914, 39938, 36864, 39936, 40961, 41985, 41986, 43009, 44033, 44034, 47137, 48163, 45058, 44035, 45060, 43012, 46084, 45059, 46082, 50211, 49189, 48165, 49221, 48196, 48195, 46115, 46114, 41987, 39937, 40962, 42019, 40963, 41988, 43045, 39939, 45061, 44037, 44036, 43044, 44069, 36865, 47144, 46116, 50217, 44065, 46145, 46113, 40964, 40994, 38912, 46117, 46086, 45091, 49185, 35841, 43010, 43011, 51235, 52260, 54371, 45092, 49190, 42018, 40995, 45093, 46119, 45090, 46083, 47143, 44070, 52290, 55397, 53349, 51299, 50243, 50241, 38915, 37890, 52357, 50245, 46121, 48173, 46148, 50308, 48193, 43013, 45099, 44066, 43042, 50247, 56452, 49281, 52386, 39941, 52263, 46154, 40960, 42017, 44068, 44067, 53380, 52327, 50249, 48171, 43041, 51240, 46147, 41991, 53353, 48199, 48200, 46150, 47236, 52452, 53383, 44073, 51301, 56486, 52455, 54503, 50406, 50311, 46184, 39971, 50372, 52359, 55432, 45103, 49231, 45101, 54472, 39970, 43043, 44101, 47180, 41993, 53416, 40993, 38945, 54500, 49229, 47235, 44064, 41984, 39969, 44032, 51304, 38946, 50251, 50219, 48203, 47183, 48210, 49242, 49239, 50290, 56580, 39968, 50314, 52394, 51307, 46131, 46134, 41995, 48175, 43029, 43025, 47274, 40992, 50317, 51405, 53389, 51243, 44098, 38947, 56553, 53387, 38944, 42049, 46129, 43073, 43008, 55467, 46140, 41998, 47158, 43038, 56646, 42050, 48176, 48179, 47161, 56619, 54510, 54569, 52399, 42016, 39957, 49236, 51310, 42010, 49247, 44102, 50288, 51346, 52405, 53483, 42052, 54484, 55601, 54481, 49245, 58755, 55489, 58664, 48241, 40001, 57772, 60995, 55649, 44162, 46143, 47164, 47167, 46163, 46160, 55629, 46401, 59891, 57745, 58627, 43040, 43175, 35844, 37921, 37920};
|
the_stack_data/73575878.c | //===-- CBackend.cpp - Library for converting LLVM code to C
//----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===------------------------------------------------------------------------------===//
//
// This code tests to see that the CBE will pass a structure into a function
// correctly. *TW
//===------------------------------------------------------------------------------===//
int k = 0;
struct test {
int i;
float f;
};
void funct(struct test example) { k = example.i; }
int main() {
struct test example;
example.i = 6;
example.f = 6.0;
funct(example);
return k;
}
|
the_stack_data/162642958.c | // RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -o - %s | FileCheck %s
// PR14355: don't crash
// Keep this test in its own file because CodeGenTypes has global state.
// CHECK: define{{.*}} void @test10_foo({}* %p1.coerce) [[NUW:#[0-9]+]] {
struct test10_B;
typedef struct test10_B test10_F3(double);
void test10_foo(test10_F3 p1);
struct test10_B test10_b(double);
void test10_bar() {
test10_foo(test10_b);
}
struct test10_B {};
void test10_foo(test10_F3 p1)
{
p1(0.0);
}
// CHECK: attributes [[NUW]] = { noinline nounwind{{.*}} }
|
the_stack_data/124958.c | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("Oi, mundo!\n");
exit(EXIT_SUCCESS);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.