file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/36075071.c
/************************************************************************ * 1.9 Feladat * * Olvass be a billentyűzetről három számot (x, y, z) * * Tárolja el és írassa ki 3*x – y*z értékét * * Újabb változó felhasználása nélkül írassa ki a három szám szorzatát * ************************************************************************/ #include <stdio.h> int main() { int x, y, z; scanf("%d %d %d", &x, &y, &z); int result=3*x-y*z; printf("3*x-y*z erteke: %d\n", result); printf("a harom szam szorzata: %d\n", x*y*z); return 0; }
the_stack_data/98574606.c
#include <stdio.h> int gv; int gc = 2; int main() { int lv; int lc = 2; gv = 2; lv = 2; gv = lc + gv + gc + lv; lv = lc * gv * gc * lv; printf("%d\n", gv); printf("%d\n", lv); gv = lc + ((gv + gc) * lv); lv = (lc + (gv + (gc + (lv + (lc + (gv + (gc + (lv + lc)))))))); printf("%d\n", gv); printf("%d\n", lv); return 0; }
the_stack_data/28262631.c
// RUN: %clang_cc1 %s -emit-llvm -g -o /dev/null typedef long unsigned int size_t; typedef unsigned short int uint16_t; typedef unsigned int uint32_t; typedef unsigned long int uint64_t; typedef uint16_t Elf64_Half; typedef uint32_t Elf64_Word; typedef uint64_t Elf64_Xword; typedef uint64_t Elf64_Addr; typedef uint64_t Elf64_Off; typedef struct { Elf64_Word p_type; Elf64_Off p_offset; Elf64_Addr p_vaddr; Elf64_Xword p_align; } Elf64_Phdr; struct dl_phdr_info { const char *dlpi_name; const Elf64_Phdr *dlpi_phdr; Elf64_Half dlpi_phnum; unsigned long long int dlpi_adds; }; typedef unsigned _Unwind_Ptr; struct object { union { const struct dwarf_fde *single; struct dwarf_fde **array; struct fde_vector *sort; } u; union { struct { } b; } s; struct object *next; }; typedef int sword; typedef unsigned int uword; struct dwarf_fde { uword length; sword CIE_delta; unsigned char pc_begin[]; }; typedef struct dwarf_fde fde; struct unw_eh_callback_data { const fde *ret; struct frame_hdr_cache_element *link; } frame_hdr_cache[8]; _Unwind_Ptr base_from_cb_data (struct unw_eh_callback_data *data) { } void _Unwind_IteratePhdrCallback (struct dl_phdr_info *info, size_t size, void *ptr) { const unsigned char *p; const struct unw_eh_frame_hdr *hdr; struct object ob; }
the_stack_data/212644368.c
#include <stdio.h> #include <stdlib.h> int main(){ int n; scanf("%d", &n); printf("Antecessor de %d eh: %d\nSucessor de %d eh: %d\n", n, (n - 1), n, (n + 1)); return 0; }
the_stack_data/557216.c
#include<math.h> #include<stdio.h> double f(double x) { return x*x+4*sin(x)+7; } main() { int n; double x,dx; scanf("%d %lf %lf",&n,&x,&dx); while(n--) { printf("%lf %lf %lf\n",dx,(f(x+dx) - f(x)) / dx,(f(x+dx) - f(x- dx)) /(2 *dx)); dx/=2; } }
the_stack_data/20709.c
/* * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <limits.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> /* * Convert a string to an unsigned long integer. * * Assumes that the upper and lower case * alphabets and digits are each contiguous. */ unsigned long strtoul(const char * __restrict nptr, char ** __restrict endptr, int base) { const char *s; unsigned long acc; char c; unsigned long cutoff; int neg, any, cutlim; /* * See strtol for comments as to the logic used. */ s = nptr; do { c = *s++; } while (isspace((unsigned char)c)); if (c == '-') { neg = 1; c = *s++; } else { neg = 0; if (c == '+') c = *s++; } if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X') && ((s[1] >= '0' && s[1] <= '9') || (s[1] >= 'A' && s[1] <= 'F') || (s[1] >= 'a' && s[1] <= 'f'))) { c = s[1]; s += 2; base = 16; } if (base == 0) base = c == '0' ? 8 : 10; acc = any = 0; if (base < 2 || base > 36) goto noconv; cutoff = ULONG_MAX / base; cutlim = ULONG_MAX % base; for ( ; ; c = *s++) { if (c >= '0' && c <= '9') c -= '0'; else if (c >= 'A' && c <= 'Z') c -= 'A' - 10; else if (c >= 'a' && c <= 'z') c -= 'a' - 10; else break; if (c >= base) break; if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) any = -1; else { any = 1; acc *= base; acc += c; } } if (any < 0) { acc = ULONG_MAX; errno = ERANGE; } else if (!any) { noconv: errno = EINVAL; } else if (neg) acc = -acc; if (endptr != NULL) *endptr = (char *)(any ? s - 1 : nptr); return (acc); }
the_stack_data/125139559.c
//Classification: p/DAM/NP/gS/D(v)/fr/rp //Written by: Sergey Pomelov //Reviewed by: Igor Eremeev //Comment: #include <stdio.h> int *func(void) { static int q = 1; int *p = &q; return p; }; int a; int main(void) { int i; for(i=1; i<100; i++) { a = *func(); } printf("%d",a); return 0; }
the_stack_data/21481.c
#include <stdio.h> void merge(int* nums1, int m, int* nums2, int n) { int i, j, t, pos = 0; for (i = 0; i < n; i++) { printf("pos is %i\n", pos); for (j = pos; j < m+i; j++) if (nums1[j] > nums2[i]) { for (t = m+i; t > j; t--) nums1[t] = nums1[t-1]; break; } nums1[j] = nums2[i]; printf("nums1[%i] is %i\n", j, nums2[i]); pos = j + 1; } } int main(void) { int i; int nums1[6] = {1, 2, 3, 0, 0, 0}; int nums2[3] = {2, 5, 6}; void merge(int*, int, int*, int); merge(nums1, 3, nums2, 3); for (i = 0; i < 6; i++) printf("%i\n", nums1[i]); return 0; }
the_stack_data/129130.c
/* * Copyright 2014 The Emscripten Authors. All rights reserved. * Emscripten is available under two separate licenses, the MIT license and the * University of Illinois/NCSA Open Source License. Both these licenses can be * found in the LICENSE file. */ #include <locale.h> #include <stdio.h> int main() { // Test basic functions from classic locale. struct lconv* locale = localeconv(); printf("Testing locale information.\n"); printf("Decimal point: %s\n", locale->decimal_point); printf("Thousands separator: %s\n", locale->thousands_sep); printf("Grouping: %s\n", locale->grouping); printf("International currency symbol: %s\n", locale->int_curr_symbol); printf("Currency symbol: %s\n", locale->currency_symbol); printf("Money decimal point: %s\n", locale->mon_decimal_point); printf("Money thousands separator: %s\n", locale->mon_thousands_sep); printf("Money Grouping: %s\n", locale->mon_grouping); printf("Positive sign: %s\n", locale->positive_sign); printf("Negative sign: %s\n", locale->negative_sign); // If no runtime errors, assume the test passed. printf("Locale tests passed.\n"); return 0; }
the_stack_data/225142117.c
/*********************************************************** isbn.c -- ISBN番号 ***********************************************************/ #include <stdio.h> #include <stdlib.h> int main(void) { int i, c, d[11]; printf("ISBN book number: "); for (i = 1; i <= 10; i++) { c = getchar(); if (c >= '0' && c <= '9') d[i] = c - '0'; else if (i == 10 && (c == 'x' || c == 'X')) d[i] = 10; else return 1; } d[0] = 0; for (i = 1; i <= 10; i++) d[i] += d[i - 1]; for (i = 1; i <= 10; i++) d[i] += d[i - 1]; if (d[10] % 11 == 0) puts("Valid"); /* 有効な番号 */ else puts("Wrong"); /* 無効な番号 */ return 0; }
the_stack_data/143621.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strstr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpolonen <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/31 15:42:36 by tpolonen #+# #+# */ /* Updated: 2021/05/31 19:51:50 by tpolonen ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_strstr(char *str, char *to_find) { int index; int sub_index; index = 0; while (str[index] != '\0') { if (str[index] == to_find[0]) { sub_index = 1; while (str[index + sub_index] == to_find[sub_index]) sub_index++; if (to_find[sub_index] == '\0') return (str + index); } index++; } return (0); }
the_stack_data/164167.c
#include <string.h> #include <stdlib.h> #include <ctype.h> #undef strcpy #undef strncpy #undef strcat #undef strncat #undef strlen #undef strcmp #undef strncmp #undef strchr #undef strrchr #undef strspn #undef strcspn #undef strpbrk #undef strstr #undef strtok #undef memchr #undef memcmp #undef memset #undef memcpy #undef memmove #undef memchr char *strcpy(char *dst, const char *src) { __ESBMC_HIDE:; char *cp = dst; while((*cp++ = *src++)) ; return dst; } char *strncpy(char *dst, const char *src, size_t n) { __ESBMC_HIDE:; char *start = dst; while(n && (*dst++ = *src++)) n--; if(n) while(--n) *dst++ = '\0'; return start; } char *strcat(char *dst, const char *src) { __ESBMC_HIDE:; strcpy(dst + strlen(dst), src); return dst; } char *strncat(char *dst, const char *src, size_t n) { __ESBMC_HIDE:; char *start = dst; while(*dst++) ; dst--; while(n--) if(!(*dst++ = *src++)) return start; *dst = '\0'; return start; } size_t strlen(const char *s) { __ESBMC_HIDE:; size_t len = 0; while(s[len] != 0) len++; return len; } int strcmp(const char *p1, const char *p2) { __ESBMC_HIDE:; const unsigned char *s1 = (const unsigned char *)p1; const unsigned char *s2 = (const unsigned char *)p2; unsigned char c1, c2; do { c1 = (unsigned char)*s1++; c2 = (unsigned char)*s2++; if(c1 == '\0') return c1 - c2; } while(c1 == c2); return c1 - c2; } int strncmp(const char *s1, const char *s2, size_t n) { __ESBMC_HIDE:; size_t i = 0; unsigned char ch1, ch2; do { ch1 = s1[i]; ch2 = s2[i]; if(ch1 == ch2) { } else if(ch1 < ch2) return -1; else return 1; i++; } while(ch1 != 0 && ch2 != 0 && i < n); return 0; } char *strchr(const char *s, int ch) { __ESBMC_HIDE:; while(*s && *s != (char)ch) s++; if(*s == (char)ch) return (char *)s; return NULL; } char *strrchr(const char *s, int c) { __ESBMC_HIDE:; const char *found, *p; c = (unsigned char)c; /* Since strchr is fast, we use it rather than the obvious loop. */ if(c == '\0') return strchr(s, '\0'); found = NULL; while((p = strchr(s, c)) != NULL) { found = p; s = p + 1; } return (char *)found; } size_t strspn(const char *s, const char *accept) { __ESBMC_HIDE:; const char *p; const char *a; size_t count = 0; for(p = s; *p != '\0'; ++p) { for(a = accept; *a != '\0'; ++a) if(*p == *a) break; if(*a == '\0') return count; else ++count; } return count; } size_t strcspn(const char *s, const char *reject) { __ESBMC_HIDE:; size_t count = 0; while(*s != '\0') if(strchr(reject, *s++) == NULL) ++count; else return count; return count; } char *strpbrk(const char *s, const char *accept) { __ESBMC_HIDE:; while(*s != '\0') { const char *a = accept; while(*a != '\0') if(*a++ == *s) return (char *)s; ++s; } return NULL; } char *strstr(const char *str1, const char *str2) { __ESBMC_HIDE:; char *cp = (char *)str1; char *s1, *s2; if(!*str2) return (char *)str1; while(*cp) { s1 = cp; s2 = (char *)str2; while(*s1 && *s2 && !(*s1 - *s2)) s1++, s2++; if(!*s2) return cp; cp++; } return NULL; } char *strtok(char *str, const char *delim) { __ESBMC_HIDE:; static char *p = 0; if(str) p = str; else if(!p) return 0; str = p + strspn(p, delim); p = str + strcspn(str, delim); if(p == str) return p = 0; p = *p ? *p = 0, p + 1 : 0; return str; } char *strdup(const char *str) { __ESBMC_HIDE:; size_t bufsz; bufsz = (strlen(str) + 1); char *cpy = (char *)malloc(bufsz * sizeof(char)); if(cpy == ((void *)0)) return 0; strcpy(cpy, str); return cpy; } void *memcpy(void *dst, const void *src, size_t n) { __ESBMC_HIDE:; char *cdst = dst; const char *csrc = src; for(size_t i = 0; i < n; i++) cdst[i] = csrc[i]; return dst; } void *__memset_impl(void *s, int c, size_t n) { __ESBMC_HIDE:; char *sp = s; for(size_t i = 0; i < n; i++) sp[i] = c; return s; } void *memset(void *s, int c, size_t n) { __ESBMC_HIDE:; void *hax = &__memset_impl; (void)hax; return __ESBMC_memset(s, c, n); } void *memmove(void *dest, const void *src, size_t n) { __ESBMC_HIDE:; char *cdest = dest; const char *csrc = src; if(dest - src >= n) { for(size_t i = 0; i < n; i++) cdest[i] = csrc[i]; } else { for(size_t i = n; i > 0; i--) cdest[i - 1] = csrc[i - 1]; } return dest; } int memcmp(const void *s1, const void *s2, size_t n) { __ESBMC_HIDE:; int res = 0; const unsigned char *sc1 = s1, *sc2 = s2; for(; n != 0; n--) { res = (*sc1++) - (*sc2++); if(res != 0) return res; } return res; } void *memchr(const void *buf, int ch, size_t n) { while(n && (*(unsigned char *)buf != (unsigned char)ch)) { buf = (unsigned char *)buf + 1; n--; } return (n ? (void *)buf : NULL); }
the_stack_data/151706995.c
// RUN: %clang_cc1 -no-opaque-pointers %s -triple i386-unknown-unknown -Wno-strict-prototypes -emit-llvm -o - -verify | FileCheck %s int g(); int foo(int i) { return g(i); } int g(int i) { return g(i); } // rdar://6110827 typedef void T(void); void test3(T f) { f(); } void f0(void) {} // CHECK-LABEL: define{{.*}} void @f0() void f1(); void f2(void) { // CHECK: call void @f1() f1(1, 2, 3); } // CHECK-LABEL: define{{.*}} void @f1() void f1() {} // CHECK: define {{.*}} @f3{{\(\)|\(.*sret.*\)}} struct foo { int X, Y, Z; } f3(void) { while (1) {} } // PR4423 - This shouldn't crash in codegen void f4() {} void f5(void) { f4(42); } //expected-warning {{too many arguments}} // Qualifiers on parameter types shouldn't make a difference. static void f6(const float f, const float g) { } void f7(float f, float g) { f6(f, g); // CHECK: define{{.*}} void @f7(float{{.*}}, float{{.*}}) // CHECK: call void @f6(float{{.*}}, float{{.*}}) } // PR6911 - incomplete function types struct Incomplete; void f8_callback(struct Incomplete); void f8_user(void (*callback)(struct Incomplete)); void f8_test(void) { f8_user(&f8_callback); // CHECK-LABEL: define{{.*}} void @f8_test() // CHECK: call void @f8_user({{.*}}* noundef bitcast (void ()* @f8_callback to {{.*}}*)) // CHECK: declare void @f8_user({{.*}}* noundef) // CHECK: declare void @f8_callback() } // PR10204: don't crash static void test9_helper(void) {} void test9(void) { (void) test9_helper; }
the_stack_data/37636903.c
#include <stdio.h> int main() { int c = 0; for (int i = 0;i<10000000;i++){ c += i; } printf("%d\n",c); return 0; }
the_stack_data/11075215.c
#include <stdio.h> int main() { printf("Serial region.\n"); #pragma omp parallel for for (int i = 0; i < 20; i++) { printf("Hello %d\n", i); } printf("Serial region.\n"); }
the_stack_data/104828499.c
/* { dg-do compile } */ /* { dg-additional-options "-w" } */ int **dp; int sg; void z9(void) { int pz, oi, vz, yp, zi, hd, pw, gr, w9 = 0, j0 = -1, rb = &w9; int *lr; while (w9 < 1) { lr++; *lr = 1; if (*lr < 1) for (;;) if (pz && *lr) { ee: **dp = 0; } pz = zi = vz; if (j0 ^ (vz > 0)) continue; **dp = 1; while (**dp) if (++oi) { int mq = dp; j0 = 1; while (pw < 1) { if (++rb && mq) xq: hd = sg; ++pw; } sg = 0; while (!sg) { goto ee; while (++yp && gr++) { int i9, xa; while (++i9 && ++xa) fb: ; } } } } ++vz; if (zi > hd) goto xq; goto fb; }
the_stack_data/979246.c
/** ****************************************************************************** * @file stm32l1xx_ll_pwr.c * @author MCD Application Team * @brief PWR LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_ll_pwr.h" #include "stm32l1xx_ll_bus.h" /** @addtogroup STM32L1xx_LL_Driver * @{ */ #if defined(PWR) /** @defgroup PWR_LL PWR * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PWR_LL_Exported_Functions * @{ */ /** @addtogroup PWR_LL_EF_Init * @{ */ /** * @brief De-initialize the PWR registers to their default reset values. * @retval An ErrorStatus enumeration value: * - SUCCESS: PWR registers are de-initialized * - ERROR: not applicable */ ErrorStatus LL_PWR_DeInit(void) { /* Force reset of PWR clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_PWR); /* Release reset of PWR clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_PWR); return SUCCESS; } /** * @} */ /** * @} */ /** * @} */ #endif /* defined(PWR) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/12637664.c
/* -------------------------------------------------------------------------- reditor -- A very simple editor in Does not depend on libcurses, directly emits VT100 escapes on the terminal. -------------------------------------------------------------------------- */ #define REDITOR_VERSION "0.0.2" #ifdef __linux__ #define _POSIX_C_SOURCE 200809L #endif #include <termios.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <errno.h> #include <string.h> #include <ctype.h> #include <time.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/time.h> #include <unistd.h> #include <stdarg.h> #include <fcntl.h> #include <signal.h> /* Syntax highlight types */ #define HL_NORMAL 0 #define HL_NONPRINT 1 #define HL_COMMENT 2 /* Single line comment. */ #define HL_MLCOMMENT 3 /* Multi-line comment. */ #define HL_KEYWORD1 4 #define HL_KEYWORD2 5 #define HL_STRING 6 #define HL_NUMBER 7 #define HL_MATCH 8 /* Search match. */ #define HL_HIGHLIGHT_STRINGS (1<<0) #define HL_HIGHLIGHT_NUMBERS (1<<1) struct editorSyntax { char **filematch; char **keywords; char singleline_comment_start[2]; char multiline_comment_start[3]; char multiline_comment_end[3]; int flags; }; /* This structure represents a single line of the file we are editing. */ typedef struct erow { int idx; /* Row index in the file, zero-based. */ int size; /* Size of the row, excluding the null term. */ int rsize; /* Size of the rendered row. */ char *chars; /* Row content. */ char *render; /* Row content "rendered" for screen (for TABs). */ unsigned char *hl; /* Syntax highlight type for each character in render.*/ int hl_oc; /* Row had open comment at end in last syntax highlight check. */ } erow; typedef struct hlcolor { int r,g,b; } hlcolor; struct editorConfig { int cx,cy; /* Cursor x and y position in characters */ int rowoff; /* Offset of row displayed. */ int coloff; /* Offset of column displayed. */ int screenrows; /* Number of rows that we can show */ int screencols; /* Number of cols that we can show */ int numrows; /* Number of rows */ int rawmode; /* Is terminal raw mode enabled? */ erow *row; /* Rows */ int dirty; /* File modified but not saved. */ char *filename; /* Currently open filename */ char statusmsg[80]; time_t statusmsg_time; struct editorSyntax *syntax; /* Current syntax highlight, or NULL. */ }; static struct editorConfig E; enum KEY_ACTION{ KEY_NULL = 0, /* NULL */ CTRL_C = 3, /* Ctrl-c */ CTRL_D = 4, /* Ctrl-d */ CTRL_F = 6, /* Ctrl-f */ CTRL_H = 8, /* Ctrl-h */ TAB = 9, /* Tab */ CTRL_L = 12, /* Ctrl+l */ ENTER = 13, /* Enter */ CTRL_Q = 17, /* Ctrl-q */ CTRL_S = 19, /* Ctrl-s */ CTRL_U = 21, /* Ctrl-u */ ESC = 27, /* Escape */ BACKSPACE = 127, /* Backspace */ /* The following are just soft codes, not really reported by the * terminal directly. */ ARROW_LEFT = 1000, ARROW_RIGHT, ARROW_UP, ARROW_DOWN, DEL_KEY, HOME_KEY, END_KEY, PAGE_UP, PAGE_DOWN }; void editorSetStatusMessage(const char *fmt, ...); /* =========================== Syntax highlights DB ========================= * * In order to add a new syntax, define two arrays with a list of file name * matches and keywords. The file name matches are used in order to match * a given syntax with a given file name: if a match pattern starts with a * dot, it is matched as the last past of the filename, for example ".c". * Otherwise the pattern is just searched inside the filename, like "Makefile"). * * The list of keywords to highlight is just a list of words, however if they * a trailing '|' character is added at the end, they are highlighted in * a different color, so that you can have two different sets of keywords. * * Finally add a stanza in the HLDB global variable with two two arrays * of strings, and a set of flags in order to enable highlighting of * comments and numbers. * * The characters for single and multi line comments must be exactly two * and must be provided as well (see the C language example). * * There is no support to highlight patterns currently. */ /* C / C++ */ char *C_HL_extensions[] = {".c",".h",".cpp",".hpp",".cc",NULL}; char *C_HL_keywords[] = { /* C Keywords */ "auto","break","case","continue","default","do","else","enum", "extern","for","goto","if","register","return","sizeof","static", "struct","switch","typedef","union","volatile","while","NULL", /* C++ Keywords */ "alignas","alignof","and","and_eq","asm","bitand","bitor","class", "compl","constexpr","const_cast","deltype","delete","dynamic_cast", "explicit","export","false","friend","inline","mutable","namespace", "new","noexcept","not","not_eq","nullptr","operator","or","or_eq", "private","protected","public","reinterpret_cast","static_assert", "static_cast","template","this","thread_local","throw","true","try", "typeid","typename","virtual","xor","xor_eq", /* C types */ "int|","long|","double|","float|","char|","unsigned|","signed|", "void|","short|","auto|","const|","bool|",NULL }; char *Python_HL_extensions[] = {".py",NULL}; char *Python_HL_keywords[] = { // python Keywords "and","as","assert" ,"break","class","continue" ,"def","del","elif", "else", "except","False","finally", "for","from","global", "if", "import" ,"is" ,"lambda" ,"None" ,"nonlocal" ,"not","or" ,"pass" ,"raise","return","True","try","while","with","yield", // python types "str|","int|","float|","char|","complex|","list|", "tuple|","range|","dict|","set|","bool|", "frozenset|", "bytes|", "bytearray|", "memoryview|",NULL }; /* Here we define an array of syntax highlights by extensions, keywords, * comments delimiters and flags. */ struct editorSyntax HLDB[] = { { /* C / C++ */ C_HL_extensions, C_HL_keywords, /* python */ //Python_HL_extensions, //Python_HL_keywords, "//","/*","*/", HL_HIGHLIGHT_STRINGS | HL_HIGHLIGHT_NUMBERS } }; #define HLDB_ENTRIES (sizeof(HLDB)/sizeof(HLDB[3])) /* ======================= Low level terminal handling ====================== */ static struct termios orig_termios; /* In order to restore at exit.*/ void disableRawMode(int fd) { /* Don't even check the return value as it's too late. */ if (E.rawmode) { tcsetattr(fd,TCSAFLUSH,&orig_termios); E.rawmode = 0; } } /* Called at exit to avoid remaining in raw mode. */ void editorAtExit(void) { disableRawMode(STDIN_FILENO); } /* Raw mode: 1960 magic shit. */ int enableRawMode(int fd) { struct termios raw; if (E.rawmode) return 0; /* Already enabled. */ if (!isatty(STDIN_FILENO)) goto fatal; atexit(editorAtExit); if (tcgetattr(fd,&orig_termios) == -1) goto fatal; raw = orig_termios; /* modify the original mode */ /* input modes: no break, no CR to NL, no parity check, no strip char, * no start/stop output control. */ raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); /* output modes - disable post processing */ raw.c_oflag &= ~(OPOST); /* control modes - set 8 bit chars */ raw.c_cflag |= (CS8); /* local modes - choing off, canonical off, no extended functions, * no signal chars (^Z,^C) */ raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); /* control chars - set return condition: min number of bytes and timer. */ raw.c_cc[VMIN] = 0; /* Return each byte, or zero for timeout. */ raw.c_cc[VTIME] = 1; /* 100 ms timeout (unit is tens of second). */ /* put terminal in raw mode after flushing */ if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal; E.rawmode = 1; return 0; fatal: errno = ENOTTY; return -1; } /* Read a key from the terminal put in raw mode, trying to handle * escape sequences. */ int editorReadKey(int fd) { int nread; char c, seq[3]; while ((nread = read(fd,&c,1)) == 0); if (nread == -1) exit(1); while(1) { switch(c) { case ESC: /* escape sequence */ /* If this is just an ESC, we'll timeout here. */ if (read(fd,seq,1) == 0) return ESC; if (read(fd,seq+1,1) == 0) return ESC; /* ESC [ sequences. */ if (seq[0] == '[') { if (seq[1] >= '0' && seq[1] <= '9') { /* Extended escape, read additional byte. */ if (read(fd,seq+2,1) == 0) return ESC; if (seq[2] == '~') { switch(seq[1]) { case '3': return DEL_KEY; case '5': return PAGE_UP; case '6': return PAGE_DOWN; } } } else { switch(seq[1]) { case 'A': return ARROW_UP; case 'B': return ARROW_DOWN; case 'C': return ARROW_RIGHT; case 'D': return ARROW_LEFT; case 'H': return HOME_KEY; case 'F': return END_KEY; } } } /* ESC O sequences. */ else if (seq[0] == 'O') { switch(seq[1]) { case 'H': return HOME_KEY; case 'F': return END_KEY; } } break; default: return c; } } } /* Use the ESC [6n escape sequence to query the horizontal cursor position * and return it. On error -1 is returned, on success the position of the * cursor is stored at *rows and *cols and 0 is returned. */ int getCursorPosition(int ifd, int ofd, int *rows, int *cols) { char buf[32]; unsigned int i = 0; /* Report cursor location */ if (write(ofd, "\x1b[6n", 4) != 4) return -1; /* Read the response: ESC [ rows ; cols R */ while (i < sizeof(buf)-1) { if (read(ifd,buf+i,1) != 1) break; if (buf[i] == 'R') break; i++; } buf[i] = '\0'; /* Parse it. */ if (buf[0] != ESC || buf[1] != '[') return -1; if (sscanf(buf+2,"%d;%d",rows,cols) != 2) return -1; return 0; } /* Try to get the number of columns in the current terminal. If the ioctl() * call fails the function will try to query the terminal itself. * Returns 0 on success, -1 on error. */ int getWindowSize(int ifd, int ofd, int *rows, int *cols) { struct winsize ws; if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { /* ioctl() failed. Try to query the terminal itself. */ int orig_row, orig_col, retval; /* Get the initial position so we can restore it later. */ retval = getCursorPosition(ifd,ofd,&orig_row,&orig_col); if (retval == -1) goto failed; /* Go to right/bottom margin and get position. */ if (write(ofd,"\x1b[999C\x1b[999B",12) != 12) goto failed; retval = getCursorPosition(ifd,ofd,rows,cols); if (retval == -1) goto failed; /* Restore position. */ char seq[32]; snprintf(seq,32,"\x1b[%d;%dH",orig_row,orig_col); if (write(ofd,seq,strlen(seq)) == -1) { /* Can't recover... */ } return 0; } else { *cols = ws.ws_col; *rows = ws.ws_row; return 0; } failed: return -1; } /* ====================== Syntax highlight color scheme ==================== */ int is_separator(int c) { return c == '\0' || isspace(c) || strchr(",.()+-/*=~%[];",c) != NULL; } /* Return true if the specified row last char is part of a multi line comment * that starts at this row or at one before, and does not end at the end * of the row but spawns to the next row. */ int editorRowHasOpenComment(erow *row) { if (row->hl && row->rsize && row->hl[row->rsize-1] == HL_MLCOMMENT && (row->rsize < 2 || (row->render[row->rsize-2] != '*' || row->render[row->rsize-1] != '/'))) return 1; return 0; } /* Set every byte of row->hl (that corresponds to every character in the line) * to the right syntax highlight type (HL_* defines). */ void editorUpdateSyntax(erow *row) { row->hl = realloc(row->hl,row->rsize); memset(row->hl,HL_NORMAL,row->rsize); if (E.syntax == NULL) return; /* No syntax, everything is HL_NORMAL. */ int i, prev_sep, in_string, in_comment; char *p; char **keywords = E.syntax->keywords; char *scs = E.syntax->singleline_comment_start; char *mcs = E.syntax->multiline_comment_start; char *mce = E.syntax->multiline_comment_end; /* Point to the first non-space char. */ p = row->render; i = 0; /* Current char offset */ while(*p && isspace(*p)) { p++; i++; } prev_sep = 1; /* Tell the parser if 'i' points to start of word. */ in_string = 0; /* Are we inside "" or '' ? */ in_comment = 0; /* Are we inside multi-line comment? */ /* If the previous line has an open comment, this line starts * with an open comment state. */ if (row->idx > 0 && editorRowHasOpenComment(&E.row[row->idx-1])) in_comment = 1; while(*p) { /* Handle // comments. */ if (prev_sep && *p == scs[0] && *(p+1) == scs[1]) { /* From here to end is a comment */ memset(row->hl+i,HL_COMMENT,row->size-i); return; } /* Handle multi line comments. */ if (in_comment) { row->hl[i] = HL_MLCOMMENT; if (*p == mce[0] && *(p+1) == mce[1]) { row->hl[i+1] = HL_MLCOMMENT; p += 2; i += 2; in_comment = 0; prev_sep = 1; continue; } else { prev_sep = 0; p++; i++; continue; } } else if (*p == mcs[0] && *(p+1) == mcs[1]) { row->hl[i] = HL_MLCOMMENT; row->hl[i+1] = HL_MLCOMMENT; p += 2; i += 2; in_comment = 1; prev_sep = 0; continue; } /* Handle "" and '' */ if (in_string) { row->hl[i] = HL_STRING; if (*p == '\\') { row->hl[i+1] = HL_STRING; p += 2; i += 2; prev_sep = 0; continue; } if (*p == in_string) in_string = 0; p++; i++; continue; } else { if (*p == '"' || *p == '\'') { in_string = *p; row->hl[i] = HL_STRING; p++; i++; prev_sep = 0; continue; } } /* Handle non printable chars. */ if (!isprint(*p)) { row->hl[i] = HL_NONPRINT; p++; i++; prev_sep = 0; continue; } /* Handle numbers */ if ((isdigit(*p) && (prev_sep || row->hl[i-1] == HL_NUMBER)) || (*p == '.' && i >0 && row->hl[i-1] == HL_NUMBER)) { row->hl[i] = HL_NUMBER; p++; i++; prev_sep = 0; continue; } /* Handle keywords and lib calls */ if (prev_sep) { int j; for (j = 0; keywords[j]; j++) { int klen = strlen(keywords[j]); int kw2 = keywords[j][klen-1] == '|'; if (kw2) klen--; if (!memcmp(p,keywords[j],klen) && is_separator(*(p+klen))) { /* Keyword */ memset(row->hl+i,kw2 ? HL_KEYWORD2 : HL_KEYWORD1,klen); p += klen; i += klen; break; } } if (keywords[j] != NULL) { prev_sep = 0; continue; /* We had a keyword match */ } } /* Not special chars */ prev_sep = is_separator(*p); p++; i++; } /* Propagate syntax change to the next row if the open commen * state changed. This may recursively affect all the following rows * in the file. */ int oc = editorRowHasOpenComment(row); if (row->hl_oc != oc && row->idx+1 < E.numrows) editorUpdateSyntax(&E.row[row->idx+1]); row->hl_oc = oc; } /* Maps syntax highlight token types to terminal colors. */ int editorSyntaxToColor(int hl) { switch(hl) { case HL_COMMENT: case HL_MLCOMMENT: return 36; /* cyan */ case HL_KEYWORD1: return 33; /* yellow */ case HL_KEYWORD2: return 32; /* green */ case HL_STRING: return 35; /* magenta */ case HL_NUMBER: return 31; /* red */ case HL_MATCH: return 34; /* blue */ default: return 37; /* white */ } } /* Select the syntax highlight scheme depending on the filename, * setting it in the global state E.syntax. */ void editorSelectSyntaxHighlight(char *filename) { for (unsigned int j = 0; j < HLDB_ENTRIES; j++) { struct editorSyntax *s = HLDB+j; unsigned int i = 0; while(s->filematch[i]) { char *p; int patlen = strlen(s->filematch[i]); if ((p = strstr(filename,s->filematch[i])) != NULL) { if (s->filematch[i][0] != '.' || p[patlen] == '\0') { E.syntax = s; return; } } i++; } } } /* ======================= Editor rows implementation ======================= */ /* Update the rendered version and the syntax highlight of a row. */ void editorUpdateRow(erow *row) { unsigned int tabs = 0, nonprint = 0; int j, idx; /* Create a version of the row we can directly print on the screen, * respecting tabs, substituting non printable characters with '?'. */ free(row->render); for (j = 0; j < row->size; j++) if (row->chars[j] == TAB) tabs++; unsigned long long allocsize = (unsigned long long) row->size + tabs*8 + nonprint*9 + 1; if (allocsize > UINT32_MAX) { printf("Some line of the edited file is too long for reditor\n"); exit(1); } row->render = malloc(row->size + tabs*8 + nonprint*9 + 1); idx = 0; for (j = 0; j < row->size; j++) { if (row->chars[j] == TAB) { row->render[idx++] = ' '; while((idx+1) % 8 != 0) row->render[idx++] = ' '; } else { row->render[idx++] = row->chars[j]; } } row->rsize = idx; row->render[idx] = '\0'; /* Update the syntax highlighting attributes of the row. */ editorUpdateSyntax(row); } /* Insert a row at the specified position, shifting the other rows on the bottom * if required. */ void editorInsertRow(int at, char *s, size_t len) { if (at > E.numrows) return; E.row = realloc(E.row,sizeof(erow)*(E.numrows+1)); if (at != E.numrows) { memmove(E.row+at+1,E.row+at,sizeof(E.row[0])*(E.numrows-at)); for (int j = at+1; j <= E.numrows; j++) E.row[j].idx++; } E.row[at].size = len; E.row[at].chars = malloc(len+1); memcpy(E.row[at].chars,s,len+1); E.row[at].hl = NULL; E.row[at].hl_oc = 0; E.row[at].render = NULL; E.row[at].rsize = 0; E.row[at].idx = at; editorUpdateRow(E.row+at); E.numrows++; E.dirty++; } /* Free row's heap allocated stuff. */ void editorFreeRow(erow *row) { free(row->render); free(row->chars); free(row->hl); } /* Remove the row at the specified position, shifting the remainign on the * top. */ void editorDelRow(int at) { erow *row; if (at >= E.numrows) return; row = E.row+at; editorFreeRow(row); memmove(E.row+at,E.row+at+1,sizeof(E.row[0])*(E.numrows-at-1)); for (int j = at; j < E.numrows-1; j++) E.row[j].idx++; E.numrows--; E.dirty++; } /* Turn the editor rows into a single heap-allocated string. * Returns the pointer to the heap-allocated string and populate the * integer pointed by 'buflen' with the size of the string, escluding * the final nulterm. */ char *editorRowsToString(int *buflen) { char *buf = NULL, *p; int totlen = 0; int j; /* Compute count of bytes */ for (j = 0; j < E.numrows; j++) totlen += E.row[j].size+1; /* +1 is for "\n" at end of every row */ *buflen = totlen; totlen++; /* Also make space for nulterm */ p = buf = malloc(totlen); for (j = 0; j < E.numrows; j++) { memcpy(p,E.row[j].chars,E.row[j].size); p += E.row[j].size; *p = '\n'; p++; } *p = '\0'; return buf; } /* Insert a character at the specified position in a row, moving the remaining * chars on the right if needed. */ void editorRowInsertChar(erow *row, int at, int c) { if (at > row->size) { /* Pad the string with spaces if the insert location is outside the * current length by more than a single character. */ int padlen = at-row->size; /* In the next line +2 means: new char and null term. */ row->chars = realloc(row->chars,row->size+padlen+2); memset(row->chars+row->size,' ',padlen); row->chars[row->size+padlen+1] = '\0'; row->size += padlen+1; } else { /* If we are in the middle of the string just make space for 1 new * char plus the (already existing) null term. */ row->chars = realloc(row->chars,row->size+2); memmove(row->chars+at+1,row->chars+at,row->size-at+1); row->size++; } row->chars[at] = c; editorUpdateRow(row); E.dirty++; } /* Append the string 's' at the end of a row */ void editorRowAppendString(erow *row, char *s, size_t len) { row->chars = realloc(row->chars,row->size+len+1); memcpy(row->chars+row->size,s,len); row->size += len; row->chars[row->size] = '\0'; editorUpdateRow(row); E.dirty++; } /* Delete the character at offset 'at' from the specified row. */ void editorRowDelChar(erow *row, int at) { if (row->size <= at) return; memmove(row->chars+at,row->chars+at+1,row->size-at); editorUpdateRow(row); row->size--; E.dirty++; } /* Insert the specified char at the current prompt position. */ void editorInsertChar(int c) { int filerow = E.rowoff+E.cy; int filecol = E.coloff+E.cx; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; /* If the row where the cursor is currently located does not exist in our * logical representaion of the file, add enough empty rows as needed. */ if (!row) { while(E.numrows <= filerow) editorInsertRow(E.numrows,"",0); } row = &E.row[filerow]; editorRowInsertChar(row,filecol,c); if (E.cx == E.screencols-1) E.coloff++; else E.cx++; E.dirty++; } /* Inserting a newline is slightly complex as we have to handle inserting a * newline in the middle of a line, splitting the line as needed. */ void editorInsertNewline(void) { int filerow = E.rowoff+E.cy; int filecol = E.coloff+E.cx; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; if (!row) { if (filerow == E.numrows) { editorInsertRow(filerow,"",0); goto fixcursor; } return; } /* If the cursor is over the current line size, we want to conceptually * think it's just over the last character. */ if (filecol >= row->size) filecol = row->size; if (filecol == 0) { editorInsertRow(filerow,"",0); } else { /* We are in the middle of a line. Split it between two rows. */ editorInsertRow(filerow+1,row->chars+filecol,row->size-filecol); row = &E.row[filerow]; row->chars[filecol] = '\0'; row->size = filecol; editorUpdateRow(row); } fixcursor: if (E.cy == E.screenrows-1) { E.rowoff++; } else { E.cy++; } E.cx = 0; E.coloff = 0; } /* Delete the char at the current prompt position. */ void editorDelChar() { int filerow = E.rowoff+E.cy; int filecol = E.coloff+E.cx; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; if (!row || (filecol == 0 && filerow == 0)) return; if (filecol == 0) { /* Handle the case of column 0, we need to move the current line * on the right of the previous one. */ filecol = E.row[filerow-1].size; editorRowAppendString(&E.row[filerow-1],row->chars,row->size); editorDelRow(filerow); row = NULL; if (E.cy == 0) E.rowoff--; else E.cy--; E.cx = filecol; if (E.cx >= E.screencols) { int shift = (E.screencols-E.cx)+1; E.cx -= shift; E.coloff += shift; } } else { editorRowDelChar(row,filecol-1); if (E.cx == 0 && E.coloff) E.coloff--; else E.cx--; } if (row) editorUpdateRow(row); E.dirty++; } /* Load the specified program in the editor memory and returns 0 on success * or 1 on error. */ int editorOpen(char *filename) { FILE *fp; E.dirty = 0; free(E.filename); size_t fnlen = strlen(filename)+1; E.filename = malloc(fnlen); memcpy(E.filename,filename,fnlen); fp = fopen(filename,"r"); if (!fp) { if (errno != ENOENT) { perror("Opening file"); exit(1); } return 1; } char *line = NULL; size_t linecap = 0; ssize_t linelen; while((linelen = getline(&line,&linecap,fp)) != -1) { if (linelen && (line[linelen-1] == '\n' || line[linelen-1] == '\r')) line[--linelen] = '\0'; editorInsertRow(E.numrows,line,linelen); } free(line); fclose(fp); E.dirty = 0; return 0; } /* Save the current file on disk. Return 0 on success, 1 on error. */ int editorSave(void) { int len; char *buf = editorRowsToString(&len); int fd = open(E.filename,O_RDWR|O_CREAT,0644); if (fd == -1) goto writeerr; /* Use truncate + a single write(2) call in order to make saving * a bit safer, under the limits of what we can do in a small editor. */ if (ftruncate(fd,len) == -1) goto writeerr; if (write(fd,buf,len) != len) goto writeerr; close(fd); free(buf); E.dirty = 0; editorSetStatusMessage("%d bytes written on disk", len); return 0; writeerr: free(buf); if (fd != -1) close(fd); editorSetStatusMessage("Can't save! I/O error: %s",strerror(errno)); return 1; } /* ============================= Terminal update ============================ */ /* We define a very simple "append buffer" structure, that is an heap * allocated string where we can append to. This is useful in order to * write all the escape sequences in a buffer and flush them to the standard * output in a single call, to avoid flickering effects. */ struct abuf { char *b; int len; }; #define ABUF_INIT {NULL,0} void abAppend(struct abuf *ab, const char *s, int len) { char *new = realloc(ab->b,ab->len+len); if (new == NULL) return; memcpy(new+ab->len,s,len); ab->b = new; ab->len += len; } void abFree(struct abuf *ab) { free(ab->b); } /* This function writes the whole screen using VT100 escape characters * starting from the logical state of the editor in the global state 'E'. */ void editorRefreshScreen(void) { int y; erow *r; char buf[32]; struct abuf ab = ABUF_INIT; abAppend(&ab,"\x1b[?25l",6); /* Hide cursor. */ abAppend(&ab,"\x1b[H",3); /* Go home. */ for (y = 0; y < E.screenrows; y++) { int filerow = E.rowoff+y; if (filerow >= E.numrows) { if (E.numrows == 0 && y == E.screenrows/3) { char welcome[80]; int welcomelen = snprintf(welcome,sizeof(welcome), "Reditor -- version %s\x1b[0K\r\n", REDITOR_VERSION); int padding = (E.screencols-welcomelen)/2; if (padding) { abAppend(&ab,"~",1); padding--; } while(padding--) abAppend(&ab," ",1); abAppend(&ab,welcome,welcomelen); } else { abAppend(&ab,"~\x1b[0K\r\n",7); } continue; } r = &E.row[filerow]; int len = r->rsize - E.coloff; int current_color = -1; if (len > 0) { if (len > E.screencols) len = E.screencols; char *c = r->render+E.coloff; unsigned char *hl = r->hl+E.coloff; int j; for (j = 0; j < len; j++) { if (hl[j] == HL_NONPRINT) { char sym; abAppend(&ab,"\x1b[7m",4); if (c[j] <= 26) sym = '@'+c[j]; else sym = '?'; abAppend(&ab,&sym,1); abAppend(&ab,"\x1b[0m",4); } else if (hl[j] == HL_NORMAL) { if (current_color != -1) { abAppend(&ab,"\x1b[39m",5); current_color = -1; } abAppend(&ab,c+j,1); } else { int color = editorSyntaxToColor(hl[j]); if (color != current_color) { char buf[16]; int clen = snprintf(buf,sizeof(buf),"\x1b[%dm",color); current_color = color; abAppend(&ab,buf,clen); } abAppend(&ab,c+j,1); } } } abAppend(&ab,"\x1b[39m",5); abAppend(&ab,"\x1b[0K",4); abAppend(&ab,"\r\n",2); } /* Create a two rows status. First row: */ abAppend(&ab,"\x1b[0K",4); abAppend(&ab,"\x1b[7m",4); char status[80], rstatus[80]; int len = snprintf(status, sizeof(status), "%.20s - %d lines %s", E.filename, E.numrows, E.dirty ? "(modified)" : ""); int rlen = snprintf(rstatus, sizeof(rstatus), "%d/%d",E.rowoff+E.cy+1,E.numrows); if (len > E.screencols) len = E.screencols; abAppend(&ab,status,len); while(len < E.screencols) { if (E.screencols - len == rlen) { abAppend(&ab,rstatus,rlen); break; } else { abAppend(&ab," ",1); len++; } } abAppend(&ab,"\x1b[0m\r\n",6); /* Second row depends on E.statusmsg and the status message update time. */ abAppend(&ab,"\x1b[0K",4); int msglen = strlen(E.statusmsg); if (msglen && time(NULL)-E.statusmsg_time < 5) abAppend(&ab,E.statusmsg,msglen <= E.screencols ? msglen : E.screencols); /* Put cursor at its current position. Note that the horizontal position * at which the cursor is displayed may be different compared to 'E.cx' * because of TABs. */ int j; int cx = 1; int filerow = E.rowoff+E.cy; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; if (row) { for (j = E.coloff; j < (E.cx+E.coloff); j++) { if (j < row->size && row->chars[j] == TAB) cx += 7-((cx)%8); cx++; } } snprintf(buf,sizeof(buf),"\x1b[%d;%dH",E.cy+1,cx); abAppend(&ab,buf,strlen(buf)); abAppend(&ab,"\x1b[?25h",6); /* Show cursor. */ write(STDOUT_FILENO,ab.b,ab.len); abFree(&ab); } /* Set an editor status message for the second line of the status, at the * end of the screen. */ void editorSetStatusMessage(const char *fmt, ...) { va_list ap; va_start(ap,fmt); vsnprintf(E.statusmsg,sizeof(E.statusmsg),fmt,ap); va_end(ap); E.statusmsg_time = time(NULL); } /* =============================== Find mode ================================ */ #define REDITOR_QUERY_LEN 256 void editorFind(int fd) { char query[REDITOR_QUERY_LEN+1] = {0}; int qlen = 0; int last_match = -1; /* Last line where a match was found. -1 for none. */ int find_next = 0; /* if 1 search next, if -1 search prev. */ int saved_hl_line = -1; /* No saved HL */ char *saved_hl = NULL; #define FIND_RESTORE_HL do { \ if (saved_hl) { \ memcpy(E.row[saved_hl_line].hl,saved_hl, E.row[saved_hl_line].rsize); \ free(saved_hl); \ saved_hl = NULL; \ } \ } while (0) /* Save the cursor position in order to restore it later. */ int saved_cx = E.cx, saved_cy = E.cy; int saved_coloff = E.coloff, saved_rowoff = E.rowoff; while(1) { editorSetStatusMessage( "Search: %s (Use ESC/Arrows/Enter)", query); editorRefreshScreen(); int c = editorReadKey(fd); if (c == DEL_KEY || c == CTRL_H || c == BACKSPACE) { if (qlen != 0) query[--qlen] = '\0'; last_match = -1; } else if (c == ESC || c == ENTER) { if (c == ESC) { E.cx = saved_cx; E.cy = saved_cy; E.coloff = saved_coloff; E.rowoff = saved_rowoff; } FIND_RESTORE_HL; editorSetStatusMessage(""); return; } else if (c == ARROW_RIGHT || c == ARROW_DOWN) { find_next = 1; } else if (c == ARROW_LEFT || c == ARROW_UP) { find_next = -1; } else if (isprint(c)) { if (qlen < REDITOR_QUERY_LEN) { query[qlen++] = c; query[qlen] = '\0'; last_match = -1; } } /* Search occurrence. */ if (last_match == -1) find_next = 1; if (find_next) { char *match = NULL; int match_offset = 0; int i, current = last_match; for (i = 0; i < E.numrows; i++) { current += find_next; if (current == -1) current = E.numrows-1; else if (current == E.numrows) current = 0; match = strstr(E.row[current].render,query); if (match) { match_offset = match-E.row[current].render; break; } } find_next = 0; /* Highlight */ FIND_RESTORE_HL; if (match) { erow *row = &E.row[current]; last_match = current; if (row->hl) { saved_hl_line = current; saved_hl = malloc(row->rsize); memcpy(saved_hl,row->hl,row->rsize); memset(row->hl+match_offset,HL_MATCH,qlen); } E.cy = 0; E.cx = match_offset; E.rowoff = current; E.coloff = 0; /* Scroll horizontally as needed. */ if (E.cx > E.screencols) { int diff = E.cx - E.screencols; E.cx -= diff; E.coloff += diff; } } } } } /* ========================= Editor events handling ======================== */ /* Handle cursor position change because arrow keys were pressed. */ void editorMoveCursor(int key) { int filerow = E.rowoff+E.cy; int filecol = E.coloff+E.cx; int rowlen; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; switch(key) { case ARROW_LEFT: if (E.cx == 0) { if (E.coloff) { E.coloff--; } else { if (filerow > 0) { E.cy--; E.cx = E.row[filerow-1].size; if (E.cx > E.screencols-1) { E.coloff = E.cx-E.screencols+1; E.cx = E.screencols-1; } } } } else { E.cx -= 1; } break; case ARROW_RIGHT: if (row && filecol < row->size) { if (E.cx == E.screencols-1) { E.coloff++; } else { E.cx += 1; } } else if (row && filecol == row->size) { E.cx = 0; E.coloff = 0; if (E.cy == E.screenrows-1) { E.rowoff++; } else { E.cy += 1; } } break; case ARROW_UP: if (E.cy == 0) { if (E.rowoff) E.rowoff--; } else { E.cy -= 1; } break; case ARROW_DOWN: if (filerow < E.numrows) { if (E.cy == E.screenrows-1) { E.rowoff++; } else { E.cy += 1; } } break; } /* Fix cx if the current line has not enough chars. */ filerow = E.rowoff+E.cy; filecol = E.coloff+E.cx; row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; rowlen = row ? row->size : 0; if (filecol > rowlen) { E.cx -= filecol-rowlen; if (E.cx < 0) { E.coloff += E.cx; E.cx = 0; } } } /* Process events arriving from the standard input, which is, the user * is typing stuff on the terminal. */ #define REDITOR_QUIT_TIMES 3 void editorProcessKeypress(int fd) { /* When the file is modified, requires Ctrl-q to be pressed N times * before actually quitting. */ static int quit_times = REDITOR_QUIT_TIMES; int c = editorReadKey(fd); switch(c) { case ENTER: /* Enter */ editorInsertNewline(); break; case CTRL_C: /* Ctrl-c */ /* We ignore ctrl-c, it can't be so simple to lose the changes * to the edited file. */ break; case CTRL_Q: /* Ctrl-q */ /* Quit if the file was already saved. */ if (E.dirty && quit_times) { editorSetStatusMessage("WARNING!!! File has unsaved changes. " "Press Ctrl-Q %d more times to quit.", quit_times); quit_times--; return; } printf("\e[1;1H\e[2J"); // clear the terminal in the end exit(0); break; case CTRL_S: /* Ctrl-s */ editorSave(); break; case CTRL_F: editorFind(fd); break; case CTRL_H: /* Ctrl-h*/ editorSetStatusMessage("HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find"); break; case BACKSPACE: /* Backspace */ case DEL_KEY: editorDelChar(); break; case PAGE_UP: case PAGE_DOWN: if (c == PAGE_UP && E.cy != 0) E.cy = 0; else if (c == PAGE_DOWN && E.cy != E.screenrows-1) E.cy = E.screenrows-1; { int times = E.screenrows; while(times--) editorMoveCursor(c == PAGE_UP ? ARROW_UP: ARROW_DOWN); } break; case ARROW_UP: case ARROW_DOWN: case ARROW_LEFT: case ARROW_RIGHT: editorMoveCursor(c); break; case CTRL_L: /* ctrl+l, clear screen */ /* Just refresht the line as side effect. */ break; case ESC: /* Nothing to do for ESC in this mode. */ break; default: editorInsertChar(c); break; } quit_times = REDITOR_QUIT_TIMES; /* Reset it to the original value. */ } int editorFileWasModified(void) { return E.dirty; } void updateWindowSize(void) { if (getWindowSize(STDIN_FILENO,STDOUT_FILENO, &E.screenrows,&E.screencols) == -1) { perror("Unable to query the screen for size (columns / rows)"); exit(1); } E.screenrows -= 2; /* Get room for status bar. */ } void handleSigWinCh(int unused __attribute__((unused))) { updateWindowSize(); if (E.cy > E.screenrows) E.cy = E.screenrows - 1; if (E.cx > E.screencols) E.cx = E.screencols - 1; editorRefreshScreen(); } void initEditor(void) { E.cx = 0; E.cy = 0; E.rowoff = 0; E.coloff = 0; E.numrows = 0; E.row = NULL; E.dirty = 0; E.filename = NULL; E.syntax = NULL; updateWindowSize(); signal(SIGWINCH, handleSigWinCh); } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr,"Usage: reditor <filename>\n"); exit(1); } initEditor(); editorSelectSyntaxHighlight(argv[1]); editorOpen(argv[1]); enableRawMode(STDIN_FILENO); editorSetStatusMessage( "HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find"); while(1) { editorRefreshScreen(); editorProcessKeypress(STDIN_FILENO); } return 0; }
the_stack_data/92354.c
// Solved 2020-11-24 10:33 // Runtime: 40 ms (99.31%) // Memory Usage: 12.3 MB (97.93%) void reverseString(char* s, int sSize) { char t; for (int i = 0; 2 * i < sSize; i++) { t = s[i]; s[i] = s[sSize - 1 - i]; s[sSize - 1 - i] = t; } }
the_stack_data/1104072.c
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { float n; printf("Digite numero: "); scanf("%f", &n); if (n < 0) { printf("%.2f ao quadrado: %.2f\n", n, pow(n, 2)); } else { printf("Raiz quadrada de %.2f: %.2f\n", n, sqrt(n)); } system("pause"); return 0; }
the_stack_data/55154.c
//Background converted using Mollusk's PAImageConverter //This Background uses tilegfx2_Pal int level_4_Width = 1024; int level_4_Height = 256; const unsigned short level_4_Map[4096] __attribute__ ((aligned (4))) = { 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 1, 10, 11, 12, 1036, 1035, 0, 0, 0, 0, 0, 0, 13, 14, 15, 16, 17, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 20, 21, 22, 23, 24, 25, 26, 27, 20, 19, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 18, 15, 16, 13, 14, 0, 0, 0, 0, 0, 0, 0, 0, 9, 2, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 31, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 30, 21, 22, 21, 22, 21, 22, 31, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 30, 21, 22, 21, 22, 21, 22, 21, 22, 31, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 43, 44, 41, 42, 39, 40, 0, 0, 0, 0, 0, 0, 0, 0, 27, 20, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 2, 1, 2, 1, 2, 1, 2, 1, 2, 0, 0, 0, 0, 13, 14, 0, 0, 0, 0, 13, 14, 15, 16, 0, 0, 0, 0, 0, 0, 0, 0, 49, 50, 51, 50, 51, 50, 51, 50, 51, 50, 51, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 3, 4, 1036, 1035, 0, 0, 0, 0, 0, 0, 0, 0, 9, 2, 19, 20, 19, 20, 19, 20, 19, 20, 19, 20, 19, 20, 19, 20, 19, 28, 35, 36, 35, 36, 37, 38, 35, 36, 33, 34, 33, 34, 33, 34, 35, 36, 27, 20, 19, 20, 19, 20, 19, 20, 19, 20, 33, 34, 33, 34, 39, 40, 33, 34, 35, 36, 39, 40, 41, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 30, 21, 22, 31, 32, 0, 0, 0, 0, 0, 0, 0, 0, 62, 63, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 7, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 8, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 1036, 1035, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 54, 55, 56, 57, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 45, 46, 9, 2, 1, 2, 1, 2, 1036, 1035, 0, 0, 0, 0, 0, 0, 0, 0, 19, 20, 19, 20, 19, 20, 19, 20, 19, 20, 19, 20, 19, 20, 19, 20, 25, 26, 25, 26, 25, 26, 25, 26, 25, 26, 25, 26, 25, 26, 25, 26, 19, 20, 19, 20, 19, 20, 19, 20, 19, 20, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 31, 32, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 68, 69, 70, 71, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 58, 59, 27, 20, 19, 20, 19, 20, 31, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
the_stack_data/218893406.c
#include<stdio.h> #define MAX 25 void main() { int frag[MAX], b[MAX], f[MAX], i, j, nb, nf, temp, highest=0; static int bf[MAX], ff[MAX]; printf("\nEnter the number of blocks: "); scanf("%d", &nb); printf("Enter the number of files: "); scanf("%d", &nf); printf("\nEnter the size of the blocks: \n"); for(i = 1; i <= nb; i++) { printf("Block %d: ", i); scanf("%d", &b[i]); } printf("\nEnter the size of the files: \n"); for(i = 1; i <= nf; i++) { printf("File %d: ", i); scanf("%d", &f[i]); } for(i=1;i<=nf;i++) { for(j=1;j<=nb;j++) { if(bf[j]!=1) { //if bf[j] is not allocated temp=b[j]-f[i]; if(temp>=0) if(highest<temp) { ff[i]=j; highest=temp; } } } frag[i]=highest; bf[ff[i]]=1; highest=0; } printf("\nFile no. \tFile size \tBlock no. \tBlock size \tFragment\n"); for(i=1;i<=nf;i++) printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]); printf("\n"); }
the_stack_data/72612.c
#include<stdio.h> int main(int argc, char *argv[]) { FILE *fp = NULL; char str[10]; if ((fp = fopen(argv[1], "r")) == NULL) { // printf("can not open!\n"); return -1; } fgets(str, sizeof(str), fp); // fputs(str, stdout); // fclose(fp); // return 0; }
the_stack_data/29825510.c
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 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 the 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 INTEL OR ITS 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. END_LEGAL */ /* * this application calls a user-written function that contains a bad code pattern. */ #include <stdio.h> #include <stdlib.h> #include <string.h> extern void fall_thru(); int main( int argc, char * argv[] ) { char * buffer; buffer = (char *)malloc( 64 ); strcpy( buffer, "abc" ); printf("%s\n", buffer ); fall_thru(); printf("returned from fall_thru.\n"); free( buffer ); return 0; }
the_stack_data/75136889.c
#include <stdio.h> void hello() { printf("Hello, World!\n"); }
the_stack_data/54824792.c
// PARAM: --set ana.activated "['base','threadid','threadflag','escape','uninit','mallocWrapper']" --set exp.privatization none typedef struct { int i,j; } S; int some_function(S xx){ return xx.j; //NOWARN } int main(){ S ss; some_function(ss); //WARN return 0; }
the_stack_data/860369.c
/************************************************************************ * bitvector.c * Richard Gowen * * This is a test for extracting bits from bytes in a bitvector * ************************************************************************/ #include<stdio.h> extern void BitsFromByte( char byte, char bits[ ], int k ); void BitsFromByte( char byte, char bits[ ], int k ) { unsigned char mask = 1; int i; for ( i = 0; i < 8; i++ ) { bits[i+k] = ( byte & ( mask << i ) ) != 0; } } int main( int argc, char* argv[] ) { // A unsigned char byte[8] = { 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00 }; // B //unsigned char byte[8] = { 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00 }; // a //unsigned char byte[8] = { 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00 }; // b //unsigned char byte[8] = { 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00 }; // G //unsigned char byte[8] = { 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00 }; // g //unsigned char byte[8] = { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F }; //unsigned char byte[8] = { }; //unsigned char byte[8] = { }; unsigned char bits[64]; int i; int k; for ( i = 0; i < 8; i++ ) { k = i * 8; BitsFromByte( byte[i], bits, k ); } for ( i = 0; i < 64; i++ ) { printf("%d ",bits[i]); if ( i == 7 || i == 15 || i == 23 || i == 31 || i == 39 || i == 47 || i == 55 || i == 63) { printf("\n"); } } printf("\n"); }
the_stack_data/33888.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } int main(int argc , char *argv[] ) { unsigned int input[1] ; unsigned int output[1] ; int randomFuns_i5 ; unsigned int randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 1845409733U) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void RandomFunc(unsigned int input[1] , unsigned int output[1] ) { unsigned int state[1] ; char copy12 ; unsigned short copy13 ; unsigned short copy14 ; { state[0UL] = (input[0UL] | 51238316UL) >> 3U; if ((state[0UL] >> 3U) & 1U) { if ((state[0UL] >> 4U) & 1U) { state[0UL] >>= ((state[0UL] >> 1U) & 7U) | 1UL; } else { copy12 = *((char *)(& state[0UL]) + 0); *((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 3); *((char *)(& state[0UL]) + 3) = copy12; state[0UL] <<= ((state[0UL] >> 3U) & 7U) | 1UL; } } else if (state[0UL] & 1U) { state[0UL] <<= (state[0UL] & 7U) | 1UL; state[0UL] <<= ((state[0UL] >> 4U) & 7U) | 1UL; } else { copy13 = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0); *((unsigned short *)(& state[0UL]) + 0) = copy13; copy14 = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0); *((unsigned short *)(& state[0UL]) + 0) = copy14; } output[0UL] = state[0UL] | 745448133UL; } }
the_stack_data/2045.c
// REQUIRES: arm-registered-target // RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -S -emit-llvm -o - -mbranch-protection=none %s | FileCheck %s --check-prefix=CHECK --check-prefix=NONE // RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -S -emit-llvm -o - -mbranch-protection=pac-ret %s | FileCheck %s --check-prefix=CHECK --check-prefix=PART // RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -S -emit-llvm -o - -mbranch-protection=pac-ret+leaf %s | FileCheck %s --check-prefix=CHECK --check-prefix=ALL // RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -S -emit-llvm -o - -mbranch-protection=pac-ret+b-key %s | FileCheck %s --check-prefix=CHECK --check-prefix=PART // RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -S -emit-llvm -o - -mbranch-protection=bti %s | FileCheck %s --check-prefix=CHECK --check-prefix=BTE // Check there are no branch protection function attributes // CHECK-LABEL: @foo() #[[#ATTR:]] // CHECK-NOT: attributes #[[#ATTR]] = { {{.*}} "sign-return-address" // CHECK-NOT: attributes #[[#ATTR]] = { {{.*}} "sign-return-address-key" // CHECK-NOT: attributes #[[#ATTR]] = { {{.*}} "branch-target-enforcement" // Check module attributes // NONE: !{i32 8, !"branch-target-enforcement", i32 0} // PART: !{i32 8, !"branch-target-enforcement", i32 0} // ALL: !{i32 8, !"branch-target-enforcement", i32 0} // BTE: !{i32 8, !"branch-target-enforcement", i32 1} // NONE: !{i32 8, !"sign-return-address", i32 0} // PART: !{i32 8, !"sign-return-address", i32 1} // ALL: !{i32 8, !"sign-return-address", i32 1} // BTE: !{i32 8, !"sign-return-address", i32 0} // NONE: !{i32 8, !"sign-return-address-all", i32 0} // PART: !{i32 8, !"sign-return-address-all", i32 0} // ALL: !{i32 8, !"sign-return-address-all", i32 1} // BTE: !{i32 8, !"sign-return-address-all", i32 0} void foo() {}
the_stack_data/29824698.c
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include <fcntl.h> int main(int argc, const char **argv) { close(0); int fd = open(argv[1], O_RDWR | O_CREAT); fprintf(stdout, "Parent: File opened: fd=%d.\n", fd); pid_t pid = fork(); if (pid == 0) { char *args[] = {NULL}; execvp("./mycat", args); exit(0); } else { pid_t child = wait(NULL); fprintf(stdout, "\nParent : The child has terminated.\n"); exit(0); } }
the_stack_data/12638672.c
#include <stdio.h> void scilab_rt_histplot_d0i2_(double scalarin0, int in00, int in01, int matrixin0[in00][in01]) { int i; int j; int val0 = 0; printf("%f", scalarin0); for (i = 0; i < in00; ++i) { for (j = 0; j < in01; ++j) { val0 += matrixin0[i][j]; } } printf("%d", val0); }
the_stack_data/204798.c
#include <unistd.h> int main() { return pause(); }
the_stack_data/50136466.c
// WARNING: ODEBUG bug in bt_host_release // https://syzkaller.appspot.com/bug?id=f2639529f22768fab8a4 // status:0 // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <net/if_arp.h> #include <netinet/in.h> #include <pthread.h> #include <sched.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.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 <time.h> #include <unistd.h> #include <linux/capability.h> #include <linux/futex.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> static unsigned long long procid; static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* ctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; int skip = __atomic_load_n(&skip_segv, __ATOMIC_RELAXED) != 0; int valid = addr < prog_start || addr > prog_end; if (skip && valid) { _longjmp(segv_env, 1); } exit(sig); } static void install_segv_handler(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8); syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = segv_handler; sa.sa_flags = SA_NODEFER | SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #define NONFAILING(...) \ { \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ } static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir(void) { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) exit(1); if (chmod(tmpdir, 0777)) exit(1); if (chdir(tmpdir)) exit(1); } static void thread_start(void* (*fn)(void*), void* arg) { pthread_t th; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); int i = 0; for (; i < 100; i++) { if (pthread_create(&th, &attr, fn, arg) == 0) { pthread_attr_destroy(&attr); return; } if (errno == EAGAIN) { usleep(50); continue; } break; } exit(1); } typedef struct { int state; } event_t; static void event_init(event_t* ev) { ev->state = 0; } static void event_reset(event_t* ev) { ev->state = 0; } static void event_set(event_t* ev) { if (ev->state) exit(1); __atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000); } static void event_wait(event_t* ev) { while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0); } static int event_isset(event_t* ev) { return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE); } static int event_timedwait(event_t* ev, uint64_t timeout) { uint64_t start = current_time_ms(); uint64_t now = start; for (;;) { uint64_t remain = timeout - (now - start); struct timespec ts; ts.tv_sec = remain / 1000; ts.tv_nsec = (remain % 1000) * 1000 * 1000; syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts); if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) return 1; now = current_time_ms(); if (now - start > timeout) return 0; } } 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 (reply_len) *reply_len = 0; if (hdr->nlmsg_type == NLMSG_DONE) 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; } static void netlink_add_neigh(struct nlmsg* nlmsg, int sock, const char* name, const void* addr, int addrsize, const void* mac, int macsize) { struct ndmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ndm_ifindex = if_nametoindex(name); hdr.ndm_state = NUD_PERMANENT; netlink_init(nlmsg, RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); netlink_attr(nlmsg, NDA_DST, addr, addrsize); netlink_attr(nlmsg, NDA_LLADDR, mac, macsize); int err = netlink_send(nlmsg, sock); (void)err; } static int tunfd = -1; #define TUN_IFACE "syz_tun" #define LOCAL_MAC 0xaaaaaaaaaaaa #define REMOTE_MAC 0xaaaaaaaaaabb #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 240; if (dup2(tunfd, kTunFd) < 0) exit(1); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { exit(1); } char sysctl[64]; sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE); write_file(sysctl, "0"); sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE); write_file(sysctl, "0"); int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); netlink_add_addr4(&nlmsg, sock, TUN_IFACE, LOCAL_IPV4); netlink_add_addr6(&nlmsg, sock, TUN_IFACE, LOCAL_IPV6); uint64_t macaddr = REMOTE_MAC; struct in_addr in_addr; inet_pton(AF_INET, REMOTE_IPV4, &in_addr); netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in_addr, sizeof(in_addr), &macaddr, ETH_ALEN); struct in6_addr in6_addr; inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr); netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in6_addr, sizeof(in6_addr), &macaddr, ETH_ALEN); macaddr = LOCAL_MAC; netlink_device_change(&nlmsg, sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN, NULL); close(sock); } const int kInitNetNsFd = 239; #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; 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); int n = 0; int err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n); if (err) { return -1; } uint16_t id = 0; struct nlattr* 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); 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; 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); int n = 0; int err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n); if (err) { return -1; } uint16_t id = 0; struct nlattr* 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); 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; 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; 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) { return; } 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 int read_tun(char* data, int size) { if (tunfd < 0) return -1; int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN || errno == EBADFD) return -1; exit(1); } return rv; } static void flush_tun() { char data[1000]; while (read_tun(&data[0], sizeof(data)) != -1) { } } #define MAX_FDS 30 static long syz_init_net_socket(volatile long domain, volatile long type, volatile long proto) { int netns = open("/proc/self/ns/net", O_RDONLY); if (netns == -1) return netns; if (setns(kInitNetNsFd, 0)) return -1; int sock = syscall(__NR_socket, domain, type, proto); int err = errno; if (setns(netns, 0)) exit(1); close(netns); errno = err; return sock; } #define BTPROTO_HCI 1 #define ACL_LINK 1 #define SCAN_PAGE 2 typedef struct { uint8_t b[6]; } __attribute__((packed)) bdaddr_t; #define HCI_COMMAND_PKT 1 #define HCI_EVENT_PKT 4 #define HCI_VENDOR_PKT 0xff struct hci_command_hdr { uint16_t opcode; uint8_t plen; } __attribute__((packed)); struct hci_event_hdr { uint8_t evt; uint8_t plen; } __attribute__((packed)); #define HCI_EV_CONN_COMPLETE 0x03 struct hci_ev_conn_complete { uint8_t status; uint16_t handle; bdaddr_t bdaddr; uint8_t link_type; uint8_t encr_mode; } __attribute__((packed)); #define HCI_EV_CONN_REQUEST 0x04 struct hci_ev_conn_request { bdaddr_t bdaddr; uint8_t dev_class[3]; uint8_t link_type; } __attribute__((packed)); #define HCI_EV_REMOTE_FEATURES 0x0b struct hci_ev_remote_features { uint8_t status; uint16_t handle; uint8_t features[8]; } __attribute__((packed)); #define HCI_EV_CMD_COMPLETE 0x0e struct hci_ev_cmd_complete { uint8_t ncmd; uint16_t opcode; } __attribute__((packed)); #define HCI_OP_WRITE_SCAN_ENABLE 0x0c1a #define HCI_OP_READ_BUFFER_SIZE 0x1005 struct hci_rp_read_buffer_size { uint8_t status; uint16_t acl_mtu; uint8_t sco_mtu; uint16_t acl_max_pkt; uint16_t sco_max_pkt; } __attribute__((packed)); #define HCI_OP_READ_BD_ADDR 0x1009 struct hci_rp_read_bd_addr { uint8_t status; bdaddr_t bdaddr; } __attribute__((packed)); #define HCI_EV_LE_META 0x3e struct hci_ev_le_meta { uint8_t subevent; } __attribute__((packed)); #define HCI_EV_LE_CONN_COMPLETE 0x01 struct hci_ev_le_conn_complete { uint8_t status; uint16_t handle; uint8_t role; uint8_t bdaddr_type; bdaddr_t bdaddr; uint16_t interval; uint16_t latency; uint16_t supervision_timeout; uint8_t clk_accurancy; } __attribute__((packed)); struct hci_dev_req { uint16_t dev_id; uint32_t dev_opt; }; struct vhci_vendor_pkt { uint8_t type; uint8_t opcode; uint16_t id; }; #define HCIDEVUP _IOW('H', 201, int) #define HCISETSCAN _IOW('H', 221, int) static int vhci_fd = -1; static void hci_send_event_packet(int fd, uint8_t evt, void* data, size_t data_len) { struct iovec iv[3]; struct hci_event_hdr hdr; hdr.evt = evt; hdr.plen = data_len; uint8_t type = HCI_EVENT_PKT; iv[0].iov_base = &type; iv[0].iov_len = sizeof(type); iv[1].iov_base = &hdr; iv[1].iov_len = sizeof(hdr); iv[2].iov_base = data; iv[2].iov_len = data_len; if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0) exit(1); } static void hci_send_event_cmd_complete(int fd, uint16_t opcode, void* data, size_t data_len) { struct iovec iv[4]; struct hci_event_hdr hdr; hdr.evt = HCI_EV_CMD_COMPLETE; hdr.plen = sizeof(struct hci_ev_cmd_complete) + data_len; struct hci_ev_cmd_complete evt_hdr; evt_hdr.ncmd = 1; evt_hdr.opcode = opcode; uint8_t type = HCI_EVENT_PKT; iv[0].iov_base = &type; iv[0].iov_len = sizeof(type); iv[1].iov_base = &hdr; iv[1].iov_len = sizeof(hdr); iv[2].iov_base = &evt_hdr; iv[2].iov_len = sizeof(evt_hdr); iv[3].iov_base = data; iv[3].iov_len = data_len; if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0) exit(1); } static bool process_command_pkt(int fd, char* buf, ssize_t buf_size) { struct hci_command_hdr* hdr = (struct hci_command_hdr*)buf; if (buf_size < (ssize_t)sizeof(struct hci_command_hdr) || hdr->plen != buf_size - sizeof(struct hci_command_hdr)) { exit(1); } switch (hdr->opcode) { case HCI_OP_WRITE_SCAN_ENABLE: { uint8_t status = 0; hci_send_event_cmd_complete(fd, hdr->opcode, &status, sizeof(status)); return true; } case HCI_OP_READ_BD_ADDR: { struct hci_rp_read_bd_addr rp = {0}; rp.status = 0; memset(&rp.bdaddr, 0xaa, 6); hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp)); return false; } case HCI_OP_READ_BUFFER_SIZE: { struct hci_rp_read_buffer_size rp = {0}; rp.status = 0; rp.acl_mtu = 1021; rp.sco_mtu = 96; rp.acl_max_pkt = 4; rp.sco_max_pkt = 6; hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp)); return false; } } char dummy[0xf9] = {0}; hci_send_event_cmd_complete(fd, hdr->opcode, dummy, sizeof(dummy)); return false; } static void* event_thread(void* arg) { while (1) { char buf[1024] = {0}; ssize_t buf_size = read(vhci_fd, buf, sizeof(buf)); if (buf_size < 0) exit(1); if (buf_size > 0 && buf[0] == HCI_COMMAND_PKT) { if (process_command_pkt(vhci_fd, buf + 1, buf_size - 1)) break; } } return NULL; } #define HCI_HANDLE_1 200 #define HCI_HANDLE_2 201 static void initialize_vhci() { int hci_sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI); if (hci_sock < 0) exit(1); vhci_fd = open("/dev/vhci", O_RDWR); if (vhci_fd == -1) exit(1); const int kVhciFd = 241; if (dup2(vhci_fd, kVhciFd) < 0) exit(1); close(vhci_fd); vhci_fd = kVhciFd; struct vhci_vendor_pkt vendor_pkt; if (read(vhci_fd, &vendor_pkt, sizeof(vendor_pkt)) != sizeof(vendor_pkt)) exit(1); if (vendor_pkt.type != HCI_VENDOR_PKT) exit(1); pthread_t th; if (pthread_create(&th, NULL, event_thread, NULL)) exit(1); if (ioctl(hci_sock, HCIDEVUP, vendor_pkt.id) && errno != EALREADY) exit(1); struct hci_dev_req dr = {0}; dr.dev_id = vendor_pkt.id; dr.dev_opt = SCAN_PAGE; if (ioctl(hci_sock, HCISETSCAN, &dr)) exit(1); struct hci_ev_conn_request request; memset(&request, 0, sizeof(request)); memset(&request.bdaddr, 0xaa, 6); *(uint8_t*)&request.bdaddr.b[5] = 0x10; request.link_type = ACL_LINK; hci_send_event_packet(vhci_fd, HCI_EV_CONN_REQUEST, &request, sizeof(request)); struct hci_ev_conn_complete complete; memset(&complete, 0, sizeof(complete)); complete.status = 0; complete.handle = HCI_HANDLE_1; memset(&complete.bdaddr, 0xaa, 6); *(uint8_t*)&complete.bdaddr.b[5] = 0x10; complete.link_type = ACL_LINK; complete.encr_mode = 0; hci_send_event_packet(vhci_fd, HCI_EV_CONN_COMPLETE, &complete, sizeof(complete)); struct hci_ev_remote_features features; memset(&features, 0, sizeof(features)); features.status = 0; features.handle = HCI_HANDLE_1; hci_send_event_packet(vhci_fd, HCI_EV_REMOTE_FEATURES, &features, sizeof(features)); struct { struct hci_ev_le_meta le_meta; struct hci_ev_le_conn_complete le_conn; } le_conn; memset(&le_conn, 0, sizeof(le_conn)); le_conn.le_meta.subevent = HCI_EV_LE_CONN_COMPLETE; memset(&le_conn.le_conn.bdaddr, 0xaa, 6); *(uint8_t*)&le_conn.le_conn.bdaddr.b[5] = 0x11; le_conn.le_conn.role = 1; le_conn.le_conn.handle = HCI_HANDLE_2; hci_send_event_packet(vhci_fd, HCI_EV_LE_META, &le_conn, sizeof(le_conn)); pthread_join(th, NULL); close(hci_sock); } #define XT_TABLE_SIZE 1536 #define XT_MAX_ENTRIES 10 struct xt_counters { uint64_t pcnt, bcnt; }; struct ipt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_entries; unsigned int size; }; struct ipt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct ipt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct ipt_table_desc { const char* name; struct ipt_getinfo info; struct ipt_replace replace; }; static struct ipt_table_desc ipv4_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; static struct ipt_table_desc ipv6_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) struct arpt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_entries; unsigned int size; }; struct arpt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct arpt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct arpt_table_desc { const char* name; struct arpt_getinfo info; struct arpt_replace replace; }; static struct arpt_table_desc arpt_tables[] = { {.name = "filter"}, }; #define ARPT_BASE_CTL 96 #define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL) #define ARPT_SO_GET_INFO (ARPT_BASE_CTL) #define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1) static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (int i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); socklen_t optlen = sizeof(table->info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); struct ipt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (int i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; if (table->info.valid_hooks == 0) continue; struct ipt_getinfo info; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); socklen_t optlen = sizeof(info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { struct ipt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } struct xt_counters counters[XT_MAX_ENTRIES]; table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_arptables(void) { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (unsigned i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); socklen_t optlen = sizeof(table->info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); struct arpt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_arptables() { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (unsigned i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; if (table->info.valid_hooks == 0) continue; struct arpt_getinfo info; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); socklen_t optlen = sizeof(info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { struct arpt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } else { } struct xt_counters counters[XT_MAX_ENTRIES]; table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } #define NF_BR_NUMHOOKS 6 #define EBT_TABLE_MAXNAMELEN 32 #define EBT_CHAIN_MAXNAMELEN 32 #define EBT_BASE_CTL 128 #define EBT_SO_SET_ENTRIES (EBT_BASE_CTL) #define EBT_SO_GET_INFO (EBT_BASE_CTL) #define EBT_SO_GET_ENTRIES (EBT_SO_GET_INFO + 1) #define EBT_SO_GET_INIT_INFO (EBT_SO_GET_ENTRIES + 1) #define EBT_SO_GET_INIT_ENTRIES (EBT_SO_GET_INIT_INFO + 1) struct ebt_replace { char name[EBT_TABLE_MAXNAMELEN]; unsigned int valid_hooks; unsigned int nentries; unsigned int entries_size; struct ebt_entries* hook_entry[NF_BR_NUMHOOKS]; unsigned int num_counters; struct ebt_counter* counters; char* entries; }; struct ebt_entries { unsigned int distinguisher; char name[EBT_CHAIN_MAXNAMELEN]; unsigned int counter_offset; int policy; unsigned int nentries; char data[0] __attribute__((aligned(__alignof__(struct ebt_replace)))); }; struct ebt_table_desc { const char* name; struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; }; static struct ebt_table_desc ebt_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "broute"}, }; static void checkpoint_ebtables(void) { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (size_t i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; strcpy(table->replace.name, table->name); socklen_t optlen = sizeof(table->replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->replace.entries_size > sizeof(table->entrytable)) exit(1); table->replace.num_counters = 0; table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace, &optlen)) exit(1); } close(fd); } static void reset_ebtables() { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (unsigned i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; if (table->replace.valid_hooks == 0) continue; struct ebt_replace replace; memset(&replace, 0, sizeof(replace)); strcpy(replace.name, table->name); socklen_t optlen = sizeof(replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen)) exit(1); replace.num_counters = 0; table->replace.entries = 0; for (unsigned h = 0; h < NF_BR_NUMHOOKS; h++) table->replace.hook_entry[h] = 0; if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) { char entrytable[XT_TABLE_SIZE]; memset(&entrytable, 0, sizeof(entrytable)); replace.entries = entrytable; optlen = sizeof(replace) + replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen)) exit(1); if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0) continue; } for (unsigned j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) { if (table->replace.valid_hooks & (1 << h)) { table->replace.hook_entry[h] = (struct ebt_entries*)table->entrytable + j; j++; } } table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_net_namespace(void) { checkpoint_ebtables(); checkpoint_arptables(); checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void reset_net_namespace(void) { reset_ebtables(); reset_arptables(); reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void setup_cgroups() { if (mkdir("/syzcgroup", 0777)) { } if (mkdir("/syzcgroup/unified", 0777)) { } if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) { } if (chmod("/syzcgroup/unified", 0777)) { } write_file("/syzcgroup/unified/cgroup.subtree_control", "+cpu +memory +io +pids +rdma"); if (mkdir("/syzcgroup/cpu", 0777)) { } if (mount("none", "/syzcgroup/cpu", "cgroup", 0, "cpuset,cpuacct,perf_event,hugetlb")) { } write_file("/syzcgroup/cpu/cgroup.clone_children", "1"); write_file("/syzcgroup/cpu/cpuset.memory_pressure_enabled", "1"); if (chmod("/syzcgroup/cpu", 0777)) { } if (mkdir("/syzcgroup/net", 0777)) { } if (mount("none", "/syzcgroup/net", "cgroup", 0, "net_cls,net_prio,devices,freezer")) { } if (chmod("/syzcgroup/net", 0777)) { } } static void setup_cgroups_loop() { int pid = getpid(); char file[128]; char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/pids.max", cgroupdir); write_file(file, "32"); snprintf(file, sizeof(file), "%s/memory.low", cgroupdir); write_file(file, "%d", 298 << 20); snprintf(file, sizeof(file), "%s/memory.high", cgroupdir); write_file(file, "%d", 299 << 20); snprintf(file, sizeof(file), "%s/memory.max", cgroupdir); write_file(file, "%d", 300 << 20); snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); } static void setup_cgroups_test() { char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (symlink(cgroupdir, "./cgroup")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.cpu")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.net")) { } } static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } setup_cgroups(); } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); int netns = open("/proc/self/ns/net", O_RDONLY); if (netns == -1) exit(1); if (dup2(netns, kInitNetNsFd) < 0) exit(1); close(netns); 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); } static 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(); initialize_vhci(); sandbox_common(); drop_caps(); initialize_netdevices_init(); if (unshare(CLONE_NEWNET)) { } initialize_tun(); initialize_netdevices(); loop(); exit(1); } #define FS_IOC_SETFLAGS _IOW('f', 2, long) static void remove_dir(const char* dir) { int iter = 0; DIR* dp = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exit(1); } exit(1); } struct dirent* ep = 0; while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); while (umount2(filename, MNT_DETACH) == 0) { } struct stat st; if (lstat(filename, &st)) exit(1); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EPERM) { int fd = open(filename, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exit(1); if (umount2(filename, MNT_DETACH)) exit(1); } } closedir(dp); for (int i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EPERM) { int fd = open(dir, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exit(1); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exit(1); } } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); for (int i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_loop() { setup_cgroups_loop(); checkpoint_net_namespace(); } static void reset_loop() { reset_net_namespace(); } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setup_cgroups_test(); write_file("/proc/self/oom_score_adj", "1000"); flush_tun(); } static void close_fds() { for (int fd = 3; fd < MAX_FDS; fd++) close(fd); } static void setup_binfmt_misc() { if (mount(0, "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, 0)) { } write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:\x01::./file0:"); write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:\x02::./file0:POC"); } struct thread_t { int created, call; event_t ready, done; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { event_wait(&th->ready); event_reset(&th->ready); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); event_set(&th->done); } return 0; } static void execute_one(void) { int i, call, thread; int collide = 0; again: for (call = 0; call < 7; call++) { for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; event_init(&th->ready); event_init(&th->done); event_set(&th->done); thread_start(thr, th); } if (!event_isset(&th->done)) continue; event_reset(&th->done); th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); event_set(&th->ready); if (collide && (call % 2) == 0) break; event_timedwait(&th->done, 45); break; } } for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++) sleep_ms(1); close_fds(); if (!collide) { collide = 1; goto again; } } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { setup_loop(); int iter = 0; for (;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) exit(1); reset_loop(); int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { if (chdir(cwdbuf)) exit(1); setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5 * 1000) continue; kill_and_wait(pid, &status); break; } remove_dir(cwdbuf); } } uint64_t r[1] = {0xffffffffffffffff}; void execute_call(int call) { intptr_t res = 0; switch (call) { case 0: syscall(__NR_perf_event_open, 0ul, 0, 0xffffeffffffffffful, -1, 0ul); break; case 1: syscall(__NR_openat, 0xffffffffffffff9cul, 0ul, 0ul, 0ul); break; case 2: syscall(__NR_timer_create, 0ul, 0ul, 0ul); break; case 3: syscall(__NR_socket, 0ul, 0ul, 0); break; case 4: syscall(__NR_poll, 0ul, 0ul, 0x204); break; case 5: res = -1; NONFAILING(res = syz_init_net_socket(0x1f, 3, 1)); if (res != -1) r[0] = res; break; case 6: syscall(__NR_ioctl, r[0], 0x400448dd, 0x20000040ul); break; } } int main(void) { syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); setup_binfmt_misc(); install_segv_handler(); for (procid = 0; procid < 6; procid++) { if (fork() == 0) { use_temporary_dir(); do_sandbox_none(); } } sleep(1000000); return 0; }
the_stack_data/62748.c
// *** // Fill in code for the following C funtions. Funtion sr performs a logic right // shift using an arithmetic right shift (given by value xsra), followed by // other operations not included right shifts or division. Function sra performs // an arithmetic operations not including right shifts or division. You may use // the computation 8*sizeof(int) to determine w, the number of bits in data type // int. The shift amout k can range from 0 to w - 1. // // unsigned srl(unsigned x, int k) { // /* Perform shift arithmetically */ // unsigned xsra = (int) x >> k; // . // . // . // . // . // . // } // // int sra(int x, int k) { // /* Perform shift logically */ // int xsrl = (unsigned) x >> k; // . // . // . // . // . // . // } unsigned srl(unsigned x, int k) { /* Perform shift arithmetically */ unsigned xsra = (int) x >> k; int w = sizeof(int) << 3; unsigned neg = x >> w - 1 & 1U; unsigned mask = ~(-neg << w - k); return xsra & mask; } int sra(int x, int k) { /* Perform shift logically */ int xsrl = (unsigned) x >> k; int w = sizeof(int) << 3; unsigned neg = x >> w - 1 & 1U; unsigned mask = -neg << w - k; return xsrl | mask; }
the_stack_data/64198980.c
int main(){ TestArray_test_fold() ; return 0 ; }
the_stack_data/107953277.c
#include <stdio.h> #include <stdlib.h> void foo(FILE *f) { fclose(f); } int main(int argc, char **argv) { FILE *f; int x; x = 3; fscanf(f, "%d", &x); f = fopen(argv[1], "a"); foo(f); return 0; }
the_stack_data/83186.c
/* * Copyright (c) 1995 * The Regents of the University of California. All rights reserved. * * %sccs.include.redist.c% */ #ifndef lint static char sccsid[] = "@(#)vfslist.c 8.1 (Berkeley) 05/08/95"; #endif /* not lint */ #include <stdlib.h> #include <string.h> #include <unistd.h> int checkvfsname __P((const char *, const char **)); const char **makevfslist __P((char *)); static int skipvfs; int checkvfsname(vfsname, vfslist) const char *vfsname; const char **vfslist; { if (vfslist == NULL) return (0); while (*vfslist != NULL) { if (strcmp(vfsname, *vfslist) == 0) return (skipvfs); ++vfslist; } return (!skipvfs); } const char ** makevfslist(fslist) char *fslist; { const char **av; int i; char *nextcp; if (fslist == NULL) return (NULL); if (fslist[0] == 'n' && fslist[1] == 'o') { fslist += 2; skipvfs = 1; } for (i = 0, nextcp = fslist; *nextcp; nextcp++) if (*nextcp == ',') i++; if ((av = malloc((size_t)(i + 2) * sizeof(char *))) == NULL) { warn(NULL); return (NULL); } nextcp = fslist; i = 0; av[i++] = nextcp; while ((nextcp = strchr(nextcp, ',')) != NULL) { *nextcp++ = '\0'; av[i++] = nextcp; } av[i++] = NULL; return (av); }
the_stack_data/232955813.c
#include <stdio.h> int main () { int opcao; printf("Bem Vindo ! \n O que deseja fazer ? \n 1 - Se cadastrar \n 2 - Reservar um lugar \n"); scanf("%d", &opcao); if (opcao == 1) { int tipoPessoa; printf("Você é: \n 1 - Professor \n 2 - Aluno \n 3 - Convidado \n 4 - Portador de necessidade especial \n"); scanf("%d", &tipoPessoa); switch(tipoPessoa) { case 1: { char nomePessoa[31], rgPessoa[10], emailPessoa[65]; printf("Informe seu nome completo: "); scanf("%30s", nomePessoa); printf("Informe seu RG: "); scanf("%9s", rgPessoa); printf("Informe seu E-mail: "); scanf("%64s", emailPessoa); } } } } //https://pt.stackoverflow.com/q/337905/101
the_stack_data/44386.c
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char passwd[] = "password"; if (argc < 2) { printf("usage: %s password\n", argv[0]); return 0; } if (!strcmp(passwd, argv[1])) { printf("Correct Password!\n"); } else { printf("Invalid Password!\n"); } return 0; }
the_stack_data/126701763.c
#include<stdio.h> int main() { int array[10],a; printf("Enter upto 10 elements"); for(int i=0;i<10;i++) { scanf("%d",&array[i]); } printf("Enter the element to be searched: "); scanf("%d",&a); for(int i=0;i<10;i++) { if(a==array[i]) { printf("Element found at %dth position.\n",i+1); break; } } return 0; }
the_stack_data/104826707.c
/************************************************************************* * Program latex_calib * To convert a Latex array with measurements in pixels to array in arcseconds * (and conversion of angles from XY axis to Noth-East referential) * * Format of input files: \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} & Name & Epoch & Filter & Eyep. & $\rho$ & $\sigma_\rho$ & $\theta$ & $\sigma_\theta$ & comments \\ & & & & (mm) & (pixels) & (pixels) & (deg.) & (deg.) & \\ \hline % ------------------------------------------------------------------------$ %% 16564+6502 = STF 2118 AB & ADS 10279 & 2004. & & & & & & & orb \\ %% %% 090904_ads10279_Vd_a %% Thresholds: -1,8 %% rho_center=14.62 (+/-1.87) theta_center=156.71 (+/-7.32)or theta=-23.29 %% rho_center=14.72 theta_center=156.70 or theta = -23.30 %% rho_center=14.37 (+/-1.89) theta_center=-23.64 (+/-7.54) %% rho_center=14.34 theta_center=-23.73 %% mean: rho = 14.50 \pm 0.17 theta = -23.61 \pm 0.27 (too small -> 0.3)(n=8) & 090904\_ads10279\_Vd\ & 09/09/2004 & V & 20 & 14.50 & 0.17 & -23.61 & 0.3 & \\ .... * * JLP * Version 16/06/2005 *************************************************************************/ #include <stdio.h> #include <math.h> #include <malloc.h> #include <string.h> /* Maximum length for a line will be 170 characters: */ #define NMAX 360 #define NO_DATA -10000. #define SQUARE(x) ((x)*(x)) #define MINI(x,y) ((x) < (y)) ? (x) : (y) #define MAXI(x,y) ((x) < (y)) ? (y) : (x) #define DEBUG /* */ /* Maximum number of measurements per object: */ #define NMEAS 30 /* Maximum number of objects: */ #define NOBJ_MAX 500 /* Structure to define a measurement: */ typedef struct { char comments[30][80]; /* Comments (lines starting with %) */ char data[180]; /* Data: line with filename, filter, measurements */ char filename[40]; /* Name of the FITS file used for this measurement */ char date[12]; /* Date, e.g., 29/12/2004 */ double epoch; /* Julian day as a fraction of year, e;g., 2004.23 */ char filter[10]; /* Filter name: V, R, Sf */ int eyepiece; /* Focal length of the magnifying eyepiece */ int quadrant; /* Quadrant value */ int dquadrant; /* Quadrant uncertainty (0 or 1) */ double rho; /* Angular separation of the binary (arcseconds) */ double drho; /* Error on rho (arcseconds) */ double theta; /* Position angle of the companion (relative to North)*/ double dtheta; /* Error on theta (degrees) */ char notes[40]; /* Notes in the last column of the data line */ int flagged_out; /* Flag to cancel output (for publication) */ } MEASURE; /* Structure to define an object */ typedef struct { char wds[40]; /* WDS name */ char name[40]; /* Official binary name */ char ads[40]; /* ADS name */ MEASURE measure[NMEAS]; /* Measurements concerning this object */ char notes[40]; /* Notes which are common to all measurements */ double ra; /* Right ascension */ int dec; /* Declination */ int orbit; /* Flag, set to one if orbit */ int nmeas; /* Nber of measurements for this object*/ } OBJECT; static int latex_calib_publi(FILE *fp_in, FILE *fp_out, double scale_10, double scale_20, double theta0, double sign, int i_filename, int i_date, int i_filter, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta, int i_notes, int comments_wanted, int work_mode); static int latex_calib_copy(FILE *fp_in, FILE *fp_out, double scale_10, double scale_20, double theta0, double sign, int i_date, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta, int comments_wanted); static int calibrate_measures(OBJECT *obj, int nobj, double scale_10, double scale_20, double theta0, double sign); static int calib_data_copy(char *b_data, char *b_out, double scale_10, double scale_20, double theta0, double sign, int i_date, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta); static int decode_data(char *b_data, char *date, double *epoch, double *rho, double *drho, double *theta, double *dtheta, int *eyepiece, int i_date, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta); static int read_dvalue(char *b_data, int *value, int icol); static int read_fvalue(char *b_data, double *value, int icol); static int read_svalue(char *b_data, char *value, int icol); static int read_object_name(char *b_data, char *wds_name, char *official_name, char *ads_name, int *orbit); static int read_quadrant(char *notes, int *quadrant, int *dquadrant); static int write_fvalue(char *b_data, char *b_out, double value, int icol, int nber_of_decimals); static int read_epoch_value(char *b_data, char *date, double *epoch , int icol); int julian(double aa, int mm, int idd, double time, double *djul); static int add_new_measure(char *b_data, OBJECT *obj, int nobj, int i_filename, int i_date, int i_filter, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta, int i_notes); static int add_new_object(char *b_data, OBJECT *obj, int *nobj); static int check_measure(char *b_data, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta); static int read_measures(FILE *fp_in, int comments_wanted, OBJECT *obj, int *nobj, int i_filename, int i_date, int i_filter, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta, int i_notes); static int write_publi_table(FILE *fp_out, int comments_wanted, OBJECT *obj, int *index_obj, int nobj); static int compute_statistics(FILE *fp_out, OBJECT *obj, int nobj); static int ra_sort_objects(OBJECT *obj, int *index_obj, int nobj); static int JLP_QSORT_INDX(double *array, int *index, int *nn); static void qs2(double *array, int *index, int left, int right); static int mean_for_paper2(OBJECT *obj, int nobj); static int is_record_file(char *filename); static int is_direct_file(char *filename); static int compute_mean_for_paper2(OBJECT *obj, int io, int jm); static int good_quadrant(MEASURE *me); int main(int argc, char *argv[]) { double scale_10, scale_20, theta0, sign; char filein[60], fileout[60]; int i_filename, i_date, i_filter, i_eyepiece, i_rho, i_drho, i_theta, i_dtheta; int i_notes; int comments_wanted, publi_mode, work_mode; FILE *fp_in, *fp_out; if(argc == 7 && *argv[4]) argc = 5; if(argc == 7 && *argv[3]) argc = 4; if(argc == 7 && *argv[2]) argc = 3; if(argc == 7 && *argv[1]) argc = 2; if(argc != 5) { printf(" Syntax: latex_calib scale_10,scale_20,sign,theta0 in_file out_file comments_wanted,publi_mode \n"); printf(" out_rho = in_rho * scale_10 (or in_rho * scale_20 if 20 mm eyepiece)\n"); printf(" out_theta = in_theta * sign + theta0 \n"); printf(" Example: runs latex_calib 0.03181,0.07438,1.,90.04 astrom04g.tex astrom04g_calib.tex 0,1 (without comments, publication mode)\n"); printf(" Example: runs latex_calib 0.03181,0.07438,1.,90.04 astrom04g.tex astrom04g_calib.tex 1,0 (with comments, no publication)\n"); exit(-1); } else { sscanf(argv[1],"%lf,%lf,%lf,%lf", &scale_10, &scale_20, &sign, &theta0); strcpy(filein,argv[2]); strcpy(fileout,argv[3]); sscanf(argv[4],"%d,%d", &comments_wanted, &publi_mode); } printf(" OK: out_rho = in_rho * %g (for 10 mm eyepiece)\n", scale_10); printf(" OK: out_rho = in_rho * %g (for 20 mm eyepiece)\n", scale_20); printf(" OK: out_theta = in_theta * %g + %g \n", sign, theta0); printf(" OK: filein=%s fileout=%s comments_wanted=%d publi_mode=%d\n", filein,fileout,comments_wanted,publi_mode); if((fp_in = fopen(filein,"r")) == NULL) { printf(" Fatal error opening input file %s \n",filein); exit(-1); } if((fp_out = fopen(fileout,"w")) == NULL) { printf(" Fatal error opening output file %s \n",fileout); fclose(fp_in); exit(-1); } fprintf(fp_out,"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"); fprintf(fp_out,"%%%% Automatic conversion with latex_calib\n"); fprintf(fp_out,"%%%% JLP / Version of 08/06/2005 \n"); fprintf(fp_out,"%%%% out_rho = in_rho * %g (for 10 mm eyepiece)\n", scale_10); fprintf(fp_out,"%%%% out_rho = in_rho * %g (for 20 mm eyepiece)\n", scale_20); fprintf(fp_out,"%%%% out_theta = in_theta * %g + %g \n", sign, theta0); fprintf(fp_out,"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"); if(publi_mode) { fprintf(fp_out,"%%%% Version 16/06/2005 for Paper II (Merate) \n"); fprintf(fp_out,"%%%% Publication mode: only direct measurement is kept when rho > 0.3\" \n"); fprintf(fp_out,"%%%% Weighted mean between direct and recorded measurements when rho <= 0.3\" \n"); fprintf(fp_out,"%%%% Minimum error for rho: 0.1 pixel or 0.5%% \n"); fprintf(fp_out,"%%%% Minimum error for theta: 0.3 degree \n"); } /* Scan the file and make the conversion: */ /* date in column 3 * eyepiece in column 5 * rho in column 6 * drho in column 7 * theta in column 8 * dtheta in column 9 */ i_filename = 2; i_date = 3; i_filter = 4; i_eyepiece = 5; i_rho = 6; i_drho = 7; i_theta = 8; i_dtheta = 9; i_notes = 10; work_mode = 1; /* Version "publi", to generate a laTeX array formatted for publication: * sort out the objects, compute mean values, perform calibration, etc. */ if(publi_mode) latex_calib_publi(fp_in,fp_out, scale_10, scale_20, theta0, sign, i_filename, i_date, i_filter, i_eyepiece, i_rho, i_drho, i_theta, i_dtheta, i_notes, comments_wanted, work_mode); /* Version "copy", to copy all the contents, and simply convert the * measurements to arcseconds and degrees relative to North */ else latex_calib_copy(fp_in,fp_out, scale_10, scale_20, theta0, sign, i_date, i_eyepiece, i_rho, i_drho, i_theta, i_dtheta, comments_wanted); fclose(fp_in); fclose(fp_out); return(0); } /************************************************************************* * * INPUT: * i_eyepiece: column nber of eyepiece focal length information * i_rho: column nber with rho values * i_drho: column nber with drho values * i_theta: column nber with theta values * i_dtheta: column nber with dtheta values * comments_wanted: 1 if comments are wanted, 0 otherwise *************************************************************************/ static int latex_calib_copy(FILE *fp_in, FILE *fp_out, double scale_10, double scale_20, double theta0, double sign, int i_date, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta, int comments_wanted) { char b_in[NMAX], b_data[NMAX]; int inside_array, line_is_opened, status; int line_with_object_name; char *pc, *pc1; inside_array = 0; line_is_opened = 0; while(!feof(fp_in)) { /* Maximum length for a line will be 170 characters: */ if(fgets(b_in,170,fp_in)) { line_with_object_name = 0; b_in[169] = '\0'; if(!strncmp(b_in,"\\begin{tabular}",15)){ inside_array = 1; #ifdef DEBUG printf(" OK: >%s< inside_array=%d\n", b_in, inside_array); #endif } else if(!strncmp(b_in,"\\end{tabular}",13)){ inside_array = 0; #ifdef DEBUG printf(" OK: >%s< inside_array=%d\n", b_in, inside_array); #endif } else if(inside_array && b_in[0] != '%' && strncmp(b_in,"\\hline",6)) { if(!line_is_opened) { strcpy(b_data, b_in); } /* Fill the data array with the next line */ else { /* Look for the first zero (end of string marker) in data buffer */ b_data[119] = '\0'; pc1 = b_data; while(*pc1) pc1++; pc1--; /* Then copy the second line from there*/ strcpy(pc1, b_in); } /* Check if this line is ended with "\\": */ line_is_opened = 1; pc = b_data; while(*pc) { if(!strncmp(pc,"\\\\",2)){ line_is_opened = 0; pc += 2; *pc = '\n'; pc++; *pc = '\0'; break; } pc++; } #ifdef DEBUG printf(" Data line: >%s<\n", b_data); printf(" line_is_opened=%d\n", line_is_opened); #endif if(!line_is_opened) { status = calib_data_copy(b_data, b_in, scale_10, scale_20, theta0, sign, i_date, i_eyepiece, i_rho, i_drho, i_theta, i_dtheta); } } if(comments_wanted ) { if(!line_is_opened) fputs(b_in,fp_out); } else { if(!line_is_opened && b_in[0] != '%') fputs(b_in,fp_out); } } /* EOF if fgets() */ } /* EOF while loop */ return(0); } /************************************************************************* * Publication mode * * INPUT: * i_eyepiece: column nber of eyepiece focal length information * i_rho: column nber with rho values * i_drho: column nber with drho values * i_theta: column nber with theta values * i_dtheta: column nber with dtheta values * comments_wanted: 1 if comments are wanted, 0 otherwise *************************************************************************/ static int latex_calib_publi(FILE *fp_in, FILE *fp_out, double scale_10, double scale_20, double theta0, double sign, int i_filename, int i_date, int i_filter, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta, int i_notes, int comments_wanted, int work_mode) { OBJECT *obj; int *index_obj; int nobj; if((obj = (OBJECT *)malloc(NOBJ_MAX * sizeof(OBJECT))) == NULL) { printf("Fatal error allocating memory space for OBJECT: nobj_max=%d\n", NOBJ_MAX); exit(-1); } if((index_obj = (int *)malloc((NOBJ_MAX) * sizeof(int))) == NULL) { printf("Fatal error allocating memory space for index_obj: nobj_max=%d\n", NOBJ_MAX); exit(-1); } read_measures(fp_in, comments_wanted, obj, &nobj, i_filename, i_date, i_filter, i_eyepiece, i_rho, i_drho, i_theta, i_dtheta, i_notes); #ifdef DEBUG printf("Returned by read_measures: nobj = %d\n", nobj); #endif calibrate_measures(obj, nobj, scale_10, scale_20, theta0, sign); /* Sort the objects according to their Right Ascension: */ ra_sort_objects(obj, index_obj, nobj); /* Compute mean values for the objects with rho < 0.3" (Merate-Paper II) */ mean_for_paper2(obj, nobj); write_publi_table(fp_out, comments_wanted, obj, index_obj, nobj); compute_statistics(fp_out, obj, nobj); free(index_obj); free(obj); return(0); } /***************************************************************************** * Write the LateX array in a new format * *****************************************************************************/ static int write_publi_table(FILE *fp_out, int comments_wanted, OBJECT *obj, int *index_obj, int nobj) { MEASURE *me; int good_q, nm, io, nlines, jj, nl_max = 50; char qflag[20], asterisc[20], exclam[20], q_error[1]; register int i, j; /* Portrait: nl_max=50 */ /* Landscape: nl_max= 30 */ nl_max = 30; strcpy(asterisc,"\\rlap{$^*$}"); strcpy(exclam,"\\rlap{!!}"); fprintf(fp_out,"\\def\\idem{''} \n"); nlines = -1; for(i = 0; i < nobj; i++) { io = index_obj[i]; nm = (obj[io]).nmeas; /* New table header in publi_mode */ if(nlines > nl_max) { fprintf(fp_out,"& & & & & & & & & & & \\\\ \n"); fprintf(fp_out,"\\hline \n"); fprintf(fp_out,"\\end{tabular} \n"); fprintf(fp_out,"\\end{table} \n"); } if((nlines == -1) || (nlines > nl_max)) { fprintf(fp_out,"\\begin{table} \n"); fprintf(fp_out,"\\tabcolsep=1mm \n"); fprintf(fp_out,"\\begin{tabular}{cccccccccccc} \n"); fprintf(fp_out,"\\hline \n"); fprintf(fp_out,"& & & & & & & & & & & \\\\ \n"); fprintf(fp_out,"WDS & Name & ADS & Epoch & Fil. & Eyep. & $\\rho$ & $\\sigma_\\rho$ & $\\theta$ & $\\sigma_\\theta$ & Orb. & Notes \\\\ \n"); fprintf(fp_out,"& & & & & (mm)& (arcsec) & (arcsec) & (deg.) & (deg.) & & \\\\ \n"); fprintf(fp_out,"& & & & & & & & & & & \\\\ \n"); fprintf(fp_out,"\\hline \n"); fprintf(fp_out,"& & & & & & & & & & & \\\\ \n"); nlines = 0; } jj = 0; /************* Loop on measurements: **********************/ for(j = 0; j < nm; j++) { me = &(obj[io]).measure[j]; /* BOF case not_flagged */ if(!me->flagged_out) { /* printf("i= %d io=%d nm=%d j=%d flag=%d\n", i, io, nm, j, me->flagged_out); printf(" WDS=%s rho=%.2f drho=%.2f theta=%.2f dtheta=%.2f eyepiece=%d\n", obj[io].wds, me->rho, me->drho, me->theta, me->dtheta, me->eyepiece); */ good_q = good_quadrant(me); if(good_q == 1) strcpy(qflag,asterisc); else if(good_q == -1) { strcpy(qflag,exclam); printf(" write_publi_table/Quadrant incompatible with theta value for %s!\n",obj[io].wds); } else strcpy(qflag," "); *q_error = (me->dquadrant == 1) ? '?' : ' '; if(jj == 0) { /*** Format for first line of an object */ if(me->rho != NO_DATA) #ifdef Q_IN_NOTES fprintf(fp_out,"%s & %s & %s & %.3f & %s & %d & %.3f & %.3f & %.1f%s & %.1f & %d & %s q=%d%c\\\\\n", obj[io].wds, obj[io].name, obj[io].ads, me->epoch, me->filter, me->eyepiece, me->rho, me->drho, me->theta, qflag, me->dtheta, obj[io].orbit, me->notes, me->quadrant, *q_error); #else fprintf(fp_out,"%s & %s & %s & %.3f & %s & %d & %.3f & %.3f & %.1f%s & %.1f & %d & %s \\\\\n", obj[io].wds, obj[io].name, obj[io].ads, me->epoch, me->filter, me->eyepiece, me->rho, me->drho, me->theta, qflag, me->dtheta, obj[io].orbit, me->notes); #endif else fprintf(fp_out,"%s & %s & %s & %.3f & %s & %d & \\nodata & \\nodata & \\nodata & \\nodata & %d & %s \\\\\n", obj[io].wds, obj[io].name, obj[io].ads, me->epoch, me->filter, me->eyepiece, obj[io].orbit, me->notes); } /* EOF j == 0 */ /*** Format for subsequent lines of an object */ else { if(me->rho != NO_DATA) #ifdef Q_IN_NOTES fprintf(fp_out,"\\idem & \\idem & \\idem & %.3f & %s & %d & %.3f & %.3f & %.1f%s & %.1f & %d & %s q=%d%c\\\\\n", me->epoch, me->filter, me->eyepiece, me->rho, me->drho, me->theta, qflag, me->dtheta, obj[io].orbit, me->notes, me->quadrant, *q_error); #else fprintf(fp_out,"\\idem & \\idem & \\idem & %.3f & %s & %d & %.3f & %.3f & %.1f%s & %.1f & %d & %s\\\\\n", me->epoch, me->filter, me->eyepiece, me->rho, me->drho, me->theta, qflag, me->dtheta, obj[io].orbit, me->notes); #endif else fprintf(fp_out,"\\idem & \\idem & \\idem & %.3f & %s & %d & \\nodata & \\nodata & \\nodata & \\nodata & %d & %s \\\\\n", me->epoch, me->filter, me->eyepiece, obj[io].orbit, me->notes); } /* EOF j != 0 */ nlines++; jj++; } /* EOF case not_flagged */ } /* EOF loop on j */ } /* EOF loop on i */ fprintf(fp_out,"& & & & & & & & & & & \\\\ \n"); fprintf(fp_out,"\\hline \n"); fprintf(fp_out,"\\end{tabular} \n"); fprintf(fp_out,"\\end{table} \n"); return(0); } /***************************************************************************** * Read the measurements and object parameters from the input file * *****************************************************************************/ static int read_measures(FILE *fp_in, int comments_wanted, OBJECT *obj, int *nobj, int i_filename, int i_date, int i_filter, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta, int i_notes) { char b_in[NMAX], b_data[NMAX]; char wds_name[40], official_name[40], ads_name[40]; int inside_array, line_is_opened, status, orbit, line_to_reject; char *pc, *pc1; inside_array = 0; line_to_reject = 0; line_is_opened = 0; wds_name[0] = '\0'; official_name[0] = '\0'; ads_name[0] = '\0'; orbit = 0; *nobj = 0; while(!feof(fp_in)) { /* Maximum length for a line will be 170 characters: */ if(fgets(b_in,170,fp_in)) { b_in[169] = '\0'; if(!strncmp(b_in,"\\begin{tabular}",15)){ inside_array = 1; strcpy(b_in,"\\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|} \n"); } else if(!strncmp(b_in,"\\end{tabular}",13)){ inside_array = 0; } else if(inside_array && b_in[0] != '%' && strncmp(b_in,"\\hline",6)) { if(!line_is_opened) { strcpy(b_data, b_in); } /* Fill the data array with the next line */ else { /* Look for the first zero (end of string marker) in data buffer */ b_data[119] = '\0'; pc1 = b_data; while(*pc1) pc1++; pc1--; /* Then copy the second line from there*/ strcpy(pc1, b_in); } /* Check if this line is ended with "\\": */ line_is_opened = 1; pc = b_data; while(*pc) { if(!strncmp(pc,"\\\\",2)){ line_is_opened = 0; pc += 2; *pc = '\n'; pc++; *pc = '\0'; break; } pc++; } if(!line_is_opened) { #ifdef DEBUG printf(" Data line: >%s<\n", b_data); #endif status = check_measure(b_data, i_eyepiece, i_rho, i_drho, i_theta, i_dtheta); if(!status) { add_new_measure(b_data, obj, *nobj, i_filename, i_date, i_filter, i_eyepiece, i_rho, i_drho, i_theta, i_dtheta, i_notes); } else { /* Try to add a new object: */ status = add_new_object(b_data, obj, nobj); } } /* EOF !line_is_opened */ } } /* EOF if fgets() */ } /* EOF while loop */ return(0); } /************************************************************************** * **************************************************************************/ static int add_new_object(char *b_data, OBJECT *obj, int *nobj) { OBJECT *ob; char wds_name[40], official_name[40], ads_name[40], *pc, buffer[40]; int status, orbit, ih, im; ob = &obj[*nobj]; status = read_object_name(b_data, wds_name, official_name, ads_name, &orbit); if(!status) { strcpy(ob->wds, wds_name); strcpy(ob->ads, ads_name); strcpy(ob->name, official_name); ob->nmeas = 0; ob->orbit = orbit; (*nobj)++; /* Decode Right Ascension from WDS name: */ ob->ra = 0.; strcpy(buffer, wds_name); pc = buffer; while(*pc && (*pc != '+') && (*pc != '-')) pc++; if((*pc == '+') || (*pc == '-')) { *pc = '\0'; sscanf(buffer,"%2d%3d", &ih, &im); /* Divide "im" by 600, since "im" is measured in tenths of minutes: */ ob->ra = (double)ih + ((double)im)/600.; } /* Decode Declination from WDS name: */ ob->dec = 0.; pc = wds_name; while(*pc && (*pc != '+') && (*pc != '-')) pc++; if((*pc == '+') || (*pc == '-')) { strcpy(buffer,pc); sscanf(buffer,"%d", &ih); ob->dec = ih; } #ifdef DEBUG printf(" New object added: nobj = %d\n", *nobj); printf(" name= %s %s %s orbit=%d", ob->wds, ob->name, ob->ads, ob->orbit); printf(" ra= %f dec=%d\n", ob->ra, ob->dec); #endif } return(status); } /************************************************************************* * 22388+4419 = HO 295 AB & ADS 16138 & 2004. & & & & & & & orb \\ *************************************************************************/ static int read_object_name(char *b_data, char *wds_name, char *official_name, char *ads_name, int *orbit) { char *pc, buff[60]; int istat, status, icol; status = 1; /* First step: decodes WDS name: */ icol = 1; istat = read_svalue(b_data, buff, icol); if(istat) { #ifdef DEBUG printf("read_object_name/Error reading column #%d\n", icol); #endif status = -1; return(status); } pc = buff; buff[59]='\0'; /* Look for the second item (official name) starting after a "=" symbol: */ while(*pc && *pc != '=') pc++; if(*pc == '=') { pc++; strcpy(official_name, pc); status = 0; } /* Look for the first item ending with a "=" symbol: */ if(!status) { pc = buff; while(*pc && *pc != '=') pc++; if(*pc == '=') { *pc = '\0'; strcpy(wds_name, buff); status = 0; *orbit = 0; } /* Reads ADS name in 2nd column: */ icol = 2; ads_name[0] = '\0'; istat = read_svalue(b_data, buff, icol); if(!istat){ pc = buff; while(*pc && strncmp(pc,"ADS",3)) pc++; if(!strncmp(pc,"ADS",3)){ pc +=3; strcpy(ads_name, pc); } } /* Then tries to read "orb" in column notes: */ icol = 10; istat = read_svalue(b_data, buff, icol); if(!istat) { pc = buff; while(*pc && *pc != 'o') pc++; if(*pc == 'o') { if(!strncmp(pc,"orb",3)) *orbit = 1; } } } /* EOF !status case */ return(status); } /************************************************************************* * Check whether input line is a measurement * * INPUT: * i_eyepiece: column nber of eyepiece focal length information * i_rho: column nber with rho values * i_drho: column nber with drho values * i_theta: column nber with theta values * i_dtheta: column nber with dtheta values *************************************************************************/ static int check_measure(char *b_data, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta) { int status; double ww; status = read_fvalue(b_data, &ww, i_rho); if(!status) status = read_fvalue(b_data, &ww, i_drho); if(!status) status = read_fvalue(b_data, &ww, i_theta); if(!status) status = read_fvalue(b_data, &ww, i_dtheta); if(!status) status = read_fvalue(b_data, &ww, i_eyepiece); return(status); } /************************************************************************* * * INPUT: * i_eyepiece: column nber of eyepiece focal length information * i_rho: column nber with rho values * i_drho: column nber with drho values * i_theta: column nber with theta values * i_dtheta: column nber with dtheta values * wds_name, official_name, ads_name : object designation in various catalogues * orbit: flag, set to one if orbit is known, 0 otherwise *************************************************************************/ static int calibrate_measures(OBJECT *obj, int nobj, double scale_10, double scale_20, double theta0, double sign) { MEASURE *me; double scale; int nm; register int i, j; for(i = 0; i < nobj; i++) { nm = (obj[i]).nmeas; for(j = 0; j < nm; j++) { me = &(obj[i]).measure[j]; /* Scale according to eyepiece: */ if(me->eyepiece == 10) scale = scale_10; else scale = scale_20; if(me->rho != NO_DATA) { me->rho *= scale; me->drho *= scale; me->theta = me->theta * sign + theta0; while(me->theta < 0.) me->theta += 360.; while(me->theta >= 360.) me->theta -= 360.; } } /* EOF loop on j */ } /* EOF loop on i */ return(0); } /************************************************************************* * * INPUT: * i_eyepiece: column nber of eyepiece focal length information * i_rho: column nber with rho values * i_drho: column nber with drho values * i_theta: column nber with theta values * i_dtheta: column nber with dtheta values * wds_name, official_name, ads_name : object designation in various catalogues * orbit: flag, set to one if orbit is known, 0 otherwise *************************************************************************/ static int calib_data_copy(char *b_data, char *b_out, double scale_10, double scale_20, double theta0, double sign, int i_date, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta) { int status, eyepiece; double epoch, rho, drho, theta, dtheta, scale; char date[30]; status = decode_data(b_data, date, &epoch, &rho, &drho, &theta, &dtheta, &eyepiece, i_date, i_eyepiece, i_rho, i_drho, i_theta, i_dtheta); if(status) { strcpy(b_out, b_data); return(1); } if(eyepiece == 10) scale = scale_10; else scale = scale_20; if(rho != NO_DATA) { rho *= scale; drho *= scale; theta = theta * sign + theta0; while(theta < 0.) theta += 360.; while(theta >= 360.) theta -= 360.; dtheta = dtheta; /* rho and drho with 3 decimals */ status = write_fvalue(b_data, b_out, rho, i_rho, 3); if(!status) { strcpy(b_data, b_out); status = write_fvalue(b_data, b_out, drho, i_drho, 3); } /* theta and dtheta with 1 decimal */ if(!status) { strcpy(b_data, b_out); status = write_fvalue(b_data, b_out, theta, i_theta, 1); } if(!status) { strcpy(b_data, b_out); status = write_fvalue(b_data, b_out, dtheta, i_dtheta, 1); } } /* EOF !NO_DATA */ /* epoch with 3 decimals */ if((epoch > 0) && (!status)) { strcpy(b_data, b_out); status = write_fvalue(b_data, b_out, epoch, i_date, 3); } if(status) { printf("calib_data/Fatal error, updating array!\n"); exit(-1); } return(0); } /************************************************************************** * * INPUT: * i_eyepiece: column nber of eyepiece focal length information * i_rho: column nber with rho values * i_drho: column nber with drho values * i_theta: column nber with theta values * i_dtheta: column nber with dtheta values * * OUTPUT: * rho, drho, theta, dtheta * eyepiece * epoch * **************************************************************************/ static int add_new_measure(char *b_data, OBJECT *obj, int nobj, int i_filename, int i_date, int i_filter, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta, int i_notes) { MEASURE *me; double epoch, rho, drho, theta, dtheta, ww; char notes[40], filter[10], date[30], filename[40]; int eyepiece, quadrant, dquadrant, status, nm; /* Return if no object has been entered yet: */ if(nobj <= 0) return(-1); eyepiece = 0; quadrant = 0; dquadrant = 0; rho = 0.; drho = 0.; theta = 0.; dtheta = 0.; epoch = 0.; filter[0] = '\0'; notes[0] = '\0'; /* Read date: */ epoch = 0.; status = read_epoch_value(b_data, date, &epoch, i_date); status = read_fvalue(b_data, &rho, i_rho); if(!status) status = read_fvalue(b_data, &drho, i_drho); if(!status) status = read_fvalue(b_data, &theta, i_theta); if(!status) status = read_fvalue(b_data, &dtheta, i_dtheta); if(!status) { status = read_fvalue(b_data, &ww, i_eyepiece); eyepiece = (int)(ww+0.5); } /* Read non-compulsory parameters */ read_svalue(b_data, filename, i_filename); read_svalue(b_data, filter, i_filter); read_svalue(b_data, notes, i_notes); /* Read the quadreant value if present, and removes "Q=" from notes */ read_quadrant(notes, &quadrant, &dquadrant); /* Store data and increase nber of measurements for this object */ if(!status) { nm = (obj[nobj-1]).nmeas; me = &(obj[nobj-1]).measure[nm]; me->rho = rho; /* Minimum value for rho error: 0.1 pixel or 0.5% */ drho = MAXI(drho, 0.1); me->drho = MAXI(drho, rho*0.005); me->theta = theta; /* Minimum value for theta error: 0.3 degree */ me->dtheta = MAXI(dtheta, 0.3); me->eyepiece = eyepiece; me->quadrant = quadrant; me->dquadrant = dquadrant; me->epoch = epoch; me->flagged_out = 0; strcpy(me->filename, filename); strcpy(me->filter, filter); strcpy(me->notes, notes); strcpy(me->date, date); ((obj[nobj-1]).nmeas)++; #ifdef DEBUG printf(" nobj=%d, new measure successfully added (nm=%d)\n", nobj, (obj[nobj-1]).nmeas); printf(" rho=%.2f drho=%.2f theta=%.2f dtheta=%.2f eyep.=%d Q=%d dQ=%d notes=>%s<\n", me->rho, me->drho, me->theta, me->dtheta, me->eyepiece, me->quadrant, me->dquadrant, me->notes); #endif } #ifdef DEBUG else printf("add_new_measure/Failure adding new measurement \n"); #endif return(status); } /************************************************************************** * * INPUT: * i_eyepiece: column nber of eyepiece focal length information * i_rho: column nber with rho values * i_drho: column nber with drho values * i_theta: column nber with theta values * i_dtheta: column nber with dtheta values * * OUTPUT: * rho, drho, theta, dtheta * eyepiece * epoch * **************************************************************************/ static int decode_data(char *b_data, char *date, double *epoch, double *rho, double *drho, double *theta, double *dtheta, int *eyepiece, int i_date, int i_eyepiece, int i_rho, int i_drho, int i_theta, int i_dtheta) { double ww; int status; *eyepiece = 0; *rho = *drho = *theta = *dtheta = 0; /* Read date: */ *epoch = 0.; status = read_epoch_value(b_data, date, epoch, i_date); status = read_fvalue(b_data, rho, i_rho); if(!status) status = read_fvalue(b_data, drho, i_drho); if(!status) status = read_fvalue(b_data, theta, i_theta); if(!status) status = read_fvalue(b_data, dtheta, i_dtheta); if(!status) { status = read_fvalue(b_data, &ww, i_eyepiece); *eyepiece = (int)(ww+0.5); } #ifdef DEBUG if(!status) printf(" rho=%.2f drho=%.2f theta=%.2f dtheta=%.2f eyepiece=%d\n", *rho, *drho, *theta, *dtheta, *eyepiece); #endif return(status); } /************************************************************************** * Read decimal value in column #icol from b_data string * **************************************************************************/ static int read_dvalue(char *b_data, int *value, int icol) { int ival, status; char buff[40]; *value = 0.; status = read_svalue(b_data, buff, icol); if(!status) { ival = sscanf(buff, "%d", value); printf("read_dvalue/buff=>%s< value=%d ival=%d\n", buff, *value, ival); /* */ if(ival <= 0) status = 1; } return(status); } /************************************************************************** * Read double value in column #icol from b_data string * **************************************************************************/ static int read_fvalue(char *b_data, double *value, int icol) { int ival, status; char buff[40], nodata[40]; *value = 0.; status = read_svalue(b_data, buff, icol); if(!status) { sscanf(buff, "%s", nodata); if(!strncmp(nodata,"\\nodata",7)) { /* printf("read_fvalue: nodata found! \n"); */ *value = NO_DATA; } else { ival = sscanf(buff, "%lf", value); if(ival <= 0) { /* printf("read_fvalue/buff=>%s< value=%.2f ival=%d\n", buff, *value, ival); */ status = 1; } } } return(status); } /************************************************************************** * Read epoch value from date information in column #icol from b_data string * * Input format: dd/mm/yy, e.g. 12/2/2004 or 01/12/1998 or 31/06/2002 * Output: epoch, as a fraction of year, e.g. 2004.234 * **************************************************************************/ static int read_epoch_value(char *b_data, char *date, double *epoch , int icol) { int ival, status, dd, mm, iyy; double yy, time, jdate, jdate_jan01; /* Read date: */ date[0] = '\0'; status = read_svalue(b_data, date, icol); /* Removes the blanks in "date" string: */ sscanf(date, "%s", date); if(!status) { ival = sscanf(date, "%d/%d/%d", &dd, &mm, &iyy); /* printf("read_epoch_value/date=>%s< dd=%d mm=%d iyy=%d ival=%d\n", date, dd, mm, iyy, ival); */ if(ival < 3) status = 1; } if(!status) { /* Assume observations at 10:30 pm, local time, i.e., 8:30 (U.T) in summer */ /* Assume observations at 9:30 pm, local time, i.e., 8:30 (U.T) in winter */ time = 20.5; yy = (double)iyy; status = julian(yy, mm, dd, time, &jdate); /* 1st of January at 0.00: */ julian(yy, 1, 1, 0., &jdate_jan01); *epoch = yy + (jdate - jdate_jan01)/365.25; /* printf("read_epoch_value/jdate=%f jdate_jan01=%f epoch=%f\n", jdate, jdate_jan01, *epoch); */ } return(status); } /************************************************************************** * Read string value in column #icol from b_data string * **************************************************************************/ static int read_svalue(char *b_data, char *value, int icol) { int ic, status, column_is_found; char buff[NMAX], data[NMAX], *pc; strcpy(data, b_data); pc = data; data[NMAX-1] = '\0'; column_is_found = 0; ic = 1; buff[0] = '\0'; while(*pc) { if(ic == icol) { column_is_found = 1; strcpy(buff,pc); break; } if(*pc == '&') { ic++; } pc++; } *pc = '\0'; /* Return if column not found, or empty */ if(!buff[0]) return(-1); /* Otherwise go on analysis: */ status = 1; buff[NMAX-1] = '\0'; pc = buff; while(*pc) { if(*pc == '&' || !strncmp(pc,"\\\\",2)) { *pc = '\0'; *value = '\0'; strcpy(value,buff); if(*value) status = 0; break; } pc++; } return(status); } /************************************************************************** * Write a double value in column #icol to b_out string * **************************************************************************/ static int write_fvalue(char *b_data, char *b_out, double value, int icol, int nber_of_decimals) { int ic, column_is_found, istart, iend; char data[360], *pc; register int i; strcpy(data, b_data); pc = data; column_is_found = 0; ic = 1; i = 0; while(*pc) { if(ic == icol && !column_is_found) { column_is_found = 1; istart = i; } else if(ic == icol+1) { iend = i-1; break; } if(*pc == '&') { ic++; } pc++; i++; } /* Return if column not found, or empty */ if(istart == 0 || iend == istart) return(-1); strcpy(b_out, b_data); switch(nber_of_decimals) { case 1: sprintf(&b_out[istart],"%8.1f ",value); break; case 2: sprintf(&b_out[istart],"%8.2f ",value); break; case 3: default: sprintf(&b_out[istart],"%8.3f ",value); break; case 4: sprintf(&b_out[istart],"%9.4f ",value); break; } strcpy(&b_out[istart+9],&b_data[iend]); /* printf("update_value/from >%s< to >%s< (value=%.2f)\n", b_data, b_out, value); */ return(0); } /********************************************************************* * Subroutine JULIAN to compute the Julian day of an observation: * (from "cel_meca.c") * * The Julian day begins at Greenwich mean noon (at 12 U.T.) * * Here also the Gregorian calendar reform is taken into account. * Thus the day following 1582 October 4 is 1582 October 15. * * The B.C. years are counted astronomically. Thus the year * before the year +1 is the year 0. * * Input: * AA, MM, IDD, TIME : year,month, day, time of the observation * DJUL : Julian day **********************************************************************/ int julian(double aa, int mm, int idd, double time, double *djul) { double day1, year1, date_obs, date_reform; long month1, ia1, ib1; day1 = time/24. + (double)idd; /* First the year after the 1st March ... */ if(mm > 2) { year1 = aa; month1 = mm; } else { year1 = aa - 1; month1 = mm + 12; } /* Then check if after the Gregorian reform: */ date_obs = aa + ((int)(275 * mm / 9) - 2. * (int) ((mm + 9) / 12) + idd - 30 ) / 365.; date_reform = 1582. + 289./365.; if(date_obs >= date_reform) { ia1 = (int) (year1 / 100.); ib1 = 2 - ia1 + (int) (((double)ia1)/4.); } else ib1 = 0; /* Now final formula: */ *djul = (int)(365.25 * year1) + (int)(30.6001 * (month1 + 1)) + day1 + 1720994.5 + ib1; return(0); } /*************************************************************************** * ra_sort_objects * Calling routine int JLP_QSORT_INDX(double *array, int *index, int *nn) * INPUT: * array[nn]: array to be sorted * * OUTPUT: * array[nn]: sorted array * index[nn]: array giving the index of the input array, * to sort other arrays in the same way if necessary * (f.i. array2[i] := array2[index[i]]) ****************************************************************************/ static int ra_sort_objects(OBJECT *obj, int *index_obj, int nobj) { double *ra; int j1, j2, nswap; register int i; ra = (double *)malloc((nobj) * sizeof(double)); for(i = 0; i < nobj; i++) ra[i] = obj[i].ra; JLP_QSORT_INDX(ra, index_obj, &nobj); /* Final check on declination criterion too: */ nswap = 1; while(nswap > 0) { nswap = 0; for(i = 0; i < nobj-1; i++) { j1 = index_obj[i]; j2 = index_obj[i+1]; /* Swap indices if declination is not sorted out: */ if((obj[j1].ra == obj[j2].ra) && (obj[j1].dec > obj[j2].dec)) { index_obj[i] = j2; index_obj[i+1] = j1; nswap++; #ifdef DEBUG printf("ra1=%f ra2=%f dec1=%d dec2=%d\n", obj[j1].ra, obj[j2].ra, obj[j1].dec, obj[j2].dec); #endif } } /* EOF loop on i */ #ifdef DEBUG printf("Sorting declination now: nswap=%d for this iteration\n",nswap); #endif } /* EOF while loop */ free(ra); return(0); } /**************************************************************************** * Quicksort (Cf. "C: The complete reference", Herbert Schildt) * * INPUT: * array[nn]: array to be sorted * * OUTPUT: * array[nn]: sorted array * index[nn]: array giving the index of the input array, * to sort other arrays in the same way if necessary * (f.i. array2[i] := array2[index[i]]) ****************************************************************************/ static int JLP_QSORT_INDX(double *array, int *index, int *nn) { register int i; /* Initialization of index array: */ for(i = 0; i < *nn; i++) index[i] = i; if(*nn < 2) return(0); qs2(array, index, 0, (*nn)-1); return(0); } /************************************************************************** * The Quicksort, with index array ***************************************************************************/ static void qs2(double *array, int *index, int left, int right) { register int i, j; int iy; double x, y; i = left; j = right; /* Take the element in the middle as reference to partition the array: */ x = array[(left+right)/2]; /* Put the elements < x to the left and those > x to the right: */ do { while(array[i] < x && i < right) i++; while(x < array[j] && j > left) j--; if(i <= j) { /* Exchange array[i] and array[j]: */ y = array[i]; array[i] = array[j]; array[j] = y; /* Exchange index[i] and index[j]: */ iy = index[i]; index[i] = index[j]; index[j] = iy; i++; j--; } } while(i<=j); if(left < j) qs2(array, index, left, j); if(i < right) qs2(array, index, i, right); return; } /************************************************************************* * Compute mean values for the objects with rho < 0.3" (Merate-Paper II) **************************************************************************/ static int mean_for_paper2(OBJECT *obj, int nobj) { MEASURE *me, *me_prev; int rec_dir, rec_dir_prev, nm, no_data_prev, no_data; register int i, j; for(i = 0; i < nobj; i++) { nm = (obj[i]).nmeas; me_prev = NULL; for(j = 0; j < nm; j++) { me = &(obj[i]).measure[j]; /* rec_dir = 1 if recorded file * = -1 if direct file * = 0 otherwise */ if(is_record_file(me->filename) == 1) rec_dir = 1; else if(is_direct_file(me->filename) == 1) rec_dir = -1; else rec_dir = 0; no_data = ((me->rho == NO_DATA) || (me->theta == NO_DATA)) ? 1 : 0; /* Store current parameters (they become "previous" parameters in next * iteration if same object) */ if(me_prev == NULL) { rec_dir_prev = rec_dir; no_data_prev = no_data; me_prev = me; } else { /* Process measurements when two measurements refer to same epoch, * with direct/recorded files: */ if((me->epoch == me_prev->epoch) && (me->filter[0] == me_prev->filter[0]) && (me->eyepiece == me_prev->eyepiece) && (rec_dir * rec_dir_prev) == -1) { /* If two measurements have been made: */ if(!no_data && !no_data_prev) { /* Handle quadrant: */ if(me->quadrant == -1 && me_prev->quadrant == 0) me_prev->quadrant = -1; if(me->quadrant == 0 && me_prev->quadrant == -1) me->quadrant = -1; if(me->quadrant > 0 && me_prev->quadrant <= 0) { me_prev->quadrant = me->quadrant; me_prev->dquadrant = me->dquadrant; } if(me_prev->quadrant > 0 && me->quadrant <= 0) { me->quadrant = me_prev->quadrant; me->dquadrant = me_prev->dquadrant; } /* Handle rho and theta: */ if(me->rho > 0.3) { /* if rec and dir_prev */ if(rec_dir == 1 && rec_dir_prev == -1) me->flagged_out = 1; /* if dir and rec_prev */ if(rec_dir == -1 && rec_dir_prev == 1) me_prev->flagged_out = 1; } else compute_mean_for_paper2(obj, i, j); } /* EOF !no_data && !no_data_prev */ /* Special handling when NO_DATA were present for both measurements: */ /* Removes the second measurement (NB: the 2nd is the same as the first): */ else if(no_data && no_data_prev) me->flagged_out = 1; /* Case when only one mesurement over two files: */ else { if(no_data) me->flagged_out = 1; else if(no_data_prev) me_prev->flagged_out = 1; } /* Second file was linked to first, I neutralize it for further inspection */ me_prev = NULL; } /* EOF epoch == epoch_prev */ /* Second file was not linked to first, it may be linked to next: */ else { rec_dir_prev = rec_dir; no_data_prev = no_data; me_prev = me; } } /* EOF me_prev != NULL */ /* Go to next measurement */ } /* EOF loop on j (measurements) */ /* Go to next object */ } /* EOF loop on i (objects) */ return(0); } /************************************************************************ * Check if recorded file, * i.e. filename with _Rr _Vr or _Sfr * ************************************************************************/ static int is_record_file(char *filename) { char *pc; int is_record_file; is_record_file = 0; /* Check if recorded file: */ pc = filename; while(*pc && strncmp(pc,"_Vr",3) && strncmp(pc,"_Rr",3) && strncmp(pc,"_Sfr",4) && strncmp(pc,"_s.f.r",6)) pc++; if(!strncmp(pc,"_Vr",3) || !strncmp(pc,"_Rr",3) || !strncmp(pc,"_Sfr",4) || !strncmp(pc,"_s.f.r",6)) is_record_file = 1; return(is_record_file); } /************************************************************************ * Check if direct file, * i.e. filename with _Rd _Vd or _Sfd * ************************************************************************/ static int is_direct_file(char *filename) { char *pc; int is_direct_file; is_direct_file = 0; /* Check if direct file: */ pc = filename; while(*pc && strncmp(pc,"_Vd",3) && strncmp(pc,"_Rd",3) && strncmp(pc,"_Sfd",4) && strncmp(pc,"_s.f.d",6)) pc++; if(!strncmp(pc,"_Vd",3) || !strncmp(pc,"_Rd",3) || !strncmp(pc,"_Sfd",4) || !strncmp(pc,"_s.f.d",6)) is_direct_file = 1; return(is_direct_file); } /************************************************************************ * * io: object index in obj * jm: measurement index in obj[io].measure ************************************************************************/ static int compute_mean_for_paper2(OBJECT *obj, int io, int jm) { MEASURE *me1, *me2; double w1, w2, sum; me1 = &(obj[io]).measure[jm-1]; me2 = &(obj[io]).measure[jm]; w1 = (me2->drho / (me1->drho + me2->drho)) + (me2->dtheta / (me1->dtheta + me2->dtheta)); w2 = (me1->drho / (me1->drho + me2->drho)) + (me1->dtheta / (me1->dtheta + me2->dtheta)); sum = w1 + w2; if(sum == 0) { printf("compute_mean_forp_paper2/Fatal: rms error is null for io=%d jm=%d\n", io, jm); exit(-1); } w1 /= sum; w2 /= sum; /* printf(" WDS=%s ADS=%s NAME=%s io=%d jm=%d dt1=%f dt2=%f dr1=%f dr2=%f w1=%f w2 =%f \n", (obj[io]).wds, (obj[io]).ads, (obj[io]).name, io, jm, me1->dtheta, me2->dtheta, me1->drho, me2->drho, w1, w2); */ me1->rho = me1->rho * w1 + me2->rho * w2; me1->theta = me1->theta * w1 + me2->theta * w2; me1->drho = sqrt((SQUARE(me1->drho) * w1 + SQUARE(me2->drho) * w2)); me1->dtheta = sqrt((SQUARE(me1->dtheta) * w1 + SQUARE(me2->dtheta) * w2)); me2->flagged_out = 1; return(0); } /*************************************************************************** * Read the quadrant value if present, and removes "Q=*" from notes * * INPUT: * notes: string from notes column of input file * * OUTPUT * quadrant: 0 if Q was not present * -1 if Q=? * 1, 2, 3 or 4 if Q=1, Q=2, Q=3 or Q=4 * notes: same as input string, but without "Q=*" * ***************************************************************************/ static int read_quadrant(char *notes, int *quadrant, int *dquadrant) { char *pc, buffer[40]; int status, k; status = 0; *quadrant=0; *dquadrant=0; pc = notes; k = 0; while(*pc && strncmp(pc,"Q=",2)) {pc++; buffer[k++] = *pc;} if(!strncmp(pc,"Q=",2)){ k--; pc +=2; switch(*pc) { case '1': *quadrant=1; break; case '2': *quadrant=2; break; case '3': *quadrant=3; break; case '4': *quadrant=4; break; case '?': default: *quadrant=-1; break; } /* Case when Q=1?, Q=2?, Q=3? or Q=4? */ if(*pc) pc++; if(*pc == '?') {pc++; *dquadrant = 1;} /* Normal syntax is f.i. "Q=4," */ while(*pc) {pc++; buffer[k++] = *pc;} buffer[k++] = '\0'; } /* Update notes, after removing quadrant indication: */ strcpy(notes,buffer); return(status); } /********************************************************************************* * Check if theta value is compatible with the quadrant value *********************************************************************************/ static int good_quadrant(MEASURE *me) { double theta; int quad, good_quad; good_quad = 0; quad = me->quadrant; theta = me->theta; switch(quad) { case 1: if(theta > -1. && theta < 91.) good_quad = 1; else good_quad = -1; break; case 2: if(theta > 89. && theta < 181.) good_quad = 1; else good_quad = -1; break; case 3: if(theta > 179. && theta < 271.) good_quad = 1; else good_quad = -1; break; case 4: if(theta > 269. && theta <= 360.) good_quad = 1; else good_quad = -1; break; default: break; } return(good_quad); } /********************************************************************* * *********************************************************************/ static int compute_statistics(FILE *fp_out, OBJECT *obj, int nobj) { MEASURE *me; int nm, nmeas, no_detected, no_data; int nquad, nquad_uncert, is_quad, is_bad_quad, nbad_quad; register int i, j; /* Compute number of measurements: */ nmeas = 0; no_detected = 0; nquad = 0; nquad_uncert = 0; nbad_quad = 0; for(i = 0; i < nobj; i++) { nm = (obj[i]).nmeas; for(j = 0; j < nm; j++) { me = &(obj[i]).measure[j]; if(!me->flagged_out) { nmeas ++; no_data = ((me->rho == NO_DATA) || (me->theta == NO_DATA)) ? 1 : 0; no_detected += no_data; is_quad = (me->quadrant > 0) ? 1 : 0; nquad += is_quad; nquad_uncert += me->dquadrant; is_bad_quad = (good_quadrant(me) == -1) ? 1 : 0; nbad_quad += is_bad_quad; } } } printf(" Number of objects: %d \n", nobj); fprintf(fp_out, " Number of objects: %d \n \n", nobj); printf(" Number of observations: %d with %d measurements and %d cases of no detection \n ", nmeas, nmeas - no_detected, no_detected); fprintf(fp_out, " Number of observations: %d with %d measurements and %d cases of no detection \n \n ", nmeas, nmeas - no_detected, no_detected); printf("Quadrant was determined for %d measurements (including %d uncertain determinations)\n", nquad, nquad_uncert); fprintf(fp_out, "Quadrant was determined for %d measurements (including %d uncertain determinations)\n \n", nquad, nquad_uncert); printf("Warning: %d quadrant values are inconsistent with theta values in this table! \n", nbad_quad); fprintf(fp_out,"Warning: %d quadrant values are inconsistent with theta values in this table! \n \n", nbad_quad); return(0); }
the_stack_data/126126.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, L. Sekanina, Z. Vasicek "Libraries of Approximate Circuits: Automated Design and Application in CNN Accelerators" IEEE Journal on Emerging and Selected Topics in Circuits and Systems, Vol 10, No 4, 2020 * This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and ep parameters ***/ // MAE% = 0.24 % // MAE = 20 // WCE% = 0.78 % // WCE = 64 // WCRE% = 66.67 % // EP% = 49.22 % // MRE% = 0.65 % // MSE = 876 // PDK45_PWR = 0.043 mW // PDK45_AREA = 100.4 um2 // PDK45_DELAY = 0.47 ns #include <stdint.h> #include <stdlib.h> uint64_t add12u_4YR(uint64_t a, uint64_t b) { int wa[12]; int wb[12]; uint64_t y = 0; wa[0] = (a >> 0) & 0x01; wb[0] = (b >> 0) & 0x01; wa[1] = (a >> 1) & 0x01; wb[1] = (b >> 1) & 0x01; wa[2] = (a >> 2) & 0x01; wb[2] = (b >> 2) & 0x01; wa[3] = (a >> 3) & 0x01; wb[3] = (b >> 3) & 0x01; wa[4] = (a >> 4) & 0x01; wb[4] = (b >> 4) & 0x01; wa[5] = (a >> 5) & 0x01; wb[5] = (b >> 5) & 0x01; wa[6] = (a >> 6) & 0x01; wb[6] = (b >> 6) & 0x01; wa[7] = (a >> 7) & 0x01; wb[7] = (b >> 7) & 0x01; wa[8] = (a >> 8) & 0x01; wb[8] = (b >> 8) & 0x01; wa[9] = (a >> 9) & 0x01; wb[9] = (b >> 9) & 0x01; wa[10] = (a >> 10) & 0x01; wb[10] = (b >> 10) & 0x01; wa[11] = (a >> 11) & 0x01; wb[11] = (b >> 11) & 0x01; int sig_24 = wa[0] ^ wb[0]; int sig_25 = wa[0] & wb[0]; int sig_26 = wa[1] ^ wb[1]; int sig_27 = wa[1] & wb[1]; int sig_28 = sig_26 & sig_25; int sig_29 = sig_26 ^ sig_25; int sig_30 = sig_27 | sig_28; int sig_31 = wa[2] ^ wb[2]; int sig_32 = wa[2] & wb[2]; int sig_33 = sig_31 & sig_30; int sig_34 = sig_31 ^ sig_30; int sig_35 = sig_32 | sig_33; int sig_36 = wa[3] ^ wb[3]; int sig_37 = wa[3] & wb[3]; int sig_38 = sig_36 & sig_35; int sig_39 = sig_36 ^ sig_35; int sig_40 = sig_37 | sig_38; int sig_41 = wa[4] ^ wb[4]; int sig_42 = wa[4] & wb[4]; int sig_43 = sig_41 & sig_40; int sig_44 = sig_41 ^ sig_40; int sig_45 = sig_42 | sig_43; int sig_46 = wa[5] | wb[5]; int sig_49 = sig_46 | sig_45; int sig_51 = wa[6] ^ wb[6]; int sig_52 = wa[6] & wb[6]; int sig_54 = sig_51; int sig_55 = sig_52; int sig_56 = wa[7] ^ wb[7]; int sig_57 = wa[7] & wb[7]; int sig_58 = sig_56 & sig_55; int sig_59 = sig_56 ^ sig_55; int sig_60 = sig_57 | sig_58; int sig_61 = wa[8] ^ wb[8]; int sig_62 = wa[8] & wb[8]; int sig_63 = sig_61 & sig_60; int sig_64 = sig_61 ^ sig_60; int sig_65 = sig_62 | sig_63; int sig_66 = wa[9] ^ wb[9]; int sig_67 = wa[9] & wb[9]; int sig_68 = sig_66 & sig_65; int sig_69 = sig_66 ^ sig_65; int sig_70 = sig_67 | sig_68; int sig_71 = wa[10] ^ wb[10]; int sig_72 = wa[10] & wb[10]; int sig_73 = sig_71 & sig_70; int sig_74 = sig_71 ^ sig_70; int sig_75 = sig_72 | sig_73; int sig_76 = wa[11] ^ wb[11]; int sig_77 = wa[11] & wb[11]; int sig_78 = sig_76 & sig_75; int sig_79 = sig_76 ^ sig_75; int sig_80 = sig_77 | sig_78; y |= (sig_24 & 0x01) << 0; // default output y |= (sig_29 & 0x01) << 1; // default output y |= (sig_34 & 0x01) << 2; // default output y |= (sig_39 & 0x01) << 3; // default output y |= (sig_44 & 0x01) << 4; // default output y |= (sig_49 & 0x01) << 5; // default output y |= (sig_54 & 0x01) << 6; // default output y |= (sig_59 & 0x01) << 7; // default output y |= (sig_64 & 0x01) << 8; // default output y |= (sig_69 & 0x01) << 9; // default output y |= (sig_74 & 0x01) << 10; // default output y |= (sig_79 & 0x01) << 11; // default output y |= (sig_80 & 0x01) << 12; // default output return y; }
the_stack_data/90761438.c
#include <stdio.h> #include <string.h> #define P (1000 * 1000 * 1000 + 7) #define N (10000 + 1) #if 0 int checkRecord(int n, int a_cnt, int cl) { if (n == 0) { return 1; } int p = checkRecord(n - 1, a_cnt, 0); int a = 0; if (a_cnt <= 0) { a = checkRecord(n - 1, a_cnt + 1, 0); } int l = 0; if (cl <= 1) { l = checkRecord(n - 1, a_cnt, cl + 1); } return (p + a + l) % P; } void initTbl() { } void showTbl() { } #else static int a[N][2][3]; // N * a_cnt={0,1} * cl={0,1,2} static int max_n = 0; static int init = 0; static inline void initTbl() { memset(a, 0x00, sizeof(a)); a[0][0][0] = 1; a[0][0][1] = 1; a[0][0][2] = 1; a[0][1][0] = 1; a[0][1][1] = 1; a[0][1][2] = 1; } static inline int addm(int a, int b) { return (a + b) % P; } static inline int addm3(int a, int b, int c) { return ((a + b) % P + c) % P; } int checkRecord(int n) { if (init == 0) { initTbl(); init = 1; } if (n > max_n) { int i; for (i = max_n; i < n; i++) { a[i + 1][0][0] = addm3(a[i][0][0], a[i][1][0], a[i][0][1]); a[i + 1][0][1] = addm3(a[i][0][0], a[i][1][0], a[i][0][2]); a[i + 1][0][2] = addm(a[i][0][0], a[i][1][0]); a[i + 1][1][0] = addm(a[i][1][0], a[i][1][1]); a[i + 1][1][1] = addm(a[i][1][0], a[i][1][2]); a[i + 1][1][2] = a[i][1][0]; } } return a[n][0][0]; } void showTbl() { int i; for (i = 0; i != 10; i++) { printf("%d %d %d\t%d %d %d\n", a[i][0][0], a[i][0][1], a[i][0][2], a[i][1][0], a[i][1][1], a[i][1][2]); } } #endif int main() { // initTbl(); printf("%d\n", P); // int i; // for (i = 0; i != 30; i++) { // printf("%d\n", checkRecord(i, 0, 0)); // } printf("%d\n", checkRecord(29)); showTbl(); return 0; }
the_stack_data/101660.c
/* Error checking memory allocator */ #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef TESTERR #undef NULL #define NULL buf #endif /*LINTLIBRARY*/ #define V (void) #ifdef SMARTALLOC #include "smartall.h" static void nomem(const char *fname, int lineno, size_t size) { V fprintf(stderr, "\nBoom!!! Memory capacity exceeded.\n"); V fprintf(stderr, " Requested %u bytes at line %d of %s.\n", size, lineno, fname); abort(); } void *sm_xmalloc(char *fname, int lineno, size_t size) { void *buf; buf = sm_malloc(fname, lineno, size); if (buf == NULL) nomem(fname, lineno, size); return buf; } void *sm_xrealloc(char *fname, int lineno, void *ptr, size_t size) { void *buf; buf = sm_realloc(fname, lineno, ptr, size); if (buf == NULL) nomem(fname, lineno, size); return buf; } char *sm_xstrdup(char *fname, int lineno, const char *s) { char *scopy; int slen = strlen(s); scopy = sm_xmalloc(fname, lineno, slen+1); memcpy(scopy, s, slen+1); return scopy; } #else /* not SMARTALLOC */ static void nomem(size_t size) { V fprintf(stderr, "\nBoom!!! Memory capacity exceeded.\n"); V fprintf(stderr, " Requested %u bytes.\n", size); abort(); } void *xmalloc(size_t size) { void *buf; buf = malloc(size); if (buf == NULL) nomem(size); return buf; } void *xrealloc(void *ptr, size_t size) { void *buf; buf = realloc(ptr, size); if (buf == NULL) nomem(size); return buf; } char *xstrdup(const char *s) { char *scopy; int slen = strlen(s); scopy = xmalloc(slen+1); memcpy(scopy, s, slen+1); return scopy; } #endif
the_stack_data/145453383.c
#include <stdlib.h> /* Macros to emit "L Nxx R" for each octal number xx between 000 and 037. */ #define OP1(L, N, R, I, J) L N##I##J R #define OP2(L, N, R, I) \ OP1(L, N, R, 0, I), OP1(L, N, R, 1, I), \ OP1(L, N, R, 2, I), OP1(L, N, R, 3, I) #define OP(L, N, R) \ OP2(L, N, R, 0), OP2(L, N, R, 1), OP2(L, N, R, 2), OP2(L, N, R, 3), \ OP2(L, N, R, 4), OP2(L, N, R, 5), OP2(L, N, R, 6), OP2(L, N, R, 7) /* Declare 32 unique variables with prefix N. */ #define DECLARE(N) OP (, N,) /* Copy 32 variables with prefix N from the array at ADDR. Leave ADDR pointing to the end of the array. */ #define COPYIN(N, ADDR) OP (, N, = *(ADDR++)) /* Likewise, but copy the other way. */ #define COPYOUT(N, ADDR) OP (*(ADDR++) =, N,) /* Add the contents of the array at ADDR to 32 variables with prefix N. Leave ADDR pointing to the end of the array. */ #define ADD(N, ADDR) OP (, N, += *(ADDR++)) volatile double gd[32]; volatile float gf[32]; void foo (int n) { double DECLARE(d); float DECLARE(f); volatile double *pd; volatile float *pf; int i; pd = gd; COPYIN (d, pd); for (i = 0; i < n; i++) { pf = gf; COPYIN (f, pf); pd = gd; ADD (d, pd); pd = gd; ADD (d, pd); pd = gd; ADD (d, pd); pf = gf; COPYOUT (f, pf); } pd = gd; COPYOUT (d, pd); } int main () { int i; for (i = 0; i < 32; i++) gd[i] = i, gf[i] = i; foo (1); for (i = 0; i < 32; i++) if (gd[i] != i * 4 || gf[i] != i) abort (); exit (0); }
the_stack_data/154830947.c
#include <math.h> #include <stdlib.h> int *getRow(int n, int *returnSize) { int *result = malloc((n + 1) * sizeof(*result)); *returnSize = n + 1; result[0] = 1; // Use symmetry of rows. int odd = 0, mid; if ((n + 1) & 1) { odd = 1; mid = ((n + 1) / 2 + 1); } else { mid = ((n + 1) / 2); } // Fill until mid point. for (int k = 1; k < mid; k++) { int previous = result[k - 1]; // Need double cast, else precision costs. result[k] = round(previous * ((double)(n + 1 - k) / k)); } // Manually reverse and add to end of result. int end = odd ? mid - 1 : mid; for (int i = 0; i < end; i++) { result[n--] = result[i]; } return result; }
the_stack_data/1096082.c
#include <stdio.h> #define SIZE 500000 #define MOD 524287 #define swap(x, y) t=x;x=y;y=t int n, a[SIZE], i, j, t; long long c; void heapify(int i) { j = (i << 1) + 1; while (j < n) { if (j + 1 < n && a[j + 1] < a[j]) j++; if (a[i] < a[j]) break; swap(a[i], a[j]); i = j; j = (j << 1) + 1; } } void make_heap() { for (i = n / 2; i >= 0; --i) heapify(i); } int main() { scanf("%d", &n); for (i = 0; i != n; ++i) scanf("%d", a + i); make_heap(); while (n-- > 1) { swap(a[0], a[n]); heapify(0); a[0] += a[n]; c += a[0]; heapify(0); } printf("%lld", c % MOD); return 0; }
the_stack_data/1210358.c
#include <stdio.h> int main() { int a[40]={1},n,i,j; while(scanf("%d",&n)!=EOF) { if(n==-1) break; a[2]=3;a[4]=11; for(i=6;i<=32;i++) { a[i]=3*a[i-2]; for(j=i-4;j>=0;j=j-2) { a[i]+=2*a[j]; } } if(n%2==0) printf("%d\n",a[n]); else printf("0\n"); } return 0; }
the_stack_data/100140126.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } int main(int argc , char *argv[] ) { unsigned int input[1] ; unsigned int output[1] ; int randomFuns_i5 ; unsigned int randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 4242424242U) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void RandomFunc(unsigned int input[1] , unsigned int output[1] ) { unsigned int state[1] ; unsigned int local2 ; unsigned int local1 ; unsigned short copy12 ; { state[0UL] = (input[0UL] + 914778474UL) - 981234615U; local1 = 0UL; while (local1 < input[1UL]) { local2 = 0UL; while (local2 < input[1UL]) { if (state[0UL] < local2 + local1) { state[local2] = state[0UL] + state[0UL]; } else { copy12 = *((unsigned short *)(& state[local2]) + 1); *((unsigned short *)(& state[local2]) + 1) = *((unsigned short *)(& state[local2]) + 0); *((unsigned short *)(& state[local2]) + 0) = copy12; state[local2] = state[0UL] + state[0UL]; } local2 ++; } local1 ++; } output[0UL] = state[0UL] + 674032645UL; } }
the_stack_data/61993.c
// tcc -run mycat.c < mycat.c > test.txt #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { int n; char buf[BUFSIZ]; while ((n = read(0, buf, BUFSIZ)) > 0) if (write(1, buf, n) != n) fprintf(stderr, "write error"); if (n < 0) fprintf(stderr, "read error"); exit(0); }
the_stack_data/92324144.c
#define ENABLE_ETERNITY2 1 #define ENABLE_TESTBOARD_10X10 0 #define ENABLE_TESTBOARD_6X6 0 #if ENABLE_ETERNITY2 == 1 #define PIECES_FILENAME "e2pieces.txt" #define NR_OF_CARDS 256 #define NR_OF_FIELDS 256 #define NR_OF_FIELDS_X 16 #define NR_OF_FIELDS_Y 16 #define NR_OF_ROTATIONS 4 #define NR_OF_PATTERNS 23 #define MAXIMUM_OCCURRENCE2PATTERNS03 12 #define ENABLE_POSSIBILITY_FILE 1 #define LEVEL_SECOND_OPTIMIZATION 8400 #define MAX_POSSIBILITIES_PER_PATTERN 56 #define NR_OF_SAT_VARIABLES 130180 // Following is equal to (int)((NR_OF_SAT_VARIABLES + 7) / 8) #define LENGTH_OF_LINE_IN_POSSIBILITY_MATRIX 16273 #endif // ENABLE_ETERNITY2 == 1 #if ENABLE_TESTBOARD_10X10 == 1 #define PIECES_FILENAME "pieces_10x10.txt" #define NR_OF_CARDS 100 #define NR_OF_FIELDS 100 #define NR_OF_FIELDS_X 10 #define NR_OF_FIELDS_Y 10 #define NR_OF_ROTATIONS 4 #define NR_OF_PATTERNS ('O' - 'A' + 1) #define MAXIMUM_OCCURRENCE2PATTERNS03 9 #define ENABLE_GEOFF_HINTS 0 #define LEVEL_SECOND_OPTIMIZATION 15+1000 #define ENABLE_POSSIBILITY_FILE 1 #define MAX_POSSIBILITIES_PER_PATTERN 56 #define NR_OF_SAT_VARIABLES 17056 // Following is equal to (int)((NR_OF_SAT_VARIABLES + 7) / 8) #define LENGTH_OF_LINE_IN_POSSIBILITY_MATRIX 2133 #endif // ENABLE_TESTBOARD_10X10 == 1 #if ENABLE_TESTBOARD_6X6 == 1 #define PIECES_FILENAME "pieces_06x06.txt" #define NR_OF_CARDS 36 #define NR_OF_FIELDS 36 #define NR_OF_FIELDS_X 6 #define NR_OF_FIELDS_Y 6 #define NR_OF_ROTATIONS 4 #define NR_OF_PATTERNS 9 #define MAXIMUM_OCCURRENCE2PATTERNS03 6 #define ENABLE_GEOFF_HINTS 0 #define LEVEL_SECOND_OPTIMIZATION 6 + 1000 #define ENABLE_POSSIBILITY_FILE 0 #define MAX_POSSIBILITIES_PER_PATTERN 56 #define NR_OF_SAT_VARIABLES 1280 #define LENGTH_OF_LINE_IN_POSSIBILITY_MATRIX 161 #endif // ENABLE_TESTBOARD_6X6 == 1 #define PATTERN_BORDER 0
the_stack_data/832272.c
#include <stdio.h> #include <stdlib.h> /* Funçãoo : Inicializacao com inputs (vetores) - Autor : Edkallenn - Data : 06/04/2012 Observações: Usa a passagem por referencia do primeiro elemento do vetor como parametro. Demonstra como o relacionamento entre ponteiros e matrizes é estreito em C. */ #define MAX 5 //tamanho maximo do vetor void preenche_vetor(int []); //prototipo das funcoes (procedimentos) void exibe_vetor(int *); //prototipo alternativo (demonstra uso ponteiros) main(){ int x[MAX]; //vetor preenche_vetor(x); //nome de um vetor é um ponteiro para o primeiro elemento desse vetor exibe_vetor(x); getchar(); } void preenche_vetor(int *vet){ // Preenche o vetor int i; for (i=0;i<MAX;++i){ //quaisquer alteracoes aqui afetam x[MAX] (referencia) printf("\nDigite o elemento %d do vetor: ", i); scanf("%d", &vet[i]); } } void exibe_vetor(int v[]){ //Exibe int t; printf("\nO vetor digitado eh\n"); for (t=0;t<MAX;t++) printf("%-3d ", v[t]); printf("\n"); }
the_stack_data/234517179.c
#include <stdio.h> #include <stdlib.h> int *fneuronio(int *entradas, int *pesos, int *T, int n); int main(int argc, char *argv []){ int entradas[10], pesos[10], T,resultado; printf("Digite as 10 entradas:\n"); for(int i = 0; i < 10; i++) { printf("%d Entrada:\n", i+1); scanf("%d",&entradas[i]); } printf("Digite os 10 pesos:\n"); for(int y = 0; y < 10; y++) { printf("%d Peso:\n", y+1); scanf("%d",&pesos[y]); } printf("Digite o limiar T:\n"); scanf("%d", &T); fneuronio(entradas, pesos,&T, 10); resultado = fneuronio(entradas, pesos,&T, 10); if(resultado==1){ printf("Neurônio ativado!\n"); } else printf("Neurôno inibido!\n"); return 0; } int *fneuronio(int *entradas, int *pesos, int *T, int n){ int somap = 0, x; int *ativado; for(int i = 0; i < n; i++) { somap = (entradas[i]*pesos[i]) + somap; } if (somap > *T) { x = 1; ativado = x; return(ativado); } else x = 0; ativado = x; return(ativado); }
the_stack_data/95450062.c
typedef enum { injection, // 注水 drainage // 排水 }Led; void led_on(Led l){} //LEDの点灯 void led_off(Led l){}//LEDの消灯
the_stack_data/1161775.c
#include<stdio.h> struct Array { int array[10]; int size; int length; }; int linearSearch(struct Array *array, int key) { for(int i = 0; i < array->length; i++) { if(key == array->array[i]) { return i; } } return -1; } void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int linearSearchTransposition(struct Array *array, int key) { for(int i = 0; i < array->length; i++) { if(key == array->array[i]) { swap(&array->array[i], &array->array[i - 1]); return i; } } return -1; } int linearSearchMoveToFront(struct Array *array, int key) { for(int i = 0; i < array->length; i++) { if(key == array->array[i]) { swap(&array->array[i], &array->array[0]); return i; } } return -1; } int main() { struct Array arrayNormal = {{2, 23, 14, 5, 6, 9, 8, 12}, 10, 8}; int position = linearSearch(&arrayNormal, 14); if(position == -1) { printf("\nIn Normal Linear Search, Key was not Found from List\n"); } else { printf("\nIn Normal Linear Search, Key was Found at %d Position from List\n", position); } struct Array arrayTranspose = {{2, 13, 15, 5, 6, 9, 8, 12}, 10, 8}; position = linearSearchTransposition(&arrayTranspose, 5); if(position == -1) { printf("\nIn Transposition Linear Search, Key was not Found from List\n"); } else { printf("\nIn Transposition Linear Search, Key was Found at %d Position from List\n", position); } struct Array arrayMoveToFront = {{2, 23, 14, 5, 6, 9, 8, 12}, 10, 8}; position = linearSearchMoveToFront(&arrayMoveToFront, 9); if(position == -1) { printf("\nIn Move To Front Linear Search, Key was not Found from List\n"); } else { printf("\nIn Move to Front Linear Search, Key was Found at %d Position from List\n", position); } return 0; }
the_stack_data/193891995.c
#include <stdio.h> int main() { float valor[6], soma = 0, media; int i, n_positivos = 0; for (i = 0; i <= 5; i++) { scanf("%f", &valor[i]); if (valor[i] > 0) { soma += valor[i]; n_positivos++; } } media = soma / n_positivos; printf("%d valores positivos\n", n_positivos); printf("%.1f\n", media); return 0; }
the_stack_data/32950599.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* > \brief \b CPTTRF */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download CPTTRF + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/cpttrf. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/cpttrf. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/cpttrf. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE CPTTRF( N, D, E, INFO ) */ /* INTEGER INFO, N */ /* REAL D( * ) */ /* COMPLEX E( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > CPTTRF computes the L*D*L**H factorization of a complex Hermitian */ /* > positive definite tridiagonal matrix A. The factorization may also */ /* > be regarded as having the form A = U**H *D*U. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] D */ /* > \verbatim */ /* > D is REAL array, dimension (N) */ /* > On entry, the n diagonal elements of the tridiagonal matrix */ /* > A. On exit, the n diagonal elements of the diagonal matrix */ /* > D from the L*D*L**H factorization of A. */ /* > \endverbatim */ /* > */ /* > \param[in,out] E */ /* > \verbatim */ /* > E is COMPLEX array, dimension (N-1) */ /* > On entry, the (n-1) subdiagonal elements of the tridiagonal */ /* > matrix A. On exit, the (n-1) subdiagonal elements of the */ /* > unit bidiagonal factor L from the L*D*L**H factorization of A. */ /* > E can also be regarded as the superdiagonal of the unit */ /* > bidiagonal factor U from the U**H *D*U factorization of A. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -k, the k-th argument had an illegal value */ /* > > 0: if INFO = k, the leading minor of order k is not */ /* > positive definite; if k < N, the factorization could not */ /* > be completed, while if k = N, the factorization was */ /* > completed, but D(N) <= 0. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup complexPTcomputational */ /* ===================================================================== */ /* Subroutine */ int cpttrf_(integer *n, real *d__, complex *e, integer *info) { /* System generated locals */ integer i__1, i__2; complex q__1; /* Local variables */ real f, g; integer i__, i4; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); real eii, eir; /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Test the input parameters. */ /* Parameter adjustments */ --e; --d__; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; i__1 = -(*info); xerbla_("CPTTRF", &i__1, (ftnlen)6); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Compute the L*D*L**H (or U**H *D*U) factorization of A. */ i4 = (*n - 1) % 4; i__1 = i4; for (i__ = 1; i__ <= i__1; ++i__) { if (d__[i__] <= 0.f) { *info = i__; goto L20; } i__2 = i__; eir = e[i__2].r; eii = r_imag(&e[i__]); f = eir / d__[i__]; g = eii / d__[i__]; i__2 = i__; q__1.r = f, q__1.i = g; e[i__2].r = q__1.r, e[i__2].i = q__1.i; d__[i__ + 1] = d__[i__ + 1] - f * eir - g * eii; /* L10: */ } i__1 = *n - 4; for (i__ = i4 + 1; i__ <= i__1; i__ += 4) { /* Drop out of the loop if d(i) <= 0: the matrix is not positive */ /* definite. */ if (d__[i__] <= 0.f) { *info = i__; goto L20; } /* Solve for e(i) and d(i+1). */ i__2 = i__; eir = e[i__2].r; eii = r_imag(&e[i__]); f = eir / d__[i__]; g = eii / d__[i__]; i__2 = i__; q__1.r = f, q__1.i = g; e[i__2].r = q__1.r, e[i__2].i = q__1.i; d__[i__ + 1] = d__[i__ + 1] - f * eir - g * eii; if (d__[i__ + 1] <= 0.f) { *info = i__ + 1; goto L20; } /* Solve for e(i+1) and d(i+2). */ i__2 = i__ + 1; eir = e[i__2].r; eii = r_imag(&e[i__ + 1]); f = eir / d__[i__ + 1]; g = eii / d__[i__ + 1]; i__2 = i__ + 1; q__1.r = f, q__1.i = g; e[i__2].r = q__1.r, e[i__2].i = q__1.i; d__[i__ + 2] = d__[i__ + 2] - f * eir - g * eii; if (d__[i__ + 2] <= 0.f) { *info = i__ + 2; goto L20; } /* Solve for e(i+2) and d(i+3). */ i__2 = i__ + 2; eir = e[i__2].r; eii = r_imag(&e[i__ + 2]); f = eir / d__[i__ + 2]; g = eii / d__[i__ + 2]; i__2 = i__ + 2; q__1.r = f, q__1.i = g; e[i__2].r = q__1.r, e[i__2].i = q__1.i; d__[i__ + 3] = d__[i__ + 3] - f * eir - g * eii; if (d__[i__ + 3] <= 0.f) { *info = i__ + 3; goto L20; } /* Solve for e(i+3) and d(i+4). */ i__2 = i__ + 3; eir = e[i__2].r; eii = r_imag(&e[i__ + 3]); f = eir / d__[i__ + 3]; g = eii / d__[i__ + 3]; i__2 = i__ + 3; q__1.r = f, q__1.i = g; e[i__2].r = q__1.r, e[i__2].i = q__1.i; d__[i__ + 4] = d__[i__ + 4] - f * eir - g * eii; /* L110: */ } /* Check d(n) for positive definiteness. */ if (d__[*n] <= 0.f) { *info = *n; } L20: return 0; /* End of CPTTRF */ } /* cpttrf_ */
the_stack_data/771998.c
#include <stdio.h> add(); int main(void) { printf("%d", add(4, 5)); return 0; } add(a, b) { return a + b; }
the_stack_data/30653.c
/* Copyright (C) 2007-2021 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. This file was written by Chris Demetriou ([email protected]). */ /* Simple test to trigger thread events (thread start, thread exit). */ #include <pthread.h> #include <stdlib.h> #include <stdio.h> static void * threadfunc (void *arg) { printf ("in threadfunc\n"); return NULL; } static void after_join_func (void) { printf ("finished\n"); } int main (int argc, char *argv[]) { pthread_t thread; if (pthread_create (&thread, NULL, threadfunc, NULL) != 0) { printf ("pthread_create failed\n"); exit (1); } if (pthread_join (thread, NULL) != 0) { printf ("pthread_join failed\n"); exit (1); } after_join_func (); return 0; }
the_stack_data/17115.c
#include<stdio.h> #include<string.h> int main(){ // char equipe[5] = "Tera"; // char nome[6]; // strcpy(nome, "ERICK"); // printf("Nome: %s",nome); char equipe[] = "Equipe Tera"; char nome[7]; strncpy(nome, equipe, 6); nome[7] = '\0'; //finalizando a string printf("Nome: %s",nome); return 0; }
the_stack_data/3286.c
#include <stdio.h> #include <string.h> //. Elabore um programa para obter o nome de uma pessoa e a seguir forneça o sobrenome do //nome informado. Por exemplo para o nome: Omero Francisco Bertol, o programa deverá //fornecer como resultado: Seja bem-vindo(a) Sr(a). Bertol. Leve em consideração que entre //as partes do nome (Omero, Francisco e Bertol) existem um, e somente um, caractere espaço. int main() { char frase[100]; int pos, i, j; // gets(frase); int n = strlen(frase); for (i = 0; i < n; i++) { if (frase[i] == 32) { // procura pelo espaço(ASCII) pos = i; //salva o ultimo espaço } } printf("Seja bem-vindo(a) Sr(a) "); for (j = pos + 1; j < n; j++) { //começa a imprimir a partir do ultimo espaço printf("%c", frase[j]); } return 0; }
the_stack_data/153630.c
/* * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #if defined(DEBUG) #include "debug_util.h" #define DMEM_MIN(a,b) (a) < (b) ? (a) : (b) #define DMEM_MAX(a,b) (a) > (b) ? (a) : (b) typedef char byte_t; static const byte_t ByteInited = '\xCD'; static const byte_t ByteFreed = '\xDD'; static const byte_t ByteGuard = '\xFD'; enum { MAX_LINENUM = 50000, /* I certainly hope we don't have source files bigger than this */ MAX_CHECK_BYTES = 27, /* max bytes to check at start of block */ MAX_GUARD_BYTES = 8, /* size of guard areas on either side of a block */ MAX_DECIMAL_DIGITS = 15 }; /* Debug Info Header to precede allocated block */ typedef struct MemoryBlockHeader { char filename[FILENAME_MAX+1]; /* filename where alloc occurred */ int linenumber; /* line where alloc occurred */ size_t size; /* size of the allocation */ int order; /* the order the block was allocated in */ struct MemoryListLink * listEnter; /* pointer to the free list node */ byte_t guard[MAX_GUARD_BYTES]; /* guard area for underrun check */ } MemoryBlockHeader; /* Tail to follow allocated block */ typedef struct MemoryBlockTail { byte_t guard[MAX_GUARD_BYTES]; /* guard area overrun check */ } MemoryBlockTail; /* Linked list of allocated memory blocks */ typedef struct MemoryListLink { struct MemoryListLink * next; MemoryBlockHeader * header; int freed; } MemoryListLink; /************************************************** * Global Data structures */ static DMemState DMemGlobalState; extern const DMemState * DMemStatePtr = &DMemGlobalState; static MemoryListLink MemoryList = {NULL,NULL,FALSE}; static dmutex_t DMemMutex = NULL; /**************************************************/ /************************************************* * Client callback invocation functions */ static void * DMem_ClientAllocate(size_t size) { if (DMemGlobalState.pfnAlloc != NULL) { return (*DMemGlobalState.pfnAlloc)(size); } return malloc(size); } static void DMem_ClientFree(void * ptr) { if (DMemGlobalState.pfnFree != NULL) { (*DMemGlobalState.pfnFree)(ptr); } free(ptr); } static dbool_t DMem_ClientCheckPtr(void * ptr, size_t size) { if (DMemGlobalState.pfnCheckPtr != NULL) { return (*DMemGlobalState.pfnCheckPtr)(ptr, size); } return ptr != NULL; } /**************************************************/ /************************************************* * Debug Memory Manager implementation */ static MemoryListLink * DMem_TrackBlock(MemoryBlockHeader * header) { MemoryListLink * link; link = (MemoryListLink *)DMem_ClientAllocate(sizeof(MemoryListLink)); if (link != NULL) { link->header = header; link->header->listEnter = link; link->next = MemoryList.next; link->freed = FALSE; MemoryList.next = link; } return link; } static int DMem_VerifyGuardArea(const byte_t * area) { int nbyte; for ( nbyte = 0; nbyte < MAX_GUARD_BYTES; nbyte++ ) { if (area[nbyte] != ByteGuard) { return FALSE; } } return TRUE; } static void DMem_VerifyHeader(MemoryBlockHeader * header) { DASSERTMSG( DMem_ClientCheckPtr(header, sizeof(MemoryBlockHeader)), "Invalid header" ); DASSERTMSG( DMem_VerifyGuardArea(header->guard), "Header corruption, possible underwrite" ); DASSERTMSG( header->linenumber > 0 && header->linenumber < MAX_LINENUM, "Header corruption, bad line number" ); DASSERTMSG( header->size <= DMemGlobalState.biggestBlock, "Header corruption, block size is too large"); DASSERTMSG( header->order <= DMemGlobalState.totalAllocs, "Header corruption, block order out of range"); } static void DMem_VerifyTail(MemoryBlockTail * tail) { DASSERTMSG( DMem_ClientCheckPtr(tail, sizeof(MemoryBlockTail)), "Tail corruption, invalid pointer"); DASSERTMSG( DMem_VerifyGuardArea(tail->guard), "Tail corruption, possible overwrite" ); } static MemoryBlockHeader * DMem_VerifyBlock(void * memptr) { MemoryBlockHeader * header; MemoryBlockTail * tail; /* check if the pointer is valid */ DASSERTMSG( DMem_ClientCheckPtr(memptr, 1), "Invalid pointer"); /* check if the block header is valid */ header = (MemoryBlockHeader *)((byte_t *)memptr - sizeof(MemoryBlockHeader)); DMem_VerifyHeader(header); /* check that the memory itself is valid */ DASSERTMSG( DMem_ClientCheckPtr(memptr, DMEM_MIN(MAX_CHECK_BYTES,header->size)), "Block memory invalid" ); /* check that the pointer to the alloc list is valid */ DASSERTMSG( DMem_ClientCheckPtr(header->listEnter, sizeof(MemoryListLink)), "Header corruption, alloc list pointer invalid" ); /* check the tail of the block for overruns */ tail = (MemoryBlockTail *) ( (byte_t *)memptr + header->size ); DMem_VerifyTail(tail); return header; } static MemoryBlockHeader * DMem_GetHeader(void * memptr) { MemoryBlockHeader * header = DMem_VerifyBlock(memptr); return header; } /* * Should be called before any other DMem_XXX function */ void DMem_Initialize() { DMemMutex = DMutex_Create(); DMutex_Enter(DMemMutex); DMemGlobalState.pfnAlloc = NULL; DMemGlobalState.pfnFree = NULL; DMemGlobalState.pfnCheckPtr = NULL; DMemGlobalState.biggestBlock = 0; DMemGlobalState.maxHeap = INT_MAX; DMemGlobalState.totalHeapUsed = 0; DMemGlobalState.failNextAlloc = FALSE; DMemGlobalState.totalAllocs = 0; DMutex_Exit(DMemMutex); } void DMem_Shutdown() { DMutex_Destroy(DMemMutex); } /* * Allocates a block of memory, reserving extra space at the start and end of the * block to store debug info on where the block was allocated, it's size, and * 'guard' areas to catch overwrite/underwrite bugs */ void * DMem_AllocateBlock(size_t size, const char * filename, int linenumber) { MemoryBlockHeader * header; MemoryBlockTail * tail; size_t debugBlockSize; byte_t * memptr = NULL; DMutex_Enter(DMemMutex); if (DMemGlobalState.failNextAlloc) { /* force an allocation failure if so ordered */ DMemGlobalState.failNextAlloc = FALSE; /* reset flag */ goto Exit; } /* allocate a block large enough to hold extra debug info */ debugBlockSize = sizeof(MemoryBlockHeader) + size + sizeof(MemoryBlockTail); header = (MemoryBlockHeader *)DMem_ClientAllocate(debugBlockSize); if (header == NULL) { goto Exit; } /* add block to list of allocated memory */ header->listEnter = DMem_TrackBlock(header); if ( header->listEnter == NULL ) { goto Exit; } /* store size of requested block */ header->size = size; /* update maximum block size */ DMemGlobalState.biggestBlock = DMEM_MAX(header->size, DMemGlobalState.biggestBlock); /* update used memory total */ DMemGlobalState.totalHeapUsed += header->size; /* store filename and linenumber where allocation routine was called */ strncpy(header->filename, filename, FILENAME_MAX); header->linenumber = linenumber; /* store the order the block was allocated in */ header->order = DMemGlobalState.totalAllocs++; /* initialize memory to a recognizable 'inited' value */ memptr = (byte_t *)header + sizeof(MemoryBlockHeader); memset(memptr, ByteInited, size); /* put guard area before block */ memset(header->guard, ByteGuard, MAX_GUARD_BYTES); /* put guard area after block */ tail = (MemoryBlockTail *)(memptr + size); memset(tail->guard, ByteGuard, MAX_GUARD_BYTES); Exit: DMutex_Exit(DMemMutex); return memptr; } /* * Frees block of memory allocated with DMem_AllocateBlock */ void DMem_FreeBlock(void * memptr) { MemoryBlockHeader * header; DMutex_Enter(DMemMutex); if ( memptr == NULL) { goto Exit; } /* get the debug block header preceding the allocated memory */ header = DMem_GetHeader(memptr); /* fill memory with recognizable 'freed' value */ memset(memptr, ByteFreed, header->size); /* mark block as freed */ header->listEnter->freed = TRUE; /* update used memory total */ DMemGlobalState.totalHeapUsed -= header->size; Exit: DMutex_Exit(DMemMutex); } static void DMem_DumpHeader(MemoryBlockHeader * header) { char report[FILENAME_MAX+MAX_DECIMAL_DIGITS*3+1]; static const char * reportFormat = "file: %s, line %d\n" "size: %d bytes\n" "order: %d\n" "-------"; DMem_VerifyHeader(header); sprintf(report, reportFormat, header->filename, header->linenumber, header->size, header->order); DTRACE_PRINTLN(report); } /* * Call this function at shutdown time to report any leaked blocks */ void DMem_ReportLeaks() { MemoryListLink * link; DMutex_Enter(DMemMutex); /* Force memory leaks to be output regardless of trace settings */ DTrace_EnableFile(__FILE__, TRUE); DTRACE_PRINTLN("--------------------------"); DTRACE_PRINTLN("Debug Memory Manager Leaks"); DTRACE_PRINTLN("--------------------------"); /* walk through allocated list and dump any blocks not marked as freed */ link = MemoryList.next; while (link != NULL) { if ( !link->freed ) { DMem_DumpHeader(link->header); } link = link->next; } DMutex_Exit(DMemMutex); } void DMem_SetAllocCallback( DMEM_ALLOCFN pfn ) { DMutex_Enter(DMemMutex); DMemGlobalState.pfnAlloc = pfn; DMutex_Exit(DMemMutex); } void DMem_SetFreeCallback( DMEM_FREEFN pfn ) { DMutex_Enter(DMemMutex); DMemGlobalState.pfnFree = pfn; DMutex_Exit(DMemMutex); } void DMem_SetCheckPtrCallback( DMEM_CHECKPTRFN pfn ) { DMutex_Enter(DMemMutex); DMemGlobalState.pfnCheckPtr = pfn; DMutex_Exit(DMemMutex); } void DMem_DisableMutex() { DMemMutex = NULL; } #endif /* defined(DEBUG) */ /* The following line is only here to prevent compiler warnings * on release (non-debug) builds */ static int dummyVariable = 0;
the_stack_data/12638739.c
#include<stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include<stdlib.h> #include <unistd.h> int main(){ int fd,res; fd=socket(AF_INET, SOCK_DGRAM, 0); if(fd==-1) printf("Socket not created error\n"); else printf("Socket created successfully\n"); struct sockaddr_in x; x.sin_family=AF_INET; x.sin_port=ntohs(6000); x.sin_addr.s_addr=INADDR_ANY; res=bind(fd,(struct sockaddr *) &x,sizeof x); if(res==-1) printf("Bind not created error\n"); else printf("Bind created successfully\n"); struct sockaddr_in y; y.sin_family=AF_INET; y.sin_port=ntohs(6005); y.sin_addr.s_addr=INADDR_ANY; if(sendto(fd,"Hello from Client",30,0,(struct sockaddr *)&y, sizeof y) == -1) { perror("sendto"); exit(1); } printf("Send Successfully"); close(fd); return 0; }
the_stack_data/174176.c
/* * Copyright © 2011-2018 Inria. All rights reserved. * Copyright © 2011 Université Bordeaux. All rights reserved. * See COPYING in top-level directory. */ #include "hwloc.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include <assert.h> static hwloc_topology_t topology; static void print_distances(const struct hwloc_distances_s *distances) { unsigned nbobjs = distances->nbobjs; unsigned i, j; printf(" "); /* column header */ for(j=0; j<nbobjs; j++) printf(" % 5d", (int) distances->objs[j]->os_index); printf("\n"); /* each line */ for(i=0; i<nbobjs; i++) { /* row header */ printf("% 5d", (int) distances->objs[i]->os_index); /* each value */ for(j=0; j<nbobjs; j++) printf(" % 5d", (int) distances->values[i*nbobjs+j]); printf("\n"); } } static void check(unsigned nbgroups, unsigned nbnodes, unsigned nbcores, unsigned nbpus) { int depth; unsigned nb; unsigned long long total_memory; /* sanity checks */ depth = hwloc_topology_get_depth(topology); assert(depth == 3 + (nbgroups > 0)); depth = hwloc_get_type_depth(topology, HWLOC_OBJ_NUMANODE); assert(depth == HWLOC_TYPE_DEPTH_NUMANODE); depth = hwloc_get_type_depth(topology, HWLOC_OBJ_GROUP); assert(depth == ((nbgroups > 0) ? 1 : HWLOC_TYPE_DEPTH_UNKNOWN)); depth = hwloc_get_type_depth(topology, HWLOC_OBJ_CORE); assert(depth == 1 + (nbgroups > 0)); depth = hwloc_get_type_depth(topology, HWLOC_OBJ_PU); assert(depth == 2 + (nbgroups > 0)); /* actual checks */ nb = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_NUMANODE); assert(nb == nbnodes); nb = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_GROUP); assert(nb == nbgroups); nb = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_CORE); assert(nb == nbcores); nb = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_PU); assert(nb == nbpus); total_memory = hwloc_get_root_obj(topology)->total_memory; assert(total_memory == nbnodes * 1024*1024*1024); /* synthetic topology puts 1GB per node */ } static void check_distances(unsigned nbnodes, unsigned nbcores) { struct hwloc_distances_s *distance; unsigned nr; int err; /* node distance */ nr = 1; err = hwloc_distances_get_by_type(topology, HWLOC_OBJ_NUMANODE, &nr, &distance, 0, 0); assert(!err); if (nbnodes >= 2) { assert(nr == 1); assert(distance); assert(distance->nbobjs == nbnodes); print_distances(distance); hwloc_distances_release(topology, distance); } else { assert(nr == 0); } /* core distance */ nr = 1; err = hwloc_distances_get_by_type(topology, HWLOC_OBJ_CORE, &nr, &distance, 0, 0); assert(!err); if (nbcores >= 2) { assert(nr == 1); assert(distance); assert(distance->nbobjs == nbcores); print_distances(distance); hwloc_distances_release(topology, distance); } else { assert(nr == 0); } } int main(void) { hwloc_bitmap_t cpuset = hwloc_bitmap_alloc(); hwloc_obj_t nodes[3], cores[6]; hwloc_uint64_t node_distances[9], core_distances[36]; hwloc_obj_t obj; unsigned i,j; int err; hwloc_topology_init(&topology); hwloc_topology_set_synthetic(topology, "node:3 core:2 pu:4"); hwloc_topology_load(topology); for(i=0; i<3; i++) { nodes[i] = hwloc_get_obj_by_type(topology, HWLOC_OBJ_NUMANODE, i); for(j=0; j<3; j++) node_distances[i*3+j] = (i == j ? 10 : 20); } err = hwloc_distances_add(topology, 3, nodes, node_distances, HWLOC_DISTANCES_KIND_MEANS_LATENCY|HWLOC_DISTANCES_KIND_FROM_USER, HWLOC_DISTANCES_ADD_FLAG_GROUP); assert(!err); for(i=0; i<6; i++) { cores[i] = hwloc_get_obj_by_type(topology, HWLOC_OBJ_CORE, i); for(j=0; j<6; j++) core_distances[i*6+j] = (i == j ? 4 : 8); } err = hwloc_distances_add(topology, 6, cores, core_distances, HWLOC_DISTANCES_KIND_MEANS_LATENCY|HWLOC_DISTANCES_KIND_FROM_USER, HWLOC_DISTANCES_ADD_FLAG_GROUP); assert(!err); /* entire topology */ printf("starting from full topology\n"); check(3, 3, 6, 24); check_distances(3, 6); /* restrict to nothing, impossible */ printf("restricting to nothing, must fail\n"); hwloc_bitmap_zero(cpuset); err = hwloc_topology_restrict(topology, cpuset, 0); assert(err < 0 && errno == EINVAL); printf("restricting to unexisting PU:24, must fail\n"); hwloc_bitmap_only(cpuset, 24); err = hwloc_topology_restrict(topology, cpuset, 0); assert(err < 0 && errno == EINVAL); check(3, 3, 6, 24); check_distances(3, 6); /* restrict to everything, will do nothing */ printf("restricting to everything, does nothing\n"); hwloc_bitmap_fill(cpuset); err = hwloc_topology_restrict(topology, cpuset, 0); assert(!err); check(3, 3, 6, 24); check_distances(3, 6); /* remove a single pu (second PU of second core of second node) */ printf("removing second PU of second core of second node\n"); hwloc_bitmap_fill(cpuset); hwloc_bitmap_clr(cpuset, 13); err = hwloc_topology_restrict(topology, cpuset, 0); assert(!err); check(3, 3, 6, 23); check_distances(3, 6); /* remove the entire second core of first node */ printf("removing entire second core of first node\n"); hwloc_bitmap_fill(cpuset); hwloc_bitmap_clr_range(cpuset, 4, 7); err = hwloc_topology_restrict(topology, cpuset, 0); assert(!err); check(3, 3, 5, 19); check_distances(3, 5); /* remove the entire third node */ printf("removing all PUs under third node, but keep that CPU-less node\n"); hwloc_bitmap_fill(cpuset); hwloc_bitmap_clr_range(cpuset, 16, 23); err = hwloc_topology_restrict(topology, cpuset, 0); assert(!err); check(3, 3, 3, 11); check_distances(3, 3); /* only keep three PUs (first and last of first core, and last of last core of second node) */ printf("restricting to 3 PUs in 2 cores in 2 nodes, and remove the CPU-less node, and auto-merge groups\n"); hwloc_bitmap_zero(cpuset); hwloc_bitmap_set(cpuset, 0); hwloc_bitmap_set(cpuset, 3); hwloc_bitmap_set(cpuset, 15); err = hwloc_topology_restrict(topology, cpuset, HWLOC_RESTRICT_FLAG_REMOVE_CPULESS); assert(!err); check(0, 2, 2, 3); check_distances(2, 2); /* restrict to the third node, impossible */ printf("restricting to only some already removed node, must fail\n"); hwloc_bitmap_zero(cpuset); hwloc_bitmap_set_range(cpuset, 16, 23); err = hwloc_topology_restrict(topology, cpuset, 0); assert(err == -1 && errno == EINVAL); check(0, 2, 2, 3); check_distances(2, 2); hwloc_topology_destroy(topology); /* check that restricting exactly on a Group object keeps things coherent */ printf("restricting to a Group covering only the of the PU level\n"); hwloc_topology_init(&topology); hwloc_topology_set_synthetic(topology, "pu:4"); hwloc_topology_load(topology); hwloc_bitmap_zero(cpuset); hwloc_bitmap_set_range(cpuset, 1, 2); obj = hwloc_topology_alloc_group_object(topology); obj->cpuset = hwloc_bitmap_dup(cpuset); obj->name = strdup("toto"); hwloc_topology_insert_group_object(topology, obj); hwloc_topology_restrict(topology, cpuset, 0); hwloc_topology_check(topology); hwloc_topology_destroy(topology); /* check memory-based restricting */ hwloc_topology_init(&topology); hwloc_topology_set_synthetic(topology, "node:3 core:2 pu:4"); hwloc_topology_load(topology); printf("restricting bynodeset to two numa nodes\n"); hwloc_bitmap_zero(cpuset); hwloc_bitmap_set_range(cpuset, 1, 2); err = hwloc_topology_restrict(topology, cpuset, HWLOC_RESTRICT_FLAG_BYNODESET); assert(!err); hwloc_topology_check(topology); check(3, 2, 6, 24); printf("further restricting bynodeset to a single numa node\n"); hwloc_bitmap_only(cpuset, 1); err = hwloc_topology_restrict(topology, cpuset, HWLOC_RESTRICT_FLAG_BYNODESET|HWLOC_RESTRICT_FLAG_REMOVE_MEMLESS); assert(!err); hwloc_topology_check(topology); check(0, 1, 2, 8); printf("restricting with invalid flags\n"); err = hwloc_topology_restrict(topology, cpuset, HWLOC_RESTRICT_FLAG_REMOVE_MEMLESS); assert(err == -1); assert(errno == EINVAL); err = hwloc_topology_restrict(topology, cpuset, HWLOC_RESTRICT_FLAG_BYNODESET|HWLOC_RESTRICT_FLAG_REMOVE_CPULESS); assert(err == -1); assert(errno == EINVAL); hwloc_topology_destroy(topology); /* check that restricting PUs maintains ordering of normal children */ printf("restricting so that PUs get reordered\n"); hwloc_topology_init(&topology); hwloc_topology_set_synthetic(topology, "node:1 core:2 pu:2(indexes=0,2,1,3)"); hwloc_topology_load(topology); hwloc_bitmap_zero(cpuset); hwloc_bitmap_set_range(cpuset, 1, 2); err = hwloc_topology_restrict(topology, cpuset, 0); assert(!err); hwloc_topology_destroy(topology); /* check that restricting NUMA nodes maintains ordering of normal children in remove-memless case */ printf("restricting by nodeset so that remaining non-memless PUs get reordered\n"); hwloc_topology_init(&topology); hwloc_topology_set_synthetic(topology, "pack:2 l3:2 numa:1 pu:1(indexes=0,2,1,3)"); hwloc_topology_load(topology); hwloc_bitmap_zero(cpuset); hwloc_bitmap_set_range(cpuset, 1, 2); err = hwloc_topology_restrict(topology, cpuset, HWLOC_RESTRICT_FLAG_BYNODESET|HWLOC_RESTRICT_FLAG_REMOVE_MEMLESS); assert(!err); hwloc_topology_destroy(topology); hwloc_bitmap_free(cpuset); return 0; }
the_stack_data/193892605.c
// PARAM: --enable ana.int.interval --disable ana.int.def_exc --disable ana.int.enums void main(){ int n = 7; for (; n; n--) { assert(n==1); // UNKNOWN! } int i; if(i-1){ assert(i==2); // UNKNOWN } return; }
the_stack_data/54825551.c
#include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> int **array; int **array1; int *community; float **v_comm; double func( float a,float b); double funcb( int comm , int node); int vertices,m; int main(int argc , char ** argv) { char filename[50]="", filename1[50]=""; int i,t,deg,node,comm=1,num,k,k1,j,tt,flag=0,a,b; strcat(filename,argv[1]); // adjlist.txt strcat(filename1,argv[2]); // final cover float j1; double part11=0.0,part22=0.0; double alpha1=0.0,alpha2=0.0,beta=0.0,part1=0.0,part2=0.0,final=0.0,final1=0.0,part21=0.0; FILE *fp; //fp=fopen("Adjlist.txt","r"); fp=fopen(filename,"r"); if(fp==NULL) { printf("%s\n",filename); printf("does not exist"); exit(0); } fscanf(fp,"%d %d ",&vertices,&m); array=(int**)calloc(vertices+1,sizeof(int*)); while(fscanf(fp,"%d ",&node)!=EOF) { fscanf(fp,"%d ",&deg); array[node]=(int*)calloc(deg+1,sizeof(int)); array[node][0]=deg; //flag=0; for(i=1;i<=deg;i++) { fscanf(fp,"%d ",&t); array[node][i]=t; } } int countl=0,test=0; fclose(fp); int *counter=(int *)calloc(vertices+1,sizeof(int)); //fp=fopen("epi_cover.txt","r"); fp=fopen(filename1,"r"); fscanf(fp,"%d ",&num); v_comm=(float**)calloc(vertices+1,sizeof(float*)); for(i=0;i<=vertices;i++) v_comm[i]=(float*)calloc(num+1,sizeof(float)); community=(int*)calloc(num+1,sizeof(int)); while(fscanf(fp,"%d",&i)!=EOF) { if(i!=-1) { v_comm[i][comm]=1.0; community[comm]++; counter[i]++; countl++; } else{ //printf("%d\n",countl); if(countl<=3) test++; countl=0; comm++;} } fclose(fp); //printf("Test %d\n",test); for(i=1;i<=vertices;i++) { for(j=1;j<=num;j++) { if(i==1) v_comm[j][0]=community[j]; if(v_comm[i][j]==1.0) v_comm[i][j]=(float)1/(counter[i]); } } free(counter); free(community); int *comm1; double *mark=(double*)calloc(vertices+1,sizeof(double)); double partt=0.0,mark1=1.0,mark2=0.0; double tot_beta=1.0,tot=0.0,tot1=0.0; int kij=0; float alpha_val,alpha2_val;int jk=0; int index;int temp=0;double betav=0.0;int alpa=0; for(k=1;k<=num;k++) { temp=0; //printf("Community %d\n",k); part1=0.0,part2=0.0; for(j=0;j<=vertices;j++) { mark[j]=-1; } jk=0; comm1=(int*)calloc((int)v_comm[k][0],sizeof(int)); for(j=1;j<=vertices;j++) { if(v_comm[j][k]!=0){ comm1[jk]=j;jk++;} alpha2_val=v_comm[j][k]; if(mark[j]==-1.0) { if(alpha2_val!=0) mark[j]=funcb(k,j); else mark[j]=0; for(index=1;index<=vertices;index++) { if(v_comm[index][k]==alpha2_val) mark[index]=mark[j]; } } } for(i=1;i<=vertices;i++) { for(j=1;j<=array[i][0];j++) { if(i<array[i][j]) { part1+=(func(v_comm[i][k],v_comm[array[i][j]][k])); } } } for(i=0;i<(int)(v_comm[k][0]);i++) { for(j=0;j<(int)(v_comm[k][0]);j++) { part2+=((double)array[comm1[i]][0]*(double)array[comm1[j]][0]*mark[comm1[i]]*mark[comm1[j]]); } } free(comm1); part2=part2/4; part2=part2/(double)m; final+=((part1/(double)(m))-(part2/(double)m)); //printf("comm --------> %d %lf\n",k,(part1/(double)(m))-(part2/(double)m)); //printf("Community %d / %d : %lf\n",k,num,final); } free(mark); printf("Modularity is: %lf\n",final); printf("Number of vertices: %d\n",vertices); for(i=0;i<=vertices;i++) free(array[i]); free(array); for(i=0;i<=vertices;i++) free(v_comm[i]); free(v_comm); } double func( float a, float b) { double f1=(60*a)-30; double f2=(60*b)-30; f1=exp(-(f1)); f2=exp(-(f2)); f1+=1; f2+=1; double l=(double)1/(f1*f2); return(l); } /* double funcb( int comm , int node) { int j; double beta=0.0; float alpha2,alpha1; alpha1=v_comm[node][comm]; for(j=1;j<=array[node][0];j++) { alpha2=v_comm[array[node][j]][comm]; beta+=func(alpha1,alpha2); } beta=beta/(double)vertices; return beta; }*/ double funcb( int comm , int node) { int j; double beta=0.0; float alpha2,alpha1; alpha1=v_comm[node][comm]; for(j=1;j<=vertices;j++) { alpha2=v_comm[j][comm]; beta+=func(alpha1,alpha2); } beta=beta/(double)(vertices); return beta; }
the_stack_data/70450526.c
/* text version of maze 'mazefiles/binary/euro-v58.maz' generated by mazetool (c) Peter Harrison 2018 o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o | | | o o---o---o---o---o---o---o---o o---o---o o o---o---o o | | | | | | | o---o---o o o---o---o---o---o---o o o o o o---o---o | | | | | | | | | | o o---o---o---o---o o o---o o o o o o o o o | | | | | | | | | | | | o o---o o o o---o---o o o o o o o o o o | | | | | | | | | | | | | o o o---o o---o---o o o o o---o---o o o o o | | | | | | | | | | o o o o---o---o o---o---o o---o---o---o---o o o o | | | | | | | o o---o---o o---o---o o---o---o---o o---o---o o o o | | | | | | | | | | | o o o o o o o o o o o---o o o o o o | | | | | | | | | | | | o o o---o---o o---o---o---o---o---o---o---o o o o o | | | | | | | | | | o o---o---o o---o o o---o o o o---o---o o o o | | | | | | | | o o---o o---o---o o---o---o---o o o o o---o---o o | | | | | | | | o o o o o---o---o---o---o---o---o---o---o---o---o o o | | | | | | o o o---o---o---o---o---o---o---o o o---o---o---o o o | | | | | | | | | o o o o---o o o---o---o o o o o---o---o o o | | | | | | | | | o o o---o---o---o---o---o o---o---o---o o o---o---o o | | | o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o */ int euro_v58_maz[] ={ 0x0E, 0x0A, 0x0A, 0x0A, 0x08, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x08, 0x09, 0x0C, 0x09, 0x0C, 0x0A, 0x08, 0x0A, 0x03, 0x05, 0x0C, 0x0A, 0x09, 0x0C, 0x0A, 0x09, 0x05, 0x05, 0x05, 0x05, 0x05, 0x0C, 0x01, 0x0C, 0x0A, 0x03, 0x05, 0x0C, 0x03, 0x06, 0x09, 0x06, 0x03, 0x06, 0x03, 0x05, 0x05, 0x05, 0x05, 0x04, 0x09, 0x0C, 0x03, 0x06, 0x0A, 0x09, 0x04, 0x0A, 0x09, 0x0C, 0x09, 0x05, 0x05, 0x06, 0x03, 0x05, 0x07, 0x05, 0x0C, 0x0A, 0x09, 0x05, 0x05, 0x0C, 0x01, 0x05, 0x05, 0x05, 0x05, 0x0C, 0x09, 0x05, 0x0C, 0x02, 0x03, 0x0C, 0x03, 0x06, 0x03, 0x05, 0x06, 0x03, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x0C, 0x09, 0x06, 0x08, 0x09, 0x0C, 0x03, 0x0C, 0x09, 0x05, 0x05, 0x04, 0x01, 0x05, 0x05, 0x05, 0x05, 0x05, 0x0C, 0x01, 0x05, 0x06, 0x0A, 0x03, 0x05, 0x05, 0x05, 0x05, 0x06, 0x03, 0x05, 0x05, 0x06, 0x03, 0x06, 0x03, 0x04, 0x0A, 0x0A, 0x0A, 0x03, 0x06, 0x01, 0x05, 0x0C, 0x0A, 0x03, 0x06, 0x08, 0x0B, 0x0C, 0x09, 0x05, 0x0C, 0x0A, 0x0A, 0x0A, 0x09, 0x05, 0x05, 0x06, 0x0A, 0x09, 0x0C, 0x02, 0x09, 0x05, 0x06, 0x01, 0x05, 0x0C, 0x0A, 0x0A, 0x03, 0x05, 0x04, 0x0A, 0x09, 0x05, 0x06, 0x09, 0x05, 0x06, 0x09, 0x05, 0x05, 0x06, 0x0A, 0x0A, 0x0A, 0x03, 0x04, 0x09, 0x05, 0x05, 0x0C, 0x03, 0x06, 0x0A, 0x03, 0x05, 0x06, 0x0A, 0x0A, 0x0A, 0x0A, 0x09, 0x05, 0x05, 0x07, 0x05, 0x05, 0x0C, 0x0A, 0x0A, 0x0A, 0x02, 0x0A, 0x0A, 0x0A, 0x0A, 0x09, 0x05, 0x05, 0x06, 0x0A, 0x02, 0x03, 0x06, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x09, 0x05, 0x05, 0x06, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x03, 0x06, 0x03, }; /* end of mazefile */
the_stack_data/57950021.c
#include <stdlib.h> #include <string.h> #define nil ((void*)0) typedef unsigned long ulong; void* mallocz(ulong size, int clr) { void *v; v = malloc(size); if(clr && v != nil) memset(v, 0, size); return v; }
the_stack_data/773580.c
#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #ifdef __COVERITY__ #define _Float128 long double #define _Float64x long double #define _Float64 double #define _Float32x double #define _Float32 float #endif /* ** 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 <inttypes.h> #include <unistd.h> /* access() */ #define UNUSED(x) ( (void)(x) ) #ifndef __WIN32__ # if defined(_WIN32) || defined(WIN32) # define __WIN32__ # endif #endif #if __GNUC__ > 2 #define NORETURN __attribute__ ((__noreturn__)) #else #define NORETURN #endif /* #define PRIVATE static */ #define PRIVATE static #ifdef TEST #define MAXRHS 5 /* Set low to exercise exception code */ #else #define MAXRHS 1000 #endif void *msort(void *list, void **next, int(*cmp)(void *, void *)); static void memory_error() NORETURN; /******** From the file "action.h" *************************************/ struct action *Action_new(); struct action *Action_sort(); void Action_add(); /********* From the file "assert.h" ************************************/ void myassert() NORETURN; #ifndef NDEBUG # define assert(X) if(!(X))myassert(__FILE__,__LINE__) #else # define assert(X) #endif /********** From the file "build.h" ************************************/ void FindRulePrecedences(); void FindFirstSets(); void FindStates(); void FindLinks(); void FindFollowSets(); void FindActions(); /********* 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(/* void */); 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" ******************************************/ struct s_options { enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR, OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type; char *label; void *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 * */); void ReportHeader(/* struct lemon * */); void CompressTables(/* struct lemon * */); /********** From the file "set.h" ****************************************/ void SetSize(/* int N */); /* 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 *A,char *B */); /* A <- A U B, through 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 {Bo_FALSE=0, Bo_TRUE} Boolean; /* Symbols (terminals and nonterminals) of the grammar are stored ** in the following: */ struct symbol { char *name; /* Name of the symbol */ int index; /* Index number for this symbol */ enum { TERMINAL, NONTERMINAL } 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 { LEFT, RIGHT, NONE, UNK } assoc; /* Associativity if predecence is defined */ char *firstset; /* First-set for all rules of this symbol */ Boolean lambda; /* True if NT and can generate an empty string */ char *destructor; /* Code which executes whenever this symbol is ** popped from the stack during error processing */ int destructorln; /* Line number of destructor code */ 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 */ }; /* Each production rule in the grammar is stored in the following ** structure. */ struct rule { struct symbol *lhs; /* Left-hand side of the rule */ char *lhsalias; /* Alias for the LHS (NULL if none) */ int ruleline; /* Line number for the rule */ int nrhs; /* Number of RHS symbols */ struct symbol **rhs; /* The RHS symbols */ char **rhsalias; /* An alias for each RHS symbol (NULL if none) */ int line; /* Line number at which code begins */ char *code; /* The code executed when this rule is reduced */ struct symbol *precsym; /* Precedence symbol for this rule */ int index; /* An index number for this rule */ Boolean canReduce; /* True if this rule is ever reduced */ 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: */ 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 { COMPLETE, /* The status is used during followset and */ INCOMPLETE /* shift computations */ } status; struct config *next; /* Next configuration in the state */ struct config *bp; /* The next basis configuration */ }; /* Every shift or reduce operation is stored as one of the following */ struct action { struct symbol *sp; /* The look-ahead symbol */ enum e_action { SHIFT, ACCEPT, REDUCE, ERROR, CONFLICT, /* 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 */ } type; union { struct state *stp; /* The new state, if a shift */ struct rule *rp; /* The rule, if a reduce */ } x; 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 index; /* Sequential number for this state */ struct action *ap; /* Array 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 iDflt; /* Default action */ }; #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 */ int nstate; /* Number of states */ int nrule; /* Number of rules */ int nsymbol; /* Number of terminal and nonterminal symbols */ int nterminal; /* Number of terminal symbols */ struct symbol **symbols; /* Sorted array of pointers to symbols */ int errorcnt; /* Number of errors */ struct symbol *errsym; /* The error symbol */ char *name; /* Name of the generated parser */ char *arg; /* Declaration of the 3th argument to parser */ 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 */ int includeln; /* Line number for start of include code */ char *error; /* Code to execute when an error is seen */ int errorln; /* Line number for start of error code */ char *overflow; /* Code to execute on a stack overflow */ int overflowln; /* Line number for start of overflow code */ char *failure; /* Code to execute on parser failure */ int failureln; /* Line number for start of failure code */ char *accept; /* Code to execute when the parser excepts */ int acceptln; /* Line number for the start of accept code */ char *extracode; /* Code appended to the generated file */ int extracodeln; /* Line number for the start of the extra code */ char *tokendest; /* Code to execute to destroy token data */ int tokendestln; /* Line number for token destroyer code */ char *vardest; /* Code for the default non-terminal destructor */ int vardestln; /* Line number for default non-term destructor code*/ char *filename; /* Name of the input file */ char *tmplname; /* Name of the template 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 tablesize; /* Size of the parse tables */ int basisflag; /* Print only basis configurations */ int has_fallback; /* True if any %fallback is seen in the grammar */ char *argv0; /* Name of the program */ }; #define MemoryCheck(X) if((X)==0){ \ 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 */ char *Strsafe(); void Strsafe_init(/* void */); int Strsafe_insert(/* char * */); char *Strsafe_find(/* char * */); /* Routines for handling symbols of the grammar */ struct symbol *Symbol_new(); int Symbolcmpp(/* struct symbol **, struct symbol ** */); void Symbol_init(/* void */); int Symbol_insert(/* struct symbol *, char * */); struct symbol *Symbol_find(/* char * */); struct symbol *Symbol_Nth(/* int */); int Symbol_count(/* */); int State_count(void); struct symbol **Symbol_arrayof(/* */); /* Routines to manage the state table */ int Configcmp(/* struct config *, struct config * */); struct state *State_new(); void State_init(/* void */); int State_insert(/* struct state *, struct config * */); struct state *State_find(/* struct config * */); struct state **State_arrayof(/* */); /* 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 */ struct action *Action_new(){ static struct action *freelist = NULL; struct action *new; if( freelist==NULL ){ int i; int amt = 100; freelist = (struct action *)malloc( sizeof(struct action)*amt ); if( freelist==0 ){ fprintf(stderr,"Unable to allocate memory for a new parser action."); exit(1); } for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1]; freelist[amt-1].next = 0; } new = freelist; freelist = freelist->next; return new; } /* Compare two actions */ static int actioncmp(ap1,ap2) 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 ){ assert( ap1->type==REDUCE || ap1->type==RD_RESOLVED || ap1->type==CONFLICT); assert( ap2->type==REDUCE || ap2->type==RD_RESOLVED || ap2->type==CONFLICT); rc = ap1->x.rp->index - ap2->x.rp->index; } return rc; } /* Sort parser actions */ struct action *Action_sort(ap) struct action *ap; { ap = (struct action *)msort(ap,(void **)&ap->next,actioncmp); return ap; } void Action_add(app,type,sp,arg) struct action **app; enum e_action type; struct symbol *sp; void *arg; { struct action *new; new = Action_new(); new->next = *app; *app = new; new->type = type; new->sp = sp; if( type==SHIFT ){ new->x.stp = (struct state *)arg; }else{ new->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 */ typedef struct acttab acttab; struct acttab { int nAction; /* Number of used slots in aAction[] */ int nActionAlloc; /* Slots allocated for aAction[] */ struct { int lookahead; /* Value of the lookahead token */ int action; /* Action to take on the given lookahead */ } *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[] */ }; /* Return the number of entries in the yy_action table */ #define acttab_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 */ /* PRIVATE void acttab_free(acttab *p){ free( p->aAction ); free( p->aLookahead ); free( p ); } */ /* Allocate a new acttab structure */ PRIVATE acttab *acttab_alloc(void){ acttab *p = malloc( sizeof(*p) ); if( p==0 ){ fprintf(stderr,"Unable to allocate memory for a new acttab."); exit(1); } memset(p, 0, sizeof(*p)); return p; } /* Add a new action to the current transaction set */ PRIVATE void acttab_action(acttab *p, int lookahead, int action){ if( p->nLookahead>=p->nLookaheadAlloc ){ p->nLookaheadAlloc += 25; p->aLookahead = 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. */ PRIVATE int acttab_insert(acttab *p){ int i, j, k, n; 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->mxLookahead + 1; if( p->nAction + n >= p->nActionAlloc ){ int oldAlloc = p->nActionAlloc; p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20; p->aAction = 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 where we can ** insert the current transaction set. Fall out of the loop when that ** offset is found. In the worst case, we fall out of the loop when ** i reaches p->nAction, which means we append the new transaction set. ** ** i is the index in p->aAction[] where p->mnLookahead is inserted. */ for(i=0; i<p->nAction+p->mnLookahead; 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 */ } }else if( p->aAction[i].lookahead==p->mnLookahead ){ 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; 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; /* Same as a prior transaction set */ } } } /* Insert transaction set at index i. */ 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; } 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; } /********************** From the file "assert.c" ****************************/ /* ** A more efficient way of handling assertions. */ void myassert(file,line) char *file; int line; { fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file); exit(1); } /********************** 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(xp) struct lemon *xp; { struct rule *rp; for(rp=xp->rule; rp; rp=rp->next){ if( rp->precsym==0 ){ int i; for(i=0; i<rp->nrhs; i++){ if( rp->rhs[i]->prec>=0 ){ rp->precsym = rp->rhs[i]; break; } } } } 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(lemp) struct lemon *lemp; { int i; struct rule *rp; int progress; for(i=0; i<lemp->nsymbol; i++){ lemp->symbols[i]->lambda = Bo_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++){ if( rp->rhs[i]->lambda==Bo_FALSE ) break; } if( i==rp->nrhs ){ rp->lhs->lambda = Bo_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( s1==s2 ){ if( s1->lambda==Bo_FALSE ) break; }else{ progress += SetUnion(s1->firstset,s2->firstset); if( s2->lambda==Bo_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(lemp) 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->rule->lhs->name); lemp->errorcnt++; sp = lemp->rule->lhs; } }else{ sp = lemp->rule->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 ){ 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; 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(lemp) 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->index = 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; } /* 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(lemp,stp) struct lemon *lemp; struct state *stp; /* The state from which successors are computed */ { struct config *cfp; /* For looping through the config closure of "stp" */ struct config *bcfp; /* For the inner loop on config closure of "stp" */ struct config *new; /* */ 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( bsp!=sp ) continue; /* Must be same as for "cfp" */ bcfp->status = COMPLETE; /* Mark this config as used */ new = Configlist_addbasis(bcfp->rp,bcfp->dot+1); Plink_add(&new->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" */ Action_add(&stp->ap,SHIFT,sp,newstp); } } /* ** Construct the propagation links */ void FindLinks(lemp) 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(lemp) struct lemon *lemp; { int i; struct config *cfp; struct state *stp; struct plink *plp; int progress; int change; for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; for(cfp=stp->cfp; cfp; cfp=cfp->next){ cfp->status = INCOMPLETE; } } do{ progress = 0; for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; for(cfp=stp->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(); /* Compute the reduce actions, and resolve conflicts. */ void FindActions(lemp) struct lemon *lemp; { int i,j; struct config *cfp; 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 */ struct state *stp; 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],cfp->rp); } } } } } /* Add the accepting token */ if( lemp->start ){ sp = Symbol_find(lemp->start); if( sp==0 ) sp = lemp->rule->lhs; }else{ sp = lemp->rule->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. */ if (lemp->nstate) { /*(should always be true)*/ struct state *stp; stp = lemp->sorted[0]; Action_add(&stp->ap,ACCEPT,sp,0); } /* Resolve conflicts */ for(i=0; i<lemp->nstate; i++){ struct action *ap, *nap; struct state *stp; 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,lemp->errsym); } } } /* Report an error for each rule that can never be reduced. */ for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = Bo_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 = Bo_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 resolve, 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(apx,apy,errsym) struct action *apx; struct action *apy; struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */ { struct symbol *spx, *spy; int errcnt = 0; UNUSED(errsym); assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */ 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 = CONFLICT; errcnt++; }else if( spx->prec>spy->prec ){ /* Lower 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 ); apy->type = CONFLICT; errcnt++; } }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 = CONFLICT; 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==CONFLICT || apy->type==SH_RESOLVED || apy->type==RD_RESOLVED || apy->type==CONFLICT ); /* 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(){ struct config *new; if( freelist==0 ){ int i; int amt = 3; freelist = (struct config *)malloc( sizeof(struct config)*amt ); 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; } new = freelist; freelist = freelist->next; return new; } /* The configuration "old" is no longer used */ PRIVATE void deleteconfig(old) struct config *old; { old->next = freelist; freelist = old; } /* Initialized the configuration list builder */ void Configlist_init(){ current = 0; currentend = &current; basis = 0; basisend = &basis; Configtable_init(); return; } /* Initialized the configuration list builder */ void Configlist_reset(){ current = 0; currentend = &current; basis = 0; basisend = &basis; Configtable_clear(0); return; } /* Add another configuration to the configuration list */ struct config *Configlist_add(rp,dot) 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(rp,dot) 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(lemp) 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{ SetUnion(newcfp->fws,xsp->firstset); if( xsp->lambda==Bo_FALSE ) break; } } if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp); } } } return; } /* Sort the configuration list */ void Configlist_sort(){ current = (struct config *)msort(current,(void **)&(current->next),Configcmp); currentend = 0; return; } /* Sort the basis configuration list */ void Configlist_sortbasis(){ basis = (struct config *)msort(current,(void **)&(current->bp),Configcmp); basisend = 0; return; } /* Return a pointer to the head of the configuration list and ** reset the list */ struct config *Configlist_return(){ 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(){ struct config *old; old = basis; basis = 0; basisend = 0; return old; } /* Free all elements of the given configuration list */ void Configlist_eat(cfp) 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. */ /* Find a good place to break "msg" so that its length is at least "min" ** but no more than "max". Make the point as close to max as possible. */ static int findbreak(msg,min,max) char *msg; int min; int max; { int i,spot; char c; for(i=spot=min; i<=max; i++){ c = msg[i]; if( c=='\t' ) msg[i] = ' '; if( c=='\n' ){ msg[i] = ' '; spot = i; break; } if( c==0 ){ spot = i; break; } if( c=='-' && i<max-1 ) spot = i+1; if( c==' ' ) spot = i; } return spot; } /* ** The error message is split across multiple lines if necessary. The ** splits occur at a space, if there is a space available near the end ** of the line. */ #define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */ #define LINEWIDTH 79 /* Max width of any output line */ #define PREFIXLIMIT 30 /* Max width of the prefix on each line */ void ErrorMsg(const char *filename, int lineno, const char *format, ...){ char errmsg[ERRMSGSIZE]; char prefix[PREFIXLIMIT+10]; int errmsgsize; int prefixsize; int availablewidth; va_list ap; int end, restart, base; va_start(ap, format); /* Prepare a prefix to be prepended to every output line */ if( lineno>0 ){ sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno); }else{ sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename); } prefixsize = strlen(prefix); availablewidth = LINEWIDTH - prefixsize; /* Generate the error message */ vsprintf(errmsg,format,ap); va_end(ap); errmsgsize = strlen(errmsg); /* Remove trailing '\n's from the error message. */ while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){ errmsg[--errmsgsize] = 0; } /* Print the error message */ base = 0; while( errmsg[base]!=0 ){ end = restart = findbreak(&errmsg[base],0,availablewidth); restart += base; while( errmsg[restart]==' ' ) restart++; fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]); base = restart; } } /**************** 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() { fprintf(stderr,"Out of memory. Aborting...\n"); exit(1); } static const char* out_dir = "."; /* The main program. Parse the command line and do it... */ int main(argc,argv) 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 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_FLAG, "g", (char*)&rpflag, "Print grammar without actions."}, {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"}, {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."}, {OPT_FLAG, "s", (char*)&statistics, "Print parser stats to standard output."}, {OPT_FLAG, "x", (char*)&version, "Print the version number."}, {OPT_STR, "o", (char*)&out_dir, "Customize output directory."}, {OPT_FLAG,0,0,0} }; int i; struct lemon lem; char *def_tmpl_name = "lempar.c"; UNUSED(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); } lem.errorcnt = 0; /* Initialize the machine */ Strsafe_init(); Symbol_init(); State_init(); lem.argv0 = argv[0]; lem.filename = OptArg(0); lem.tmplname = (OptNArgs() == 2) ? OptArg(1) : def_tmpl_name; lem.basisflag = basisflag; lem.has_fallback = 0; lem.nconflict = 0; lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0; lem.vartype = 0; lem.stacksize = 0; lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest = lem.tokenprefix = lem.outname = lem.extracode = 0; lem.vardest = 0; lem.tablesize = 0; Symbol_new("$"); lem.errsym = Symbol_new("error"); /* Parse the input file */ Parse(&lem); if( lem.errorcnt ) exit(lem.errorcnt); if( lem.rule==0 ){ fprintf(stderr,"Empty grammar.\n"); exit(1); } /* 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*), (int(*)())Symbolcmpp); for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i; for(i=1; i<lem.nsymbol && isupper(lem.symbols[i]->name[0]); i++); lem.nsymbol--; /*(do not count "{default}")*/ lem.nterminal = i; /* 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); /* 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.nstate = State_count(); 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); /* 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); /* 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: %d terminals, %d nonterminals, %d rules\n", lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule); printf(" %d states, %d parser table entries, %d conflicts\n", lem.nstate, lem.tablesize, lem.nconflict); } if( lem.nconflict ){ fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict); } exit(lem.errorcnt + lem.nconflict); } /******************** 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**)(((unsigned long)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(a,b,cmp,offset) char *a; char *b; int (*cmp)(); 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 void *msort(void *list, void **next, int(*cmp)(void *, void *)) { unsigned long offset; char *ep; char *set[LISTSIZE]; int i; offset = (unsigned long)next - (unsigned long)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(ep,set[i],cmp,offset); return ep; } /************************ From the file "option.c" **************************/ static char **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(n,k,err) int n; int k; FILE *err; { int spcnt = 0, i; if( argv[0] ) { fprintf(err,"%s",argv[0]); spcnt += strlen(argv[0]) + 1; } for(i=1; i<n && argv[i]; i++){ fprintf(err," %s",argv[i]); spcnt += strlen(argv[i]) + 1; } spcnt += k; for(; argv[i]; i++) fprintf(err," %s",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(n) int n; { int i; int dashdash = 0; if( argv!=0 && *argv!=0 ){ for(i=1; argv[i]; i++){ if( dashdash || !ISOPT(argv[i]) ){ if( n==0 ) return i; n--; } if( strcmp(argv[i],"--")==0 ) dashdash = 1; } } return -1; } static char emsg[] = "Command line syntax error: "; /* ** Process a flag command line argument. */ static int handleflags(i,err) int i; FILE *err; { int v; int errcnt = 0; int j; for(j=0; op[j].label; j++){ if( strcmp(&argv[i][1],op[j].label)==0 ) break; } v = 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].type==OPT_FLAG ){ *((int*)op[j].arg) = v; }else if( op[j].type==OPT_FFLAG ){ (*(void(*)())(intptr_t)(op[j].arg))(v); }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(i,err) int i; FILE *err; { int lv = 0; double dv = 0.0; char *sv = 0, *end; char *cp; int j; int errcnt = 0; cp = strchr(argv[i],'='); *cp = 0; for(j=0; op[j].label; j++){ if( strcmp(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,((unsigned long)end)-(unsigned long)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,((unsigned long)end)-(unsigned long)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(*)())(intptr_t)(op[j].arg))(dv); break; case OPT_INT: *(int*)(op[j].arg) = lv; break; case OPT_FINT: (*(void(*)())(intptr_t)(op[j].arg))((int)lv); break; case OPT_STR: *(char**)(op[j].arg) = sv; break; case OPT_FSTR: (*(void(*)())(intptr_t)(op[j].arg))(sv); break; } } return errcnt; } int OptInit(a,o,err) char **a; struct s_options *o; FILE *err; { int errcnt = 0; argv = a; op = o; errstream = err; if( argv && *argv && op ){ int i; for(i=1; argv[i]; i++){ if( argv[i][0]=='+' || argv[i][0]=='-' ){ errcnt += handleflags(i,err); }else if( strchr(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(){ int cnt = 0; int dashdash = 0; int i; if( argv!=0 && argv[0]!=0 ){ for(i=1; argv[i]; i++){ if( dashdash || !ISOPT(argv[i]) ) cnt++; if( strcmp(argv[i],"--")==0 ) dashdash = 1; } } return cnt; } char *OptArg(n) int n; { int i; i = argindex(n); return i>=0 ? argv[i] : 0; } void OptErr(n) int n; { int i; i = argindex(n); if( i>=0 ) errline(i,0,errstream); } void OptPrint(){ int i; int max, len; max = 0; for(i=0; op[i].label; i++){ len = strlen(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-strlen(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-strlen(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-strlen(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 */ 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 { 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 } state; /* The state of the parser */ struct symbol *fallback; /* The fallback token */ struct symbol *lhs; /* Left-hand side of current rule */ char *lhsalias; /* Alias for the LHS */ int nrhs; /* Number of right-hand side symbols seen */ struct symbol *rhs[MAXRHS]; /* RHS symbols */ char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */ struct rule *prevrule; /* Previous rule parsed */ char *declkeyword; /* Keyword of a declaration */ char **declargslot; /* Where the declaration argument should be put */ int *decllnslot; /* Where the declaration linenumber is put */ 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(psp) struct pstate *psp; { 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 not prior rule opon 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{ psp->prevrule->line = psp->tokenlineno; psp->prevrule->code = &x[1]; } }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 *)malloc( sizeof(struct rule) + sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs ); 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 = (char**)&(rp->rhs[psp->nrhs]); for(i=0; i<psp->nrhs; i++){ rp->rhs[i] = psp->rhs[i]; rp->rhsalias[i] = psp->alias[i]; } rp->lhs = psp->lhs; rp->lhsalias = psp->lhsalias; rp->nrhs = psp->nrhs; rp->code = 0; 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 symbol on RHS or 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]=='(' && 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->decllnslot = 0; psp->state = WAITING_FOR_DECL_ARG; if( strcmp(x,"name")==0 ){ psp->declargslot = &(psp->gp->name); }else if( strcmp(x,"include")==0 ){ psp->declargslot = &(psp->gp->include); psp->decllnslot = &psp->gp->includeln; }else if( strcmp(x,"code")==0 ){ psp->declargslot = &(psp->gp->extracode); psp->decllnslot = &psp->gp->extracodeln; }else if( strcmp(x,"token_destructor")==0 ){ psp->declargslot = &psp->gp->tokendest; psp->decllnslot = &psp->gp->tokendestln; }else if( strcmp(x,"default_destructor")==0 ){ psp->declargslot = &psp->gp->vardest; psp->decllnslot = &psp->gp->vardestln; }else if( strcmp(x,"token_prefix")==0 ){ psp->declargslot = &psp->gp->tokenprefix; }else if( strcmp(x,"syntax_error")==0 ){ psp->declargslot = &(psp->gp->error); psp->decllnslot = &psp->gp->errorln; }else if( strcmp(x,"parse_accept")==0 ){ psp->declargslot = &(psp->gp->accept); psp->decllnslot = &psp->gp->acceptln; }else if( strcmp(x,"parse_failure")==0 ){ psp->declargslot = &(psp->gp->failure); psp->decllnslot = &psp->gp->failureln; }else if( strcmp(x,"stack_overflow")==0 ){ psp->declargslot = &(psp->gp->overflow); psp->decllnslot = &psp->gp->overflowln; }else if( strcmp(x,"extra_argument")==0 ){ psp->declargslot = &(psp->gp->arg); }else if( strcmp(x,"token_type")==0 ){ psp->declargslot = &(psp->gp->tokentype); }else if( strcmp(x,"default_type")==0 ){ psp->declargslot = &(psp->gp->vartype); }else if( strcmp(x,"stack_size")==0 ){ psp->declargslot = &(psp->gp->stacksize); }else if( strcmp(x,"start_symbol")==0 ){ psp->declargslot = &(psp->gp->start); }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{ 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->decllnslot = &sp->destructorln; 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 %%destructor keyword"); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; }else{ struct symbol *sp = Symbol_new(x); psp->declargslot = &sp->datatype; psp->decllnslot = 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])) ){ if( *(psp->declargslot)!=0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "The argument \"%s\" to declaration \"%%%s\" is not the first.", x[0]=='\"' ? &x[1] : x,psp->declkeyword); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; }else{ *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x; if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno; 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 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; } } /* 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". */ struct pstate ps; void Parse(gp) struct lemon *gp; { FILE *fp; char *filebuf; size_t filesize; int lineno; int c; char *cp, *nextcp; int startline = 0; 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( filebuf==0 ){ ErrorMsg(ps.filename,0,"Can't allocate %zu of memory to hold this file.", filesize+1); fclose(fp); gp->errorcnt++; return; } if( fread(filebuf,1,filesize,fp)!=filesize ){ ErrorMsg(ps.filename,0,"Can't read in all %zu bytes of this file.", filesize); free(filebuf); fclose(fp); gp->errorcnt++; return; } fclose(fp); filebuf[filesize] = 0; /* 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{ /* All other (one character) operators */ cp++; nextcp = cp; } c = *cp; *cp = 0; /* Null terminate the token */ parseonetoken(&ps); /* Parse the token */ *cp = 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(){ struct plink *new; if( plink_freelist==0 ){ int i; int amt = 100; plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt ); 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; } new = plink_freelist; plink_freelist = plink_freelist->next; return new; } /* Add a plink to a plink list */ void Plink_add(plpp,cfp) struct plink **plpp; struct config *cfp; { struct plink *new; new = Plink_new(); new->next = *plpp; *plpp = new; new->cfp = cfp; } /* Transfer every plink on the list "from" to the list "to" */ void Plink_copy(to,from) 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(plp) 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(lemp,suffix) struct lemon *lemp; char *suffix; { char *name; char *cp; name = malloc( strlen(out_dir) + strlen(lemp->filename) + strlen(suffix) + 6 ); if( name==0 ){ fprintf(stderr,"Can't allocate space for a filename.\n"); exit(1); } /* skip directory, JK */ if (NULL == (cp = strrchr(lemp->filename, '/'))) { cp = lemp->filename; } else { cp++; } strcpy(name,out_dir); strcat(name,"/"); strcat(name,cp); cp = strrchr(name,'.'); if( cp ) *cp = 0; 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(lemp,suffix,mode) struct lemon *lemp; char *suffix; 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; } /* Duplicate the input file without comments and without actions ** on rules */ void Reprint(lemp) 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 = strlen(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){ printf("%s",rp->lhs->name); /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */ printf(" ::="); for(i=0; i<rp->nrhs; i++){ printf(" %s",rp->rhs[i]->name); /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */ } printf("."); if( rp->precsym ) printf(" [%s]",rp->precsym->name); /* if( rp->code ) printf("\n %s",rp->code); */ printf("\n"); } } PRIVATE void ConfigPrint(fp,cfp) FILE *fp; struct config *cfp; { struct rule *rp; int i; rp = cfp->rp; fprintf(fp,"%s ::=",rp->lhs->name); for(i=0; i<=rp->nrhs; i++){ if( i==cfp->dot ) fprintf(fp," *"); if( i==rp->nrhs ) break; fprintf(fp," %s",rp->rhs[i]->name); } } /* #define TEST */ #ifdef TEST /* 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 */ void PlinkPrint(out,plp,tag) FILE *out; struct plink *plp; char *tag; { while( plp ){ fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->index); 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. */ PRIVATE int PrintAction(struct action *ap, FILE *fp, int indent){ int result = 1; switch( ap->type ){ case SHIFT: fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->index); break; case REDUCE: fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index); break; case ACCEPT: fprintf(fp,"%*s accept",indent,ap->sp->name); break; case ERROR: fprintf(fp,"%*s error",indent,ap->sp->name); break; case CONFLICT: fprintf(fp,"%*s reduce %-3d ** Parsing conflict **", indent,ap->sp->name,ap->x.rp->index); break; case SH_RESOLVED: case RD_RESOLVED: case NOT_USED: result = 0; break; } return result; } /* Generate the "y.output" log file */ void ReportOutput(lemp) struct lemon *lemp; { int i; struct state *stp; struct config *cfp; struct action *ap; FILE *fp; fp = file_open(lemp,".out","w"); if( fp==0 ) return; fprintf(fp," \b"); for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; fprintf(fp,"State %d:\n",stp->index); if( lemp->basisflag ) cfp=stp->bp; else cfp=stp->cfp; while( cfp ){ char buf[20]; if( cfp->dot==cfp->rp->nrhs ){ sprintf(buf,"(%d)",cfp->rp->index); fprintf(fp," %5s ",buf); }else{ fprintf(fp," "); } ConfigPrint(fp,cfp); fprintf(fp,"\n"); #ifdef TEST 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"); } fclose(fp); return; } /* Search for the file "name" which is in the same directory as ** the executable */ PRIVATE char *pathsearch(argv0,name,modemask) char *argv0; char *name; int modemask; { char *pathlist; char *path,*cp; char c; #ifdef __WIN32__ cp = strrchr(argv0,'\\'); #else cp = strrchr(argv0,'/'); #endif if( cp ){ c = *cp; *cp = 0; path = (char *)malloc( strlen(argv0) + strlen(name) + 2 ); if( path ) sprintf(path,"%s/%s",argv0,name); *cp = c; }else{ pathlist = getenv("PATH"); if( pathlist==0 ) pathlist = ".:/bin:/usr/bin"; path = (char *)malloc( strlen(pathlist)+strlen(name)+2 ); if( path!=0 ){ while( *pathlist ){ cp = strchr(pathlist,':'); if( cp==0 ) cp = &pathlist[strlen(pathlist)]; c = *cp; *cp = 0; sprintf(path,"%s/%s",pathlist,name); *cp = c; if( c==0 ) pathlist = ""; else pathlist = &cp[1]; if( access(path,modemask)==0 ) break; } } } 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(lemp,ap) struct lemon *lemp; struct action *ap; { int act; switch( ap->type ){ case SHIFT: act = ap->x.stp->index; break; case REDUCE: act = ap->x.rp->index + lemp->nstate; break; case ERROR: act = lemp->nstate + lemp->nrule; break; case ACCEPT: act = lemp->nstate + lemp->nrule + 1; 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(name,in,out,lineno) 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]); } } /* The next function finds the template file and opens it, returning ** a pointer to the opened file. */ PRIVATE FILE *tplt_open(lemp) struct lemon *lemp; { char buf[1000]; FILE *in; char *tpltname; char *tpltname_alloc = NULL; char *cp; cp = strrchr(lemp->filename,'.'); if( cp ){ sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename); }else{ sprintf(buf,"%s.lt",lemp->filename); } if( access(buf,004)==0 ){ tpltname = buf; }else if( access(lemp->tmplname,004)==0 ){ tpltname = lemp->tmplname; }else{ tpltname = tpltname_alloc = pathsearch(lemp->argv0,lemp->tmplname,0); } if( tpltname==0 ){ fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", lemp->tmplname); lemp->errorcnt++; return 0; } in = fopen(tpltname,"r"); if( in==0 ){ fprintf(stderr,"Can't open the template file \"%s\".\n",tpltname); lemp->errorcnt++; } if (tpltname_alloc) free(tpltname_alloc); return in; } /* Print a string to the file and keep the linenumber up to date */ PRIVATE void tplt_print(out,lemp,str,strln,lineno) FILE *out; struct lemon *lemp; char *str; int strln; int *lineno; { if( str==0 ) return; fprintf(out,"#line %d \"%s\"\n",strln,lemp->filename); (*lineno)++; while( *str ){ if( *str=='\n' ) (*lineno)++; putc(*str,out); str++; } fprintf(out,"\n#line %d \"%s\"\n",*lineno+2,lemp->outname); (*lineno)+=2; return; } /* ** The following routine emits code for the destructor for the ** symbol sp */ PRIVATE void emit_destructor_code(out,sp,lemp,lineno) FILE *out; struct symbol *sp; struct lemon *lemp; int *lineno; { char *cp = 0; int linecnt = 0; if( sp->type==TERMINAL ){ cp = lemp->tokendest; if( cp==0 ) return; fprintf(out,"#line %d \"%s\"\n{",lemp->tokendestln,lemp->filename); }else if( sp->destructor ){ cp = sp->destructor; fprintf(out,"#line %d \"%s\"\n{",sp->destructorln,lemp->filename); }else{ cp = lemp->vardest; if( cp==0 ) return; fprintf(out,"#line %d \"%s\"\n{",lemp->vardestln,lemp->filename); } for(; *cp; cp++){ if( *cp=='$' && cp[1]=='$' ){ fprintf(out,"(yypminor->yy%d)",sp->dtnum); cp++; continue; } if( *cp=='\n' ) linecnt++; fputc(*cp,out); } (*lineno) += 3 + linecnt; fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname); return; } /* ** Return TRUE (non-zero) if the given symbol has a destructor. */ PRIVATE int has_destructor(sp, lemp) 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; } /* ** 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(out,rp,lemp,lineno) FILE *out; struct rule *rp; struct lemon *lemp; int *lineno; { char *cp, *xp; int linecnt = 0; int i; char lhsused = 0; /* True if the LHS element has been used */ char used[MAXRHS]; /* True for each RHS element which is used */ for(i=0; i<rp->nrhs; i++) used[i] = 0; lhsused = 0; /* Generate code to do the reduce action */ if( rp->code ){ fprintf(out,"#line %d \"%s\"\n{",rp->line,lemp->filename); for(cp=rp->code; *cp; cp++){ 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 ){ fprintf(out,"yygotominor.yy%d",rp->lhs->dtnum); cp = xp; lhsused = 1; }else{ for(i=0; i<rp->nrhs; i++){ if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){ fprintf(out,"yymsp[%d].minor.yy%d",i-rp->nrhs+1,rp->rhs[i]->dtnum); cp = xp; used[i] = 1; break; } } } *xp = saved; } if( *cp=='\n' ) linecnt++; fputc(*cp,out); } /* End loop */ (*lineno) += 3 + linecnt; fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname); } /* End if( rp->code ) */ /* 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 symbols which are not used in the ** reduce code */ for(i=0; i<rp->nrhs; i++){ if( rp->rhsalias[i] && !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( rp->rhsalias[i]==0 ){ if( has_destructor(rp->rhs[i],lemp) ){ fprintf(out," yy_destructor(%d,&yymsp[%d].minor);\n", rp->rhs[i]->index,i-rp->nrhs+1); (*lineno)++; }else{ fprintf(out," /* No destructor defined for %s */\n", rp->rhs[i]->name); (*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. */ PRIVATE void print_stack_union(out,lemp,plineno,mhflag) 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; /* 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 */ int hash; /* For hashing the name of a type */ char *name; /* Name of the parser */ /* Allocate and initialize types[] and allocate stddt[] */ arraysize = lemp->nsymbol * 2; types = (char**)malloc( arraysize * sizeof(char*) ); for(i=0; i<arraysize; i++) types[i] = 0; maxdtlength = 0; if( lemp->vartype ){ maxdtlength = strlen(lemp->vartype); } for(i=0; i<lemp->nsymbol; i++){ int len; struct symbol *sp = lemp->symbols[i]; if( sp->datatype==0 ) continue; len = strlen(sp->datatype); if( len>maxdtlength ) maxdtlength = len; } stddt = (char*)malloc( maxdtlength*2 + 1 ); if( types==0 || 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; hash = 0; for(j=0; stddt[j]; j++){ hash = (unsigned int)hash*53u + (unsigned int) stddt[j]; } hash = (hash & 0x7fffffff)%arraysize; while( types[hash] ){ if( strcmp(types[hash],stddt)==0 ){ sp->dtnum = hash + 1; break; } hash++; if( hash>=arraysize ) hash = 0; } if( types[hash]==0 ){ sp->dtnum = hash + 1; types[hash] = (char*)malloc( strlen(stddt)+1 ); if( types[hash]==0 ){ fprintf(stderr,"Out of memory.\n"); exit(1); } 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," %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]); } 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. */ static const char *minimum_size_type(int lwr, int upr){ if( lwr>=0 ){ if( upr<=255 ){ return "unsigned char"; }else if( upr<65535 ){ return "unsigned short int"; }else{ return "unsigned int"; } }else if( lwr>=-127 && upr<=127 ){ return "signed char"; }else if( lwr>=-32767 && upr<32767 ){ return "short"; }else{ return "int"; } } /* ** 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 */ }; /* ** 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; return p2->nAction - p1->nAction; } /* Generate C source code for the parser */ void ReportTable(lemp, mhflag) struct lemon *lemp; int mhflag; /* Output in makeheaders format if true */ { FILE *out, *in; char line[LINESIZE]; int lineno; struct state *stp; struct action *ap; struct rule *rp; struct acttab *pActtab; int i, j, n; int mnTknOfst, mxTknOfst; int mnNtOfst, mxNtOfst; struct axset *ax; char *name; in = tplt_open(lemp); if( in==0 ) return; out = file_open(lemp,".c","w"); if( out==0 ){ fclose(in); return; } lineno = 1; tplt_xfer(lemp->name,in,out,&lineno); /* Generate the include code, if any */ tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno); if( mhflag ){ name = file_makename(lemp, ".h"); fprintf(out,"#include \"%s\"\n", name); lineno++; free(name); } tplt_xfer(lemp->name,in,out,&lineno); /* Generate #defines for all tokens */ if( mhflag ){ char *prefix; fprintf(out,"#if INTERFACE\n"); lineno++; if( lemp->tokenprefix ) prefix = lemp->tokenprefix; else prefix = ""; 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,"/* \001 */\n"); fprintf(out,"#define YYCODETYPE %s\n", minimum_size_type(0, lemp->nsymbol+5)); lineno++; fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++; fprintf(out,"#define YYACTIONTYPE %s\n", minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++; print_stack_union(out,lemp,&lineno,mhflag); if( lemp->stacksize ){ if( atoi(lemp->stacksize)<=0 ){ ErrorMsg(lemp->filename,0, "Illegal stack size: [%s]. The stack size should be an integer constant.", lemp->stacksize); lemp->errorcnt++; lemp->stacksize = "100"; } fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++; }else{ fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++; } if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; } name = lemp->name ? lemp->name : "Parse"; if( lemp->arg && lemp->arg[0] ){ i = strlen(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_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_FETCH\n",name); lineno++; fprintf(out,"#define %sARG_STORE\n",name); lineno++; } if( mhflag ){ fprintf(out,"#endif\n"); lineno++; } fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++; fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++; 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++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate 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. */ /* Compute the actions on all states and count them up */ ax = malloc( sizeof(ax[0])*lemp->nstate*2 ); if( ax==0 ){ fprintf(stderr,"malloc failed\n"); exit(1); } for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; stp->nTknAct = stp->nNtAct = 0; stp->iDflt = lemp->nstate + lemp->nrule; stp->iTknOfst = NO_OFFSET; stp->iNtOfst = NO_OFFSET; for(ap=stp->ap; ap; ap=ap->next){ if( compute_action(lemp,ap)>=0 ){ if( ap->sp->index<lemp->nterminal ){ stp->nTknAct++; }else if( ap->sp->index<lemp->nsymbol ){ stp->nNtAct++; }else{ stp->iDflt = compute_action(lemp, ap); } } } 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; /* Compute the action table. In order to try to keep the size of the ** action table to a minimum, the heuristic of placing the largest action ** sets first is used. */ qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare); pActtab = acttab_alloc(); for(i=0; i<lemp->nstate*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); 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); if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst; if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst; } } free(ax); /* Output the yy_action table */ fprintf(out,"static YYACTIONTYPE yy_action[] = {\n"); lineno++; n = acttab_size(pActtab); for(i=j=0; i<n; i++){ int action = acttab_yyaction(pActtab, i); if( action<0 ) action = lemp->nsymbol + lemp->nrule + 2; 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 */ fprintf(out,"static 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 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; /* Output the yy_shift_ofst[] table */ fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++; fprintf(out, "static %s yy_shift_ofst[] = {\n", minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++; n = lemp->nstate; for(i=j=0; i<n; i++){ int ofst; stp = lemp->sorted[i]; ofst = stp->iTknOfst; if( ofst==NO_OFFSET ) ofst = mnTknOfst - 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 yy_reduce_ofst[] table */ fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++; fprintf(out, "static %s yy_reduce_ofst[] = {\n", minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++; n = lemp->nstate; 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 YYACTIONTYPE yy_default[] = {\n"); lineno++; n = lemp->nstate; for(i=j=0; i<n; i++){ stp = lemp->sorted[i]; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", stp->iDflt); 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 ){ for(i=0; i<lemp->nterminal; 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++){ sprintf(line,"\"%s\",",lemp->symbols[i]->name); fprintf(out," %-15s",line); if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; } } if( (i&3)!=0 ){ fprintf(out,"\n"); 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->index==i ); fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name); for(j=0; j<rp->nrhs; j++) fprintf(out," %s",rp->rhs[j]->name); 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 ){ for(i=0; i<lemp->nsymbol; i++){ struct symbol *sp = lemp->symbols[i]; if( sp==0 || sp->type!=TERMINAL ) continue; fprintf(out," case %d:\n",sp->index); 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++; } } for(i=0; i<lemp->nsymbol; i++){ struct symbol *sp = lemp->symbols[i]; if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue; fprintf(out," case %d:\n",sp->index); lineno++; emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); fprintf(out," break;\n"); lineno++; } if( lemp->vardest ){ struct symbol *dflt_sp = 0; 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; fprintf(out," case %d:\n",sp->index); lineno++; dflt_sp = sp; } if( dflt_sp!=0 ){ emit_destructor_code(out,dflt_sp,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,lemp->overflowln,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Generate the table of rule information ** ** Note: This code depends on the fact that rules are number ** sequentually beginning with 0. */ for(rp=lemp->rule; rp; rp=rp->next){ fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which execution during each REDUCE action */ for(rp=lemp->rule; rp; rp=rp->next){ fprintf(out," case %d:\n",rp->index); lineno++; emit_code(out,rp,lemp,&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,lemp->failureln,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes when a syntax error occurs */ tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes when the parser accepts its input */ tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Append any addition code the user desires */ tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno); fclose(in); fclose(out); return; } /* Generate a header file for the parser */ void ReportHeader(lemp) struct lemon *lemp; { FILE *out, *in; char *prefix; char line[LINESIZE]; char pattern[LINESIZE]; int i; if( lemp->tokenprefix ) prefix = lemp->tokenprefix; else prefix = ""; in = file_open(lemp,".h","r"); if( in ){ for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){ sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); if( strcmp(line,pattern) ) break; } fclose(in); if( i==lemp->nterminal ){ /* No change in the file. Don't rewrite it. */ return; } } out = file_open(lemp,".h","w"); if( out ){ for(i=1; i<lemp->nterminal; i++){ fprintf(out,"#define %s%-30s %2d\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. Only default a reduce if there are more than one. */ void CompressTables(lemp) struct lemon *lemp; { struct state *stp; struct action *ap, *ap2; struct rule *rp, *rp2, *rbest; int nbest, n; int i; for(i=0; i<lemp->nstate; i++){ stp = lemp->sorted[i]; nbest = 0; rbest = 0; for(ap=stp->ap; ap; ap=ap->next){ if( ap->type!=REDUCE ) continue; rp = ap->x.rp; 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 2 */ if( nbest<2 ) 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); } } /***************** From the file "set.c" ************************************/ /* ** Set manipulation routines for the LEMON parser generator. */ static int global_size = 0; /* Set the set size */ void SetSize(n) int n; { global_size = n+1; } /* Allocate a new set */ char *SetNew(){ char *s; int i; s = (char*)malloc( global_size ); if( s==0 ){ memory_error(); } for(i=0; i<global_size; i++) s[i] = 0; return s; } /* Deallocate a set */ void SetFree(s) 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(s,e) char *s; int e; { int rv; rv = s[e]; s[e] = 1; return !rv; } /* Add every element of s2 to s1. Return TRUE if s1 changes. */ int SetUnion(s1,s2) char *s1; char *s2; { int i, progress; progress = 0; for(i=0; i<global_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 int strhash(x) char *x; { unsigned int h = 0; while( *x) h = h*13u + (unsigned int) *(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. */ char *Strsafe(y) char *y; { char *z; z = Strsafe_find(y); if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){ strcpy(z,y); 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 { 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(){ if( x1a ) return; x1a = (struct s_x1*)malloc( sizeof(struct s_x1) ); if( x1a ){ x1a->size = 1024; x1a->count = 0; x1a->tbl = (x1node*)malloc( (sizeof(x1node) + sizeof(x1node*))*1024 ); 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(data) char *data; { x1node *np; int h; int 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,size; struct s_x1 array; array.size = size = x1a->size*2; array.count = x1a->count; array.tbl = (x1node*)malloc( (sizeof(x1node) + sizeof(x1node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x1node**)&(array.tbl[size]); for(i=0; i<size; i++) array.ht[i] = 0; for(i=0; i<x1a->count; i++){ x1node *oldnp, *newnp; oldnp = &(x1a->tbl[i]); h = strhash(oldnp->data) & (size-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; *//* copy 'array' */ memcpy(x1a, &array, sizeof(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. */ char *Strsafe_find(key) char *key; { int 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(x) char *x; { struct symbol *sp; sp = Symbol_find(x); if( sp==0 ){ sp = (struct symbol *)malloc( 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 = Bo_FALSE; sp->destructor = 0; sp->datatype = 0; Symbol_insert(sp,sp->name); } return sp; } /* Compare two symbols for working purposes ** ** Symbols that begin with upper case letters (terminals or tokens) ** must sort before symbols that begin with lower case letters ** (non-terminals). 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(struct symbol **a, struct symbol **b){ int i1 = (**a).index + 10000000*((**a).name[0]>'Z'); int i2 = (**b).index + 10000000*((**b).name[0]>'Z'); return 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 */ 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(){ if( x2a ) return; x2a = (struct s_x2*)malloc( sizeof(struct s_x2) ); if( x2a ){ x2a->size = 128; x2a->count = 0; x2a->tbl = (x2node*)malloc( (sizeof(x2node) + sizeof(x2node*))*128 ); 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(data,key) struct symbol *data; char *key; { x2node *np; int h; int 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,size; struct s_x2 array; array.size = size = x2a->size*2; array.count = x2a->count; array.tbl = (x2node*)malloc( (sizeof(x2node) + sizeof(x2node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x2node**)&(array.tbl[size]); for(i=0; i<size; i++) array.ht[i] = 0; for(i=0; i<x2a->count; i++){ x2node *oldnp, *newnp; oldnp = &(x2a->tbl[i]); h = strhash(oldnp->key) & (size-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; *//* copy 'array' */ memcpy(x2a, &array, sizeof(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(key) char *key; { int 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(n) 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,size; if( x2a==0 ) return 0; size = x2a->count; array = (struct symbol **)malloc( sizeof(struct symbol *)*size ); if( array ){ for(i=0; i<size; i++) array[i] = x2a->tbl[i].data; } return array; } /* Compare two configurations */ int Configcmp(a,b) struct config *a; 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(a,b) 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 int statehash(a) struct config *a; { unsigned int h=0; while( a ){ h = h*571u + (unsigned int)a->rp->index*37u + (unsigned int)a->dot; a = a->bp; } return h; } /* Allocate a new state structure */ struct state *State_new() { struct state *new; new = (struct state *)malloc( sizeof(struct state) ); MemoryCheck(new); return new; } /* 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(){ if( x3a ) return; x3a = (struct s_x3*)malloc( sizeof(struct s_x3) ); if( x3a ){ x3a->size = 128; x3a->count = 0; x3a->tbl = (x3node*)malloc( (sizeof(x3node) + sizeof(x3node*))*128 ); 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(data,key) struct state *data; struct config *key; { x3node *np; int h; int 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,size; struct s_x3 array; array.size = size = x3a->size*2; array.count = x3a->count; array.tbl = (x3node*)malloc( (sizeof(x3node) + sizeof(x3node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x3node**)&(array.tbl[size]); for(i=0; i<size; i++) array.ht[i] = 0; for(i=0; i<x3a->count; i++){ x3node *oldnp, *newnp; oldnp = &(x3a->tbl[i]); h = statehash(oldnp->key) & (size-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; *//* copy 'array' */ memcpy(x3a, &array, sizeof(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(key) struct config *key; { int 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 the size of the array */ int State_count(void) { return x3a ? x3a->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 state **State_arrayof() { struct state **array; int i,size; if( x3a==0 ) return 0; size = x3a->count; array = (struct state **)malloc( sizeof(struct state *)*size ); if( array ){ for(i=0; i<size; i++) array[i] = x3a->tbl[i].data; } return array; } /* Hash a configuration */ PRIVATE int confighash(a) struct config *a; { int 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(){ if( x4a ) return; x4a = (struct s_x4*)malloc( sizeof(struct s_x4) ); if( x4a ){ x4a->size = 64; x4a->count = 0; x4a->tbl = (x4node*)malloc( (sizeof(x4node) + sizeof(x4node*))*64 ); 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(data) struct config *data; { x4node *np; int h; int ph; if( x4a==0 ) return 0; ph = confighash(data); h = ph & (x4a->size-1); np = x4a->ht[h]; while( np ){ if( Configcmp(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( x4a->count>=x4a->size ){ /* Need to make the hash table bigger */ int i,size; struct s_x4 array; array.size = size = x4a->size*2; array.count = x4a->count; array.tbl = (x4node*)malloc( (sizeof(x4node) + sizeof(x4node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x4node**)&(array.tbl[size]); for(i=0; i<size; i++) array.ht[i] = 0; for(i=0; i<x4a->count; i++){ x4node *oldnp, *newnp; oldnp = &(x4a->tbl[i]); h = confighash(oldnp->data) & (size-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; *//* copy 'array' */ memcpy(x4a, &array, sizeof(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(key) 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(np->data,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(f) 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/232955958.c
// Problem : UVA 10931 - Parity // Author : timwilliam // Compiled : 05/03/2021 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int dec_to_bit_count(int decimal){ int pwr_lv, i, temp, bit_count; pwr_lv = -1; temp = 0; bit_count = 0; // get the pwr_lv; while(temp <= decimal){ pwr_lv++; temp = (int) pow(2, pwr_lv); } // convert to binary and count the bits for(i = 0; i < pwr_lv; i++){ temp = (int) pow(2, pwr_lv - 1 - i); if(temp <= decimal){ bit_count++; decimal -= temp; printf("1"); } else{ printf("0"); } } printf(" "); return bit_count; } int main(void){ int I, sum_of_bits; while(1){ sum_of_bits = 0; scanf("%d", &I); if(I == 0) break; else if(I == 1){ printf("The parity of 1 is 1 (mod 2).\n"); continue; } printf("The parity of "); sum_of_bits = dec_to_bit_count(I); // count & print the parity printf("is %d (mod 2).\n", sum_of_bits); } }
the_stack_data/82345.c
/* PR c/65179 */ /* { dg-do compile } */ /* { dg-options "-O -Wshift-negative-value" } */ /* { dg-additional-options "-std=c++11" { target c++ } } */ enum E { A = 0 << 1, B = 1 << 1, C = -1 << 1, /* { dg-warning "left shift of negative value" } */ D = 0 >> 1, E = 1 >> 1, F = -1 >> 1 }; int left (int x) { /* Warn for LSHIFT_EXPR. */ const int z = 0; const int o = 1; const int m = -1; int r = 0; r += z << x; r += o << x; r += m << x; /* { dg-warning "left shift of negative value" } */ r += 0 << x; r += 1 << x; r += -1 << x; /* { dg-warning "left shift of negative value" } */ r += -1U << x; return r; } int right (int x) { /* Shouldn't warn for RSHIFT_EXPR. */ const int z = 0; const int o = 1; const int m = -1; int r = 0; r += z >> x; r += o >> x; r += m >> x; r += 0 >> x; r += 1 >> x; r += -1 >> x; r += -1U >> x; return r; } /* { dg-error "not an integer constant" "no constant" { target c++ } 9 } */ /* { dg-error "left operand of shift expression" "shift" { target c++ } 9 } */
the_stack_data/664731.c
/* thrd_yield( void ) This file is part of the Public Domain C Library (PDCLib). Permission is granted to use, modify, and / or redistribute at will. */ #ifndef REGTEST #include <threads.h> #ifdef __cplusplus extern "C" { #endif extern int pthread_yield( void ); #ifdef __cplusplus } #endif void thrd_yield( void ) { pthread_yield(); } #endif #ifdef TEST #include "_PDCLIB_test.h" int main( void ) { #ifndef REGTEST TESTCASE( NO_TESTDRIVER ); #endif return TEST_RESULTS; } #endif
the_stack_data/115765765.c
#include <stdio.h> #include <string.h> int main(void) { char word[20]; int i, end; printf("Enter word: "); scanf("%s", word); end = strlen(word); for (i = end; i > -1; i--) { printf("%c", word[i]); } printf("\n"); return 0; }
the_stack_data/122016347.c
/* * File: 5.12-PrintPascalTriangle.c * -------------------------------- * This Program generates Pascal triangle. */ #include <stdio.h> /* function prototypes */ int Combinations(int n, int k); int Factorial(int n); /* main program */ main() { int i, j, rows = 8; for (i = 0; i < rows; i++) { for (j = 1; j < rows - i; j++) { //print blanks printf(" "); } for (j = 0; j <= i; j++) { printf("%4d", Combinations(i, j)); } printf("\n"); } } int Combinations(int n, int k) { return (Factorial(n) / (Factorial(k) * Factorial(n - k))); } int Factorial(int n) { int i, product = 1; for (i = 1; i <= n; i++) { product *= i; } return (product); }
the_stack_data/45145.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char * argv[]) { if (argc < 3) { printf("Usage...what ever.\n"); exit(EXIT_FAILURE); } char * str = argv[1]; char * file = argv[2]; FILE * fp; if ((fp = fopen(file, "r")) == NULL) { fprintf(stderr, "I couldn't open the file \"%s\"\n", file); exit(EXIT_FAILURE); } char line[255]; int index = 1; while (fgets(line, 255, fp) != NULL) { if (strstr(line, str) != NULL) { printf("include %d\n", index); } index++; } fclose(fp); return 0; }
the_stack_data/62603.c
/** * @file malloc.c * */ /* This code is inspired by: * * Circle - A C++ bare metal environment for Raspberry Pi * Copyright (C) 2014-2016 R. Stange <[email protected]> * https://github.com/rsta2/circle/blob/master/lib/alloc.cpp */ /* Copyright (C) 2017-2018 by Arjan van Vught mailto:[email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpointer-arith" // FIXME ignored "-Wpointer-arith" #pragma GCC diagnostic ignored "-Wpedantic" // FIXME ignored "-Wpedantic" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #include <stdint.h> #include <stddef.h> #include <assert.h> #ifdef MEM_DEBUG #include <stdio.h> #endif extern int console_error(const char *); extern unsigned char heap_low; /* Defined by the linker */ extern unsigned char heap_top; /* Defined by the linker */ #define BLOCK_MAGIC 0x424C4D43 static unsigned char *next_block = &heap_low; static unsigned char *block_limit = &heap_top; struct block_header { unsigned int magic; unsigned int size ; struct block_header *next; unsigned char data[0]; } PACKED; struct block_bucket { unsigned int size; #ifdef MEM_DEBUG unsigned int count; unsigned int max_count; #endif struct block_header *free_list; }; static struct block_bucket s_block_bucket[] __attribute__((aligned(4))) = {{0x40, 0}, {0x400,0}, {0x1000,0}, {0x4000,0}, {0x40000,0}, {0x80000,0}, {0,0}}; size_t get_allocated(void *p) { if (p == 0) { return 0; } struct block_header *pBlockHeader = (struct block_header *) ((void *) p - sizeof(struct block_header)); assert(pBlockHeader->magic == BLOCK_MAGIC); if (pBlockHeader->magic != BLOCK_MAGIC) { return 0; } return pBlockHeader->size; } void *malloc(size_t size) { struct block_bucket *bucket; struct block_header *header; if (size == 0) { return NULL; } for (bucket = s_block_bucket; bucket->size > 0; bucket++) { if (size <= bucket->size) { size = bucket->size; #ifdef MEM_DEBUG if (++bucket->count > bucket->max_count) { bucket->max_count = bucket->count; } #endif break; } } if (bucket->size > 0 && (header = bucket->free_list) != 0) { assert(header->magic == BLOCK_MAGIC); bucket->free_list = header->next; } else { header = (struct block_header *) next_block; const size_t t1 = sizeof(struct block_header) + size; const size_t t2 = (t1 + (size_t) 15) & ~(size_t) 15; unsigned char *next = next_block + t2; assert(((unsigned)header & (unsigned)3) == 0); assert(((unsigned)next & (unsigned)3) == 0); if (next > block_limit) { console_error("next > block_limit\n"); return NULL; } else { next_block = next; } header->magic = BLOCK_MAGIC; header->size = (unsigned) size; } header->next = 0; #ifdef MEM_DEBUG printf("malloc: pBlockHeader = %p, size = %d\n", header, (int) size); #endif assert(((unsigned)header->data & (unsigned)3) == 0); return (void *)header->data; } void free(void *p) { struct block_bucket *bucket; if (p == 0) { return; } struct block_header *header = (struct block_header *) ((void *) p - sizeof(struct block_header)); #ifdef MEM_DEBUG printf("free: pBlockHeader = %p, pBlock = %p\n", header, p); #endif assert(header->magic == BLOCK_MAGIC); if (header->magic != BLOCK_MAGIC) { return; } for (bucket = s_block_bucket; bucket->size > 0; bucket++) { if (header->size == bucket->size) { header->next = bucket->free_list; bucket->free_list = header; #ifdef MEM_DEBUG bucket->count--; #endif break; } } } void *calloc(size_t n, size_t size) { size_t total; void *p; if ((n == 0) || (size == 0)) { return NULL; } total = n * size; p = malloc(total); if (p == NULL) { return NULL; } assert(((unsigned)p & (unsigned)3) == 0); uint32_t *dst32 = (uint32_t *) p; while (total >= 4) { *dst32++ = (uint32_t) 0; total -= 4; } uint8_t *dst8 = (uint8_t *) dst32; while (total--) { *dst8++ = (uint8_t) 0; } assert(((void *)dst8 - (void *)p) == (n * size)); return (void *) p; } void *realloc(void *ptr, size_t size) { size_t current_size; if (ptr == 0) { void *newblk = malloc(size); return newblk; } if (size == 0) { free(ptr); return NULL; } current_size = get_allocated(ptr); if (current_size >= size) { return ptr; } void *newblk = malloc(size); if (newblk != NULL) { assert(((unsigned )newblk & (unsigned )3) == 0); assert(((unsigned )ptr & (unsigned )3) == 0); const uint32_t *src32 = (const uint32_t *) ptr; uint32_t *dst32 = (uint32_t *) newblk; size_t count = size; while (count >= 4) { *dst32++ = *src32++; count -= 4; } const uint8_t *src8 = (const uint8_t *) src32; uint8_t *dst8 = (uint8_t *) dst32; while (count--) { *dst8++ = *src8++; } assert(((void *)dst8 - (void *)newblk) == size); free(ptr); } return newblk; } void mem_info(void) { #ifdef MEM_DEBUG struct block_bucket *pBucket; struct block_header *pBlockHeader; printf("s_pNextBlock = %p\n", next_block); for (pBucket = s_block_bucket; pBucket->size > 0; pBucket++) { printf("malloc(%d): %d blocks (max %d), FreeList %p\n", (unsigned) pBucket->size, (unsigned) pBucket->count, (unsigned) pBucket->max_count, pBucket->free_list); if ((pBlockHeader = pBucket->free_list) != 0) { while (1==1) { printf("\t %p:%p size %d (%p)\n", pBlockHeader, pBlockHeader->data, pBlockHeader->size, pBlockHeader->next); if (pBlockHeader->next == 0) { break; } pBlockHeader = pBlockHeader->next; } } } #endif }
the_stack_data/90763820.c
/* $Header$ */ /* * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands. * See the copyright notice in the ACK home directory, in the file "Copyright". */ #define MININT (1 << (sizeof(int) * 8 - 1)) #define MAXCHUNK (~MININT) /* Highest count we read(2). */ /* Unfortunately, MAXCHUNK is too large with some compilers. Put it in an int! */ static int maxchunk = MAXCHUNK; /* * We don't have to worry about byte order here. * Just read "cnt" bytes from file-descriptor "fd". */ int rd_bytes(fd, string, cnt) register char *string; register long cnt; { while (cnt) { register int n = cnt >= maxchunk ? maxchunk : cnt; if (read(fd, string, n) != n) rd_fatal(); string += n; cnt -= n; } }
the_stack_data/223195.c
// Use CHECK-NEXT instead of multiple CHECK-SAME to ensure we will fail if there is anything extra in the output. // RUN: not %clang_cc1 -triple armv5--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix ARM // ARM: error: unknown target CPU 'not-a-cpu' // ARM-NEXT: note: valid target CPU values are: arm8, arm810, strongarm, strongarm110, strongarm1100, strongarm1110, arm7tdmi, arm7tdmi-s, arm710t, arm720t, arm9, arm9tdmi, arm920, arm920t, arm922t, arm940t, ep9312, arm10tdmi, arm1020t, arm9e, arm946e-s, arm966e-s, arm968e-s, arm10e, arm1020e, arm1022e, arm926ej-s, arm1136j-s, arm1136jf-s, mpcore, mpcorenovfp, arm1176jz-s, arm1176jzf-s, arm1156t2-s, arm1156t2f-s, cortex-m0, cortex-m0plus, cortex-m1, sc000, cortex-a5, cortex-a7, cortex-a8, cortex-a9, cortex-a12, cortex-a15, cortex-a17, krait, cortex-r4, cortex-r4f, cortex-r5, cortex-r7, cortex-r8, cortex-r52, sc300, cortex-m3, cortex-m4, cortex-m7, cortex-m23, cortex-m33, cortex-m35p, cortex-m55, cortex-a32, cortex-a35, cortex-a53, cortex-a55, cortex-a57, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, cortex-a78, cortex-a78c, cortex-a710, cortex-x1, cortex-x1c, neoverse-n1, neoverse-n2, neoverse-v1, cyclone, exynos-m3, exynos-m4, exynos-m5, kryo, iwmmxt, xscale, swift{{$}} // RUN: not %clang_cc1 -triple arm64--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix AARCH64 // AARCH64: error: unknown target CPU 'not-a-cpu' // AARCH64-NEXT: note: valid target CPU values are: cortex-a34, cortex-a35, cortex-a53, cortex-a55, cortex-a510, cortex-a57, cortex-a65, cortex-a65ae, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, cortex-a78, cortex-a78c, cortex-a710, cortex-r82, cortex-x1, cortex-x1c, cortex-x2, neoverse-e1, neoverse-n1, neoverse-n2, neoverse-512tvb, neoverse-v1, cyclone, apple-a7, apple-a8, apple-a9, apple-a10, apple-a11, apple-a12, apple-a13, apple-a14, apple-m1, apple-s4, apple-s5, exynos-m3, exynos-m4, exynos-m5, falkor, saphira, kryo, thunderx2t99, thunderx3t110, thunderx, thunderxt88, thunderxt81, thunderxt83, tsv110, a64fx, carmel{{$}} // RUN: not %clang_cc1 -triple arm64--- -tune-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix TUNE_AARCH64 // TUNE_AARCH64: error: unknown target CPU 'not-a-cpu' // TUNE_AARCH64-NEXT: note: valid target CPU values are: cortex-a34, cortex-a35, cortex-a53, cortex-a55, cortex-a510, cortex-a57, cortex-a65, cortex-a65ae, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, cortex-a78, cortex-a78c, cortex-a710, cortex-r82, cortex-x1, cortex-x1c, cortex-x2, neoverse-e1, neoverse-n1, neoverse-n2, neoverse-512tvb, neoverse-v1, cyclone, apple-a7, apple-a8, apple-a9, apple-a10, apple-a11, apple-a12, apple-a13, apple-a14, apple-m1, apple-s4, apple-s5, exynos-m3, exynos-m4, exynos-m5, falkor, saphira, kryo, thunderx2t99, thunderx3t110, thunderx, thunderxt88, thunderxt81, thunderxt83, tsv110, a64fx, carmel{{$}} // RUN: not %clang_cc1 -triple i386--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix X86 // X86: error: unknown target CPU 'not-a-cpu' // X86-NEXT: note: valid target CPU values are: i386, i486, winchip-c6, winchip2, c3, i586, pentium, pentium-mmx, pentiumpro, i686, pentium2, pentium3, pentium3m, pentium-m, c3-2, yonah, pentium4, pentium4m, prescott, nocona, core2, penryn, bonnell, atom, silvermont, slm, goldmont, goldmont-plus, tremont, nehalem, corei7, westmere, sandybridge, corei7-avx, ivybridge, core-avx-i, haswell, core-avx2, broadwell, skylake, skylake-avx512, skx, cascadelake, cooperlake, cannonlake, icelake-client, rocketlake, icelake-server, tigerlake, sapphirerapids, alderlake, knl, knm, lakemont, k6, k6-2, k6-3, athlon, athlon-tbird, athlon-xp, athlon-mp, athlon-4, k8, athlon64, athlon-fx, opteron, k8-sse3, athlon64-sse3, opteron-sse3, amdfam10, barcelona, btver1, btver2, bdver1, bdver2, bdver3, bdver4, znver1, znver2, znver3, x86-64, x86-64-v2, x86-64-v3, x86-64-v4, geode{{$}} // RUN: not %clang_cc1 -triple x86_64--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix X86_64 // X86_64: error: unknown target CPU 'not-a-cpu' // X86_64-NEXT: note: valid target CPU values are: nocona, core2, penryn, bonnell, atom, silvermont, slm, goldmont, goldmont-plus, tremont, nehalem, corei7, westmere, sandybridge, corei7-avx, ivybridge, core-avx-i, haswell, core-avx2, broadwell, skylake, skylake-avx512, skx, cascadelake, cooperlake, cannonlake, icelake-client, rocketlake, icelake-server, tigerlake, sapphirerapids, alderlake, knl, knm, k8, athlon64, athlon-fx, opteron, k8-sse3, athlon64-sse3, opteron-sse3, amdfam10, barcelona, btver1, btver2, bdver1, bdver2, bdver3, bdver4, znver1, znver2, znver3, x86-64, x86-64-v2, x86-64-v3, x86-64-v4{{$}} // RUN: not %clang_cc1 -triple i386--- -tune-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix TUNE_X86 // TUNE_X86: error: unknown target CPU 'not-a-cpu' // TUNE_X86-NEXT: note: valid target CPU values are: i386, i486, winchip-c6, winchip2, c3, i586, pentium, pentium-mmx, pentiumpro, i686, pentium2, pentium3, pentium3m, pentium-m, c3-2, yonah, pentium4, pentium4m, prescott, nocona, core2, penryn, bonnell, atom, silvermont, slm, goldmont, goldmont-plus, tremont, nehalem, corei7, westmere, sandybridge, corei7-avx, ivybridge, core-avx-i, haswell, core-avx2, broadwell, skylake, skylake-avx512, skx, cascadelake, cooperlake, cannonlake, icelake-client, rocketlake, icelake-server, tigerlake, sapphirerapids, alderlake, knl, knm, lakemont, k6, k6-2, k6-3, athlon, athlon-tbird, athlon-xp, athlon-mp, athlon-4, k8, athlon64, athlon-fx, opteron, k8-sse3, athlon64-sse3, opteron-sse3, amdfam10, barcelona, btver1, btver2, bdver1, bdver2, bdver3, bdver4, znver1, znver2, znver3, x86-64, geode{{$}} // RUN: not %clang_cc1 -triple x86_64--- -tune-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix TUNE_X86_64 // TUNE_X86_64: error: unknown target CPU 'not-a-cpu' // TUNE_X86_64-NEXT: note: valid target CPU values are: i386, i486, winchip-c6, winchip2, c3, i586, pentium, pentium-mmx, pentiumpro, i686, pentium2, pentium3, pentium3m, pentium-m, c3-2, yonah, pentium4, pentium4m, prescott, nocona, core2, penryn, bonnell, atom, silvermont, slm, goldmont, goldmont-plus, tremont, nehalem, corei7, westmere, sandybridge, corei7-avx, ivybridge, core-avx-i, haswell, core-avx2, broadwell, skylake, skylake-avx512, skx, cascadelake, cooperlake, cannonlake, icelake-client, rocketlake, icelake-server, tigerlake, sapphirerapids, alderlake, knl, knm, lakemont, k6, k6-2, k6-3, athlon, athlon-tbird, athlon-xp, athlon-mp, athlon-4, k8, athlon64, athlon-fx, opteron, k8-sse3, athlon64-sse3, opteron-sse3, amdfam10, barcelona, btver1, btver2, bdver1, bdver2, bdver3, bdver4, znver1, znver2, znver3, x86-64, geode{{$}} // RUN: not %clang_cc1 -triple nvptx--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix NVPTX // NVPTX: error: unknown target CPU 'not-a-cpu' // NVPTX-NEXT: note: valid target CPU values are: sm_20, sm_21, sm_30, sm_32, sm_35, sm_37, sm_50, sm_52, sm_53, sm_60, sm_61, sm_62, sm_70, sm_72, sm_75, sm_80, sm_86, gfx600, gfx601, gfx602, gfx700, gfx701, gfx702, gfx703, gfx704, gfx705, gfx801, gfx802, gfx803, gfx805, gfx810, gfx900, gfx902, gfx904, gfx906, gfx908, gfx909, gfx90a, gfx90c, gfx1010, gfx1011, gfx1012, gfx1013, gfx1030, gfx1031, gfx1032, gfx1033, gfx1034, gfx1035{{$}} // RUN: not %clang_cc1 -triple r600--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix R600 // R600: error: unknown target CPU 'not-a-cpu' // R600-NEXT: note: valid target CPU values are: r600, rv630, rv635, r630, rs780, rs880, rv610, rv620, rv670, rv710, rv730, rv740, rv770, cedar, palm, cypress, hemlock, juniper, redwood, sumo, sumo2, barts, caicos, aruba, cayman, turks{{$}} // RUN: not %clang_cc1 -triple amdgcn--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix AMDGCN // AMDGCN: error: unknown target CPU 'not-a-cpu' // AMDGCN-NEXT: note: valid target CPU values are: gfx600, tahiti, gfx601, pitcairn, verde, gfx602, hainan, oland, gfx700, kaveri, gfx701, hawaii, gfx702, gfx703, kabini, mullins, gfx704, bonaire, gfx705, gfx801, carrizo, gfx802, iceland, tonga, gfx803, fiji, polaris10, polaris11, gfx805, tongapro, gfx810, stoney, gfx900, gfx902, gfx904, gfx906, gfx908, gfx909, gfx90a, gfx90c, gfx1010, gfx1011, gfx1012, gfx1013, gfx1030, gfx1031, gfx1032, gfx1033, gfx1034, gfx1035{{$}} // RUN: not %clang_cc1 -triple wasm64--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix WEBASM // WEBASM: error: unknown target CPU 'not-a-cpu' // WEBASM-NEXT: note: valid target CPU values are: mvp, bleeding-edge, generic{{$}} // RUN: not %clang_cc1 -triple systemz--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix SYSTEMZ // SYSTEMZ: error: unknown target CPU 'not-a-cpu' // SYSTEMZ-NEXT: note: valid target CPU values are: arch8, z10, arch9, z196, arch10, zEC12, arch11, z13, arch12, z14, arch13, z15, arch14{{$}} // RUN: not %clang_cc1 -triple sparc--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix SPARC // SPARC: error: unknown target CPU 'not-a-cpu' // SPARC-NEXT: note: valid target CPU values are: v8, supersparc, sparclite, f934, hypersparc, sparclite86x, sparclet, tsc701, v9, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, ma2100, ma2150, ma2155, ma2450, ma2455, ma2x5x, ma2080, ma2085, ma2480, ma2485, ma2x8x, myriad2, myriad2.1, myriad2.2, myriad2.3, leon2, at697e, at697f, leon3, ut699, gr712rc, leon4, gr740{{$}} // RUN: not %clang_cc1 -triple sparcv9--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix SPARCV9 // SPARCV9: error: unknown target CPU 'not-a-cpu' // SPARCV9-NEXT: note: valid target CPU values are: v9, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4{{$}} // RUN: not %clang_cc1 -triple powerpc--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix PPC // PPC: error: unknown target CPU 'not-a-cpu' // PPC-NEXT: note: valid target CPU values are: generic, 440, 450, 601, 602, 603, 603e, 603ev, 604, 604e, 620, 630, g3, 7400, g4, 7450, g4+, 750, 8548, 970, g5, a2, e500, e500mc, e5500, power3, pwr3, power4, pwr4, power5, pwr5, power5x, pwr5x, power6, pwr6, power6x, pwr6x, power7, pwr7, power8, pwr8, power9, pwr9, power10, pwr10, powerpc, ppc, ppc32, powerpc64, ppc64, powerpc64le, ppc64le, future{{$}} // RUN: not %clang_cc1 -triple mips--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix MIPS // MIPS: error: unknown target CPU 'not-a-cpu' // MIPS-NEXT: note: valid target CPU values are: mips1, mips2, mips3, mips4, mips5, mips32, mips32r2, mips32r3, mips32r5, mips32r6, mips64, mips64r2, mips64r3, mips64r5, mips64r6, octeon, octeon+, p5600{{$}} // RUN: not %clang_cc1 -triple lanai--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix LANAI // LANAI: error: unknown target CPU 'not-a-cpu' // LANAI-NEXT: note: valid target CPU values are: v11{{$}} // RUN: not %clang_cc1 -triple hexagon--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix HEXAGON // HEXAGON: error: unknown target CPU 'not-a-cpu' // HEXAGON-NEXT: note: valid target CPU values are: hexagonv5, hexagonv55, hexagonv60, hexagonv62, hexagonv65, hexagonv66, hexagonv67, hexagonv67t, hexagonv68, hexagonv69{{$}} // RUN: not %clang_cc1 -triple bpf--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix BPF // BPF: error: unknown target CPU 'not-a-cpu' // BPF-NEXT: note: valid target CPU values are: generic, v1, v2, v3, probe{{$}} // RUN: not %clang_cc1 -triple avr--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix AVR // AVR: error: unknown target CPU 'not-a-cpu' // AVR-NEXT: note: valid target CPU values are: avr1, avr2, avr25, avr3, avr31, avr35, avr4, avr5, avr51, avr6, avrxmega1, avrxmega2, avrxmega3, avrxmega4, avrxmega5, avrxmega6, avrxmega7, avrtiny, at90s1200, attiny11, attiny12, attiny15, attiny28, at90s2313, at90s2323, at90s2333, at90s2343, attiny22, attiny26, at86rf401, at90s4414, at90s4433, at90s4434, at90s8515, at90c8534, at90s8535, ata5272, attiny13, attiny13a, attiny2313, attiny2313a, attiny24, attiny24a, attiny4313, attiny44, attiny44a, attiny84, attiny84a, attiny25, attiny45, attiny85, attiny261, attiny261a, attiny441, attiny461, attiny461a, attiny841, attiny861, attiny861a, attiny87, attiny43u, attiny48, attiny88, attiny828, at43usb355, at76c711, atmega103, at43usb320, attiny167, at90usb82, at90usb162, ata5505, atmega8u2, atmega16u2, atmega32u2, attiny1634, atmega8, ata6289, atmega8a, ata6285, ata6286, atmega48, atmega48a, atmega48pa, atmega48pb, atmega48p, atmega88, atmega88a, atmega88p, atmega88pa, atmega88pb, atmega8515, atmega8535, atmega8hva, at90pwm1, at90pwm2, at90pwm2b, at90pwm3, at90pwm3b, at90pwm81, ata5790, ata5795, atmega16, atmega16a, atmega161, atmega162, atmega163, atmega164a, atmega164p, atmega164pa, atmega165, atmega165a, atmega165p, atmega165pa, atmega168, atmega168a, atmega168p, atmega168pa, atmega168pb, atmega169, atmega169a, atmega169p, atmega169pa, atmega32, atmega32a, atmega323, atmega324a, atmega324p, atmega324pa, atmega324pb, atmega325, atmega325a, atmega325p, atmega325pa, atmega3250, atmega3250a, atmega3250p, atmega3250pa, atmega328, atmega328p, atmega328pb, atmega329, atmega329a, atmega329p, atmega329pa, atmega3290, atmega3290a, atmega3290p, atmega3290pa, atmega406, atmega64, atmega64a, atmega640, atmega644, atmega644a, atmega644p, atmega644pa, atmega645, atmega645a, atmega645p, atmega649, atmega649a, atmega649p, atmega6450, atmega6450a, atmega6450p, atmega6490, atmega6490a, atmega6490p, atmega64rfr2, atmega644rfr2, atmega16hva, atmega16hva2, atmega16hvb, atmega16hvbrevb, atmega32hvb, atmega32hvbrevb, atmega64hve, at90can32, at90can64, at90pwm161, at90pwm216, at90pwm316, atmega32c1, atmega64c1, atmega16m1, atmega32m1, atmega64m1, atmega16u4, atmega32u4, atmega32u6, at90usb646, at90usb647, at90scr100, at94k, m3000, atmega128, atmega128a, atmega1280, atmega1281, atmega1284, atmega1284p, atmega128rfa1, atmega128rfr2, atmega1284rfr2, at90can128, at90usb1286, at90usb1287, atmega2560, atmega2561, atmega256rfr2, atmega2564rfr2, atxmega16a4, atxmega16a4u, atxmega16c4, atxmega16d4, atxmega32a4, atxmega32a4u, atxmega32c4, atxmega32d4, atxmega32e5, atxmega16e5, atxmega8e5, atxmega32x1, atxmega64a3, atxmega64a3u, atxmega64a4u, atxmega64b1, atxmega64b3, atxmega64c3, atxmega64d3, atxmega64d4, atxmega64a1, atxmega64a1u, atxmega128a3, atxmega128a3u, atxmega128b1, atxmega128b3, atxmega128c3, atxmega128d3, atxmega128d4, atxmega192a3, atxmega192a3u, atxmega192c3, atxmega192d3, atxmega256a3, atxmega256a3u, atxmega256a3b, atxmega256a3bu, atxmega256c3, atxmega256d3, atxmega384c3, atxmega384d3, atxmega128a1, atxmega128a1u, atxmega128a4u, attiny4, attiny5, attiny9, attiny10, attiny20, attiny40, attiny102, attiny104, attiny202, attiny402, attiny204, attiny404, attiny804, attiny1604, attiny406, attiny806, attiny1606, attiny807, attiny1607, attiny212, attiny412, attiny214, attiny414, attiny814, attiny1614, attiny416, attiny816, attiny1616, attiny3216, attiny417, attiny817, attiny1617, attiny3217{{$}} // RUN: not %clang_cc1 -triple riscv32 -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix RISCV32 // RISCV32: error: unknown target CPU 'not-a-cpu' // RISCV32-NEXT: note: valid target CPU values are: generic-rv32, rocket-rv32, sifive-7-rv32, sifive-e20, sifive-e21, sifive-e24, sifive-e31, sifive-e34, sifive-e76{{$}} // RUN: not %clang_cc1 -triple riscv64 -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix RISCV64 // RISCV64: error: unknown target CPU 'not-a-cpu' // RISCV64-NEXT: note: valid target CPU values are: generic-rv64, rocket-rv64, sifive-7-rv64, sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, sifive-u74{{$}} // RUN: not %clang_cc1 -triple riscv32 -tune-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix TUNE-RISCV32 // TUNE-RISCV32: error: unknown target CPU 'not-a-cpu' // TUNE-RISCV32-NEXT: note: valid target CPU values are: generic-rv32, rocket-rv32, sifive-7-rv32, sifive-e20, sifive-e21, sifive-e24, sifive-e31, sifive-e34, sifive-e76, generic, rocket, sifive-7-series{{$}} // RUN: not %clang_cc1 -triple riscv64 -tune-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix TUNE-RISCV64 // TUNE-RISCV64: error: unknown target CPU 'not-a-cpu' // TUNE-RISCV64-NEXT: note: valid target CPU values are: generic-rv64, rocket-rv64, sifive-7-rv64, sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, sifive-u74, generic, rocket, sifive-7-series{{$}}
the_stack_data/211081940.c
a; b() { char c; int d, e; d = 0; for (; d < 1000; d++) f(); if (a) g(); d = 0; for (; 0 < e;) ; h(a); for (; d < 54; d++) i(); d = 0; for (; d < 8; d++) i(c); }
the_stack_data/145452140.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; int main(int argc , char *argv[] ) { unsigned long input[1] ; unsigned long output[1] ; int randomFuns_i5 ; unsigned long randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 4242424242UL) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%lu\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void megaInit(void) { { } } void RandomFunc(unsigned long input[1] , unsigned long output[1] ) { unsigned long state[1] ; unsigned long local1 ; char copy11 ; unsigned short copy13 ; unsigned int copy14 ; { state[0UL] = (input[0UL] + 51238316UL) + 274866410UL; local1 = 0UL; while (local1 < 0UL) { if (state[0UL] < local1) { if (state[0UL] == local1) { copy11 = *((char *)(& state[local1]) + 7); *((char *)(& state[local1]) + 7) = *((char *)(& state[local1]) + 3); *((char *)(& state[local1]) + 3) = copy11; copy11 = *((char *)(& state[local1]) + 6); *((char *)(& state[local1]) + 6) = *((char *)(& state[local1]) + 5); *((char *)(& state[local1]) + 5) = copy11; state[0UL] = state[local1] - state[0UL]; } else { copy13 = *((unsigned short *)(& state[local1]) + 2); *((unsigned short *)(& state[local1]) + 2) = *((unsigned short *)(& state[local1]) + 1); *((unsigned short *)(& state[local1]) + 1) = copy13; copy13 = *((unsigned short *)(& state[local1]) + 1); *((unsigned short *)(& state[local1]) + 1) = *((unsigned short *)(& state[local1]) + 0); *((unsigned short *)(& state[local1]) + 0) = copy13; } } else { copy14 = *((unsigned int *)(& state[local1]) + 0); *((unsigned int *)(& state[local1]) + 0) = *((unsigned int *)(& state[local1]) + 1); *((unsigned int *)(& state[local1]) + 1) = copy14; } local1 += 2UL; } output[0UL] = (state[0UL] + 344325601UL) - 259534803UL; } }
the_stack_data/234517032.c
/* * Copyright 2018 Thomas Bocek * * 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. * */ /* * Why is this tool useful? * ======================== * * Since I type with the "Dvorak" keyboard layout, the shortcuts such * as ctrl-c, ctrl-x, or ctrl-v are not comfortable anymore and one of them * require two hands to press. * * Furthermore, applications such as Intellij and Eclipse have their * shortcuts, which I'm used to. So for these shortcuts I prefer "Querty". * Since there is no way to configure this, I had to intercept the * keys and remap the keys from "Dvorak" to "Querty" once CTRL, ALT, * WIN or any of those combinations are pressed. * * With X.org I was reling on the wonderful tool from Kenton Varda, * which I modified a bit, to make it work when Numlock is active. Other * than that, it worked as expected. * * And then came Wayland. XGrabKey() works partially with some application * but not with others (e.g., gedit is not working). Since XGrabKey() is * an X.org function with some support in Wayland, I was looking for a more * stable solution. After a quick look to the repo https://github.com/kentonv/dvorak-qwerty * I saw that Kenton added a systemtap script to implement the mapping. This * scared me a bit to follow that path, so I implemented an other solution * based on /dev/uinput. The idea is to read /dev/input, grab keys with * EVIOCGRAB, create a virtual device that can emit the keys and pass * the keys from /dev/input to /dev/uinput. If CTRL/ALT/WIN is * pressed it will map the keys back to "Qwerty". * * Intallation * =========== * * make dvorak * //make sure your user belongs to the group "input" -> ls -la /dev/input * //this also applies for /dev/uinput -> https://github.com/tuomasjjrasanen/python-uinput/blob/master/udev-rules/40-uinput.rules * //start it in startup applications * * Related Links * ============= * I used the following sites for inspiration: * https://www.kernel.org/doc/html/v4.12/input/uinput.html * https://www.linuxquestions.org/questions/programming-9/uinput-any-complete-example-4175524044/ * https://stackoverflow.com/questions/20943322/accessing-keys-from-linux-input-device * https://gist.github.com/toinsson/7e9fdd3c908b3c3d3cd635321d19d44d * */ #define _GNU_SOURCE #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <linux/input.h> #include <linux/uinput.h> #include <string.h> #include <stdio.h> #include <X11/XKBlib.h> static const char *const evval[3] = { "RELEASED", "PRESSED", "REPEATED" }; static int emit(int fd, int type, int code, int val) { struct input_event ie; ie.type = type; ie.code = code; ie.value = val; /* timestamp values below are ignored */ ie.time.tv_sec = 0; ie.time.tv_usec = 0; return write(fd, &ie, sizeof(ie)); } //from: https://github.com/kentonv/dvorak-qwerty/tree/master/unix static int modifier_bit(int key) { switch (key) { #ifdef CAPSLOCK case 58: #else case 20: #endif return 1; // l-ctrl case 97: return 2; // r-ctrl case 56: return 4; // l-alt case 125: return 8; // win #ifdef R_ALT case 100: return 16; #endif } return 0; } //from: https://github.com/kentonv/dvorak-qwerty/tree/master/unix static int qwerty2dvorak(int key) { switch (key) { case 12: return 40; case 13: return 27; case 16: return 45; case 17: return 51; case 18: return 32; case 19: return 24; case 20: return 37; case 21: return 20; case 22: return 33; case 23: return 34; case 24: return 31; case 25: return 19; case 26: return 12; case 27: return 13; case 30: return 30; case 31: return 39; case 32: return 35; case 33: return 21; case 34: return 22; case 35: return 36; case 36: return 46; case 37: return 47; case 38: return 25; case 39: return 44; case 40: return 16; case 44: return 53; case 45: return 48; case 46: return 23; case 47: return 52; case 48: return 49; case 49: return 38; case 50: return 50; case 51: return 17; case 52: return 18; case 53: return 26; } return key; } static int isDvorakLayout() { //get keyboard layout, heavily inspired by: //https://github.com/luminousmen/xkblang/blob/master/src/xkblang.c Display *d; //check keyboard layout preparation if (!(d = XOpenDisplay(NULL))) { fprintf(stderr, "cannot open display\n"); return EXIT_FAILURE; } XkbDescPtr keyboard = XkbAllocKeyboard(); if (!keyboard) { fprintf(stderr, "Error creating keyboard description"); return EXIT_FAILURE; } if (XkbGetNames(d, XkbGroupNamesMask, keyboard) != Success ) { fprintf(stderr, "Error obtaining symbolic names"); return EXIT_FAILURE; } XkbStateRec state; if( XkbGetState(d, XkbUseCoreKbd, &state) != Success ) { fprintf(stderr, "Error getting keyboard state"); return EXIT_FAILURE; } char *name = XGetAtomName(d, keyboard->names->groups[state.group]); printf( "%s\n", name); XFree(name); XkbFreeNames(keyboard, XkbGroupNamesMask, True); //free up: https://gist.github.com/fikovnik/ef428e82a26774280c4fdf8f96ce8eeb XCloseDisplay(d); return 1; } int main(int argc, char *argv[]) { setuid(0); if (argc < 2) { fprintf(stderr, "error: specify input device, e.g., found in " "/dev/input/by-id/.\n"); return EXIT_FAILURE; } struct input_event ev; ssize_t n; int fdi, fdo, i, mod_state, mod_current, array_counter, code, name_ret; struct uinput_user_dev uidev; const char MAX_LENGTH = 32; int array[MAX_LENGTH]; char keyboard_name[256] = "Unknown"; //the name and ids of the virtual keyboard, we need to define this now, as we need to ignore this to prevent //mapping the virtual keyboard memset(&uidev, 0, sizeof(uidev)); snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "Virtual Dvorak Keyboard"); uidev.id.bustype = BUS_USB; uidev.id.vendor = 0x1234; uidev.id.product = 0x5678; uidev.id.version = 0; //init states mod_state = 0; array_counter = 0; for (i = 0; i < MAX_LENGTH; i++) { array[i] = 0; } //get first input fdi = open(argv[1], O_RDONLY); if (fdi == -1) { fprintf(stderr, "Cannot open any of the devices: %s.\n", strerror(errno)); return EXIT_FAILURE; } // name_ret = ioctl(fdi, EVIOCGNAME(sizeof(keyboard_name) - 1), keyboard_name); if (name_ret < 0) { fprintf(stderr, "Cannot get device name: %s.\n", strerror(errno)); return EXIT_FAILURE; } if (strcasestr(keyboard_name, uidev.name) != NULL) { fprintf(stderr, "Cannot get map the virtual device: %s.\n", keyboard_name); return EXIT_FAILURE; } // match names, reuse name_ret name_ret = -1; for (i = 2; i < argc; i++) { if (strcasestr(keyboard_name, argv[i]) != NULL) { printf("found input: [%s]\n", keyboard_name); name_ret = 0; break; } } if (name_ret < 0) { fprintf(stderr, "Not a matching device: [%s]\n", keyboard_name); return EXIT_FAILURE; } fdo = open("/dev/uinput", O_WRONLY | O_NONBLOCK); if (fdo == -1) { fprintf(stderr, "Cannot open /dev/uinput: %s.\n", strerror(errno)); return EXIT_FAILURE; } //grab the key, from the input //https://unix.stackexchange.com/questions/126974/where-do-i-find-ioctl-eviocgrab-documented/126996 //fix is implemented, will make it to ubuntu sometimes in 1.9.4 //https://bugs.freedesktop.org/show_bug.cgi?id=101796 //quick workaround, sleep for 200ms... usleep(200 * 1000); if (ioctl(fdi, EVIOCGRAB, 1) == -1) { fprintf(stderr, "Cannot grab key: %s.\n", strerror(errno)); return EXIT_FAILURE; } // Keyboard if (ioctl(fdo, UI_SET_EVBIT, EV_KEY) == -1) { fprintf(stderr, "Cannot set ev bits, key: %s.\n", strerror(errno)); return EXIT_FAILURE; } if (ioctl(fdo, UI_SET_EVBIT, EV_SYN) == -1) { fprintf(stderr, "Cannot set ev bits, syn: %s.\n", strerror(errno)); return EXIT_FAILURE; } if (ioctl(fdo, UI_SET_EVBIT, EV_MSC) == -1) { fprintf(stderr, "Cannot set ev bits, msc: %s.\n", strerror(errno)); return EXIT_FAILURE; } // All keys for (i = 0; i < KEY_MAX; i++) { if (ioctl(fdo, UI_SET_KEYBIT, i) == -1) { fprintf(stderr, "Cannot set ev bits: %s.\n", strerror(errno)); return EXIT_FAILURE; } } if (write(fdo, &uidev, sizeof(uidev)) == -1) { fprintf(stderr, "Cannot set device data: %s.\n", strerror(errno)); return EXIT_FAILURE; } if (ioctl(fdo, UI_DEV_CREATE) == -1) { fprintf(stderr, "Cannot create device: %s.\n", strerror(errno)); return EXIT_FAILURE; } //TODO: clear array while (1) { n = read(fdi, &ev, sizeof ev); if (n == (ssize_t) - 1) { if (errno == EINTR) { continue; } else { break; } } else if (n != sizeof ev) { errno = EIO; break; } if (ev.type == EV_KEY && ev.value >= 0 && ev.value <= 2) { //printf("%s 0x%04x (%d), arr:%d\n", evval[ev.value], (int)ev.code, (int)ev.code, array_counter); //map the keys //isDvorakLayout(); mod_current = modifier_bit(ev.code); if (mod_current > 0) { if (ev.value == 1) { //pressed mod_state |= mod_current; } else if (ev.value == 0) {//released mod_state &= ~mod_current; } } if (ev.code != qwerty2dvorak(ev.code) && (mod_state > 0 || array_counter > 0)) { code = ev.code; //printf("dvorak %d, %d\n", array_counter, mod_state); if (ev.value == 1) { //pressed if (array_counter == MAX_LENGTH) { printf("warning, too many keys pressed: %d. %s 0x%04x (%d), arr:%d\n", MAX_LENGTH, evval[ev.value], (int) ev.code, (int) ev.code, array_counter); //skip dvorak mapping } else { array[array_counter] = ev.code + 1; //0 means not mapped array_counter++; code = qwerty2dvorak(ev.code); // dvorak mapping } } else if (ev.value == 0) { //released //now we need to check if the code is in the array //if it is, then the pressed key was in dvorak mode and //we need to remove it from the array. The ctrl or alt //key does not need to be pressed, when a key is released. //A previous implementation only had a counter, which resulted //occasionally in stuck keys. for (i = 0; i < array_counter; i++) { if (array[i] == ev.code + 1) { //found it, map it! array[i] = 0; code = qwerty2dvorak(ev.code); // dvorak mapping } } //cleanup array counter for (i = array_counter - 1; i >= 0; i--) { if (array[i] == 0) { array_counter--; } else { break; } } } emit(fdo, ev.type, code, ev.value); } else { //printf("non dvorak %d\n", array_counter); emit(fdo, ev.type, ev.code, ev.value); } } else { //printf("Not key: %d 0x%04x (%d)\n", ev.value, (int)ev.code, (int)ev.code); emit(fdo, ev.type, ev.code, ev.value); } } fflush(stdout); fprintf(stderr, "%s.\n", strerror(errno)); return EXIT_FAILURE; }
the_stack_data/190769431.c
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }; int main() { struct Node *element,*FirstHead, *SecondHead, *Prev; int N,i; printf("Enter Size of List 1 :"); scanf("%d",&N); FirstHead = NULL; for(i=0;i<N;i++) { element = (struct Node*) malloc(sizeof(struct Node)); scanf("%d",&element->data); element->next = NULL; if(FirstHead == NULL) { FirstHead = element; } else { Prev->next = element; } Prev = element; } printf("Enter Size of List 2 :"); scanf("%d",&N); SecondHead = NULL; for(i=0;i<N;i++) { element = (struct Node*) malloc(sizeof(struct Node)); scanf("%d",&element->data); element->next = NULL; if(SecondHead == NULL) { SecondHead = element; } else { Prev->next = element; } Prev = element; } //1 2 5 2 //1 1 5 //1 2 5 2 1 1 5 Merge(FirstHead, SecondHead); printf("After Merging :\n"); PrintList(FirstHead); printf("\n"); //PrintList(SecondHead); printf("\n"); sort(FirstHead); printf("\n"); printf("Final Result :\n"); PrintList(FirstHead); return 0; } void Merge(struct Node *L1, struct Node *L2) { while(L1->next != NULL) { L1 = L1->next; } L1->next = L2; } void sort(struct Node *Head) { struct Node *temp; struct Node *dummy; while(Head != NULL) { dummy = Head->next; while(dummy != NULL) { if(Head->data > dummy->data) { temp = Head->data; Head->data = dummy->data; dummy->data = temp; } dummy = dummy->next; } Head = Head->next; } } void PrintList(struct Node *Head) { while(Head != NULL) { printf("%d ",Head->data); Head = Head->next; } }
the_stack_data/489072.c
#include <fmtmsg.h> int fmtmsg(long classification, const char * label, int severity, const char * text, const char * action, const char * tag) { return 0; } /* XOPEN(400) */
the_stack_data/560541.c
#include <stdio.h> #include <stdlib.h> #include <limits.h> // Структура для хранения узла дерева. // Необходимо хранить ссылки на потомков, предка и некоторое значение typedef struct node { int value; struct node *parent; struct node *left; struct node *right; } node; // Структура для хранения дерева. // Хранит ссылку на корень дерева и количество элементов в дереве typedef struct tree { int count; node *root; } tree; void init(tree* t){ t->root = NULL; t->count = 0; } int insert(tree* t, int value){ if (t->root == NULL) { node *temp_root = (node*)malloc(sizeof(node)); t->count++; t->root = temp_root; temp_root->left = NULL; temp_root->right = NULL; temp_root->value = value; temp_root->parent = NULL; return 0; } else { node *temp = t->root; for (int i = 0; i < t->count; i++) { if (value == temp->value) { return 1; } else if (value < temp->value && temp->left != NULL) { temp = temp->left; } else if (value > temp->value && temp->right != NULL) { temp = temp->right; } else { break; } } node *new_node = (node*)malloc(sizeof(node)); t->count++; new_node->left = NULL; new_node->right = NULL; new_node->value = value; new_node->parent = temp; if (value < temp->value) { temp->left = new_node; return 0; } else { temp->right = new_node; return 0; } return 2; } } void print_tree(tree * t) { node * rights[SHRT_MAX]; int r_i = 0; node * write[SHRT_MAX]; int w_i = 0; node * n = t->root; // раз рекурсию нельзя... while (w_i < t->count){ // Проходим пока все не пройдем while (n != NULL){ // Пока звено есть w_i++; // Увеличиваем счетчик на вывод if (n->right != NULL){ // Если правое звено есть r_i++; rights[r_i] = n->right; // Заносим его в а } write[w_i] = n; // Заносим звено на вывод n = n->left; // Идем влево } n = rights[r_i]; // Идем вправо r_i -= 1; // и назад } for (int i = 1; i <= w_i; i++) printf("%d ", write[i]->value); } int main() { tree t; init(&t); for (int i = 0; i < 7; i++) { int a; scanf("%d", &a); insert(&t, a); } print_tree(&t); };
the_stack_data/1050041.c
/* * NumberOfInversions.c * * Created on: Apr 15, 2019 * Author: Abdelrahman */ #include <stdio.h> #include <stdlib.h> typedef unsigned int uint; int mergeSort(int *ptr, uint start, uint end); int merge(int *ptr, uint start, uint middle, uint end); int main(){ uint n = 0; int numInversions = 0; int *ptr = NULL; fflush(stdin); scanf("%u",&n); ptr = (int *) malloc(n * sizeof(int)); for(uint i = 0; i < n; i++){ fflush(stdin); scanf("%d", (ptr + i)); } numInversions = mergeSort(ptr, 0, n-1); printf("\n%d",numInversions); fflush(stdout); return 0; } int mergeSort(int *ptr, uint start, uint end){ if(start < end){ int numInversions = 0; uint middle = start + (end - start)/2; numInversions = mergeSort(ptr, start, middle); numInversions += mergeSort(ptr, middle+1, end); numInversions += merge(ptr, start, middle, end); return numInversions; } return 0; } int merge(int *ptr, uint start, uint middle, uint end){ uint i, j, k; int numInversions = 0; int *ptrLeft = 0; int *ptrRight = 0; uint leftSize = middle - start + 1; uint rightSize = end - middle; /*Create Temporary Arrays*/ ptrLeft = (int *) malloc(leftSize * sizeof(int)); ptrRight = (int *) malloc(rightSize * sizeof(int)); /*Copy Data to Temporary Arrays*/ for(i = 0; i < leftSize; i++){ *(ptrLeft+i) = *(ptr+start+i); } for(j = 0; j < rightSize; j++){ *(ptrRight+j) = *(ptr+middle+j+1); } /*Merge the temporary arrays*/ i = 0; j = 0; k = start; while((i < leftSize) && (j < rightSize)){ if(*(ptrLeft+i) <= *(ptrRight+j)){ *(ptr+k) = *(ptrLeft+i); /*Pick the left element if it's smaller*/ i++; /*Move the pointer to the next element in the left array*/ } else{ *(ptr+k) = *(ptrRight+j); /*Pick the right element if it's smaller*/ j++; /*Move the pointer to the next element in the right array*/ numInversions += (middle - (i+start) + 1); } k++; /*Move the pointer to the next element in the merged array*/ } /*Copy the remaining elements*/ while(i < leftSize){ *(ptr+k) = *(ptrLeft+i); i++; k++; } while(j < rightSize){ *(ptr+k) = *(ptrRight+j); j++; k++; } return numInversions; }
the_stack_data/547207.c
// No touchio module functions.
the_stack_data/90761573.c
#include<stdio.h> #include<pthread.h> #include<stdlib.h> int sum; void *sumf(void *value){ int i, upper = strtol(value, 0, 0); // string to long for(int i=1;i<=upper;i++){ sum+=i; } //calculate the number and exit the thread } int main(int argc, char *argv[]){ pthread_t tid; if(argc < 2){ printf("Usage: %s number\n", argv[0]); exit(-1); } pthread_create(&tid, NULL, (void*)sumf, (void*)argv[1]); pthread_join(tid,NULL); printf("sum = %d\n",sum); }
the_stack_data/232956783.c
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <assert.h> #include <stdio.h> int main() { assert(0); printf("shouldn't be here\n"); return 0; }
the_stack_data/92325387.c
#include <stdio.h> #include <inttypes.h> unsigned fib(unsigned n) { if (!n) return 0; else if (n <= 2) return 1; else { unsigned a, c; for (a = c = 1;; --n) { c += a; if (n <= 3) return c; a = c - a; } } } int main() { printf("%ju", fib(5)); return 0; }
the_stack_data/187642931.c
/* * Copyright (c) 2017, 2018, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ int main() { unsigned long a = 0; unsigned long b = 7; return a / b; }
the_stack_data/218944.c
/* * keyd - A key remapping daemon. * * © 2019 Raheman Vaiya (see also: LICENSE). */ #include "error.h" char errstr[2048]; int debug_level;
the_stack_data/76700866.c
/*Exercise 3 - Repetition Write a C program to calculate the sum of the numbers from 1 to n. Where n is a keyboard input. e.g. n -> 100 sum = 1+2+3+....+ 99+100 = 5050 n -> 1- sum = 1+2+3+...+10 = 55 */ #include <stdio.h> int main() { int i, n; int sum = 0; printf("ENTER NUMBER"); scanf("%d", &n); for(i = 0; i < n; i++){ sum = sum + i; } printf("%d", sum); return 0; }
the_stack_data/399635.c
/** * This file was autogenerated from Al_seana_16_Bold.png by WiiBuilder. */ const unsigned char Al_seana_16_Bold[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x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x01, 0x3B, 0x75, 0x97, 0x55, 0xDD, 0x94, 0xB3, 0xCE, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 }; const int Al_seana_16_Bold_size = 6268;
the_stack_data/30718.c
/* 3. Implement a program that creates two threads. The threads will print their ID (pthread_self) 10 times and then stop. Insure that the printed IDs alternate always (ie A, B, A, B, ...) */ #include <pthread.h> #include <stdio.h> #include <stdlib.h> pthread_mutex_t mta, mtb; pthread_t a, b; void* funca(void *arg) { int i; for(i = 0; i < 10; ++ i) { pthread_mutex_lock(&mta); printf("Thread A = %d\n", (int)pthread_self()); pthread_mutex_unlock(&mtb); } return NULL; } void* funcb(void *arg) { int i; for(i = 0; i < 10; ++ i) { pthread_mutex_lock(&mtb); printf("Thread B = %d\n", (int)pthread_self()); pthread_mutex_unlock(&mta); } return NULL; } int main() { pthread_mutex_init(&mta, NULL); pthread_mutex_init(&mtb, NULL); pthread_mutex_lock(&mtb); pthread_create(&a, NULL, funca, NULL); pthread_create(&b, NULL, funcb, NULL); pthread_join(a, NULL); pthread_join(b, NULL); pthread_mutex_destroy(&mta); pthread_mutex_destroy(&mtb); return 0; }
the_stack_data/95450129.c
/* $NetBSD: _inet_pton.c,v 1.4 2005/09/13 01:44:09 christos Exp $ */ /* * Written by Klaus Klein, September 14, 1999. * Public domain. */ #include <sys/cdefs.h> #if defined(LIBC_SCCS) && !defined(lint) __RCSID("$NetBSD: _inet_pton.c,v 1.4 2005/09/13 01:44:09 christos Exp $"); #endif /* LIBC_SCCS and not lint */ #if defined(__indr_reference) __indr_reference(_inet_pton, inet_pton) #else #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> int _inet_pton(int, const char *, void *); int inet_pton(int af, const char *src, void *dst) { return _inet_pton(af, src, dst); } #endif
the_stack_data/31490.c
#include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <pthread.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <db.h> #define ENV_DIRECTORY "TXNAPP" void add_cat(DB_ENV *, DB *, char *, ...); void run_xact(DB_ENV *, DB *, int, int); /*void add_color(DB_ENV *, DB *, char *, int); void add_fruit(DB_ENV *, DB *, char *, char *); */ void *checkpoint_thread(void *); void log_archlist(DB_ENV *); void *logfile_thread(void *); void db_open(DB_ENV *, DB **, char *, int); void env_dir_create(void); void env_open(DB_ENV **); void usage(void); int main(int argc, char *argv[]) { extern int optind; DB *db_cats; /*, *db_color, *db_fruit; */ DB_ENV *dbenv; pthread_t ptid; int ch, ret; /* while ((ch = getopt(argc, argv, "")) != EOF) switch (ch) { case '?': default: usage(); } argc -= optind; argv += optind; */ assert(argc == 3); env_dir_create(); env_open(&dbenv); /* Start a checkpoint thread. */ if ((ret = pthread_create( &ptid, NULL, checkpoint_thread, (void *)dbenv)) != 0) { fprintf(stderr, "txnapp: failed spawning checkpoint thread: %s\n", strerror(ret)); exit (1); } /* Start a logfile removal thread. */ if ((ret = pthread_create( &ptid, NULL, logfile_thread, (void *)dbenv)) != 0) { fprintf(stderr, "txnapp: failed spawning log file removal thread: %s\n", strerror(ret)); exit (1); } /* Open database: Key is fruit class; Data is specific type. */ /* db_open(dbenv, &db_fruit, "fruit", 0); */ /* Open database: Key is a color; Data is an integer. */ /*db_open(dbenv, &db_color, "color", 0); */ /* * Open database: * Key is a name; Data is: company name, address, cat breeds. */ db_open(dbenv, &db_cats, "cats", 1); /* add_fruit(dbenv, db_fruit, "apple", "yellow delicious"); add_color(dbenv, db_color, "blue", 0); add_color(dbenv, db_color, "blue", 3); */ /* add_cat(dbenv, db_cats, "Amy Adams", "Sleepycat Software", "394 E. Riding Dr., Carlisle, MA 01741, USA", "abyssinian", "bengal", "chartreaux", NULL);*/ int r; int num_xact = atoi(argv[1]); //100; int insert_per_xact = atoi(argv[2]); //1000; for(r = 0; r < num_xact; r ++) { run_xact(dbenv, db_cats, 1+r*insert_per_xact, insert_per_xact); } return (0); } void env_dir_create() { struct stat sb; /* * If the directory exists, we're done. We do not further check * the type of the file, DB will fail appropriately if it's the * wrong type. */ if (stat(ENV_DIRECTORY, &sb) == 0) return; /* Create the directory, read/write/access owner only. */ if (mkdir(ENV_DIRECTORY, S_IRWXU) != 0) { fprintf(stderr, "txnapp: mkdir: %s: %s\n", ENV_DIRECTORY, strerror(errno)); exit (1); } } void env_open(DB_ENV **dbenvp) { DB_ENV *dbenv; int ret; /* Create the environment handle. */ if ((ret = db_env_create(&dbenv, 0)) != 0) { fprintf(stderr, "txnapp: db_env_create: %s\n", db_strerror(ret)); exit (1); } /* Set up error handling. */ dbenv->set_errpfx(dbenv, "txnapp"); dbenv->set_errfile(dbenv, stderr); /* Do deadlock detection internally. */ if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT)) != 0) { dbenv->err(dbenv, ret, "set_lk_detect: DB_LOCK_DEFAULT"); exit (1); } /* * Open a transactional environment: * create if it doesn't exist * free-threaded handle * run recovery * read/write owner only */ if ((ret = dbenv->open(dbenv, ENV_DIRECTORY, DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_RECOVER | DB_THREAD, S_IRUSR | S_IWUSR)) != 0) { dbenv->err(dbenv, ret, "dbenv->open: %s", ENV_DIRECTORY); exit (1); } *dbenvp = dbenv; } void * checkpoint_thread(void *arg) { DB_ENV *dbenv; int ret; dbenv = arg; dbenv->errx(dbenv, "Checkpoint thread: %lu", (u_long)pthread_self()); /* Checkpoint once a minute. */ for (;; sleep(60)) if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0)) != 0) { dbenv->err(dbenv, ret, "checkpoint thread"); exit (1); } /* NOTREACHED */ } void * logfile_thread(void *arg) { DB_ENV *dbenv; int ret; char **begin, **list; dbenv = arg; dbenv->errx(dbenv, "Log file removal thread: %lu", (u_long)pthread_self()); /* Check once every 5 minutes. */ for (;; sleep(300)) { /* Get the list of log files. */ if ((ret = dbenv->log_archive(dbenv, &list, DB_ARCH_ABS)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->log_archive"); exit (1); } /* Remove the log files. */ if (list != NULL) { for (begin = list; *list != NULL; ++list) if ((ret = remove(*list)) != 0) { dbenv->err(dbenv, ret, "remove %s", *list); exit (1); } free (begin); } } /* NOTREACHED */ } void log_archlist(DB_ENV *dbenv) { int ret; char **begin, **list; /* Get the list of database files. */ if ((ret = dbenv->log_archive(dbenv, &list, DB_ARCH_ABS | DB_ARCH_DATA)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->log_archive: DB_ARCH_DATA"); exit (1); } if (list != NULL) { for (begin = list; *list != NULL; ++list) printf("database file: %s\n", *list); free (begin); } /* Get the list of log files. */ if ((ret = dbenv->log_archive(dbenv, &list, DB_ARCH_ABS | DB_ARCH_LOG)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->log_archive: DB_ARCH_LOG"); exit (1); } if (list != NULL) { for (begin = list; *list != NULL; ++list) printf("log file: %s\n", *list); free (begin); } } void db_open(DB_ENV *dbenv, DB **dbp, char *name, int dups) { DB *db; int ret; /* Create the database handle. */ if ((ret = db_create(&db, dbenv, 0)) != 0) { dbenv->err(dbenv, ret, "db_create"); exit (1); } /* Optionally, turn on duplicate data items. */ /* if (dups && (ret = db->set_flags(db, DB_DUP)) != 0) { dbenv->err(dbenv, ret, "db->set_flags: DB_DUP"); exit (1); } */ /* * Open a database in the environment: * create if it doesn't exist * free-threaded handle * read/write owner only */ if ((ret = db->open(db, NULL, name, NULL, /*DB_BTREE*//* DB_RECNO */DB_HASH, DB_AUTO_COMMIT | DB_CREATE | DB_THREAD, S_IRUSR | S_IWUSR)) != 0) { (void)db->close(db, 0); dbenv->err(dbenv, ret, "db->open: %s", name); exit (1); } *dbp = db; } void add_fruit(DB_ENV *dbenv, DB *db, char *fruit, char *name) { DBT key, data; DB_TXN *tid; int ret; /* Initialization. */ memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data)); key.data = fruit; key.size = strlen(fruit); data.data = name; data.size = strlen(name); for (;;) { /* Begin the transaction. */ if ((ret = dbenv->txn_begin(dbenv, NULL, &tid, 0)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->txn_begin"); exit (1); } /* Store the value. */ switch (ret = db->put(db, tid, &key, &data, 0)) { case 0: /* Success: commit the change. */ if ((ret = tid->commit(tid, 0)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->commit"); exit (1); } return; case DB_LOCK_DEADLOCK: /* Deadlock: retry the operation. */ if ((ret = tid->abort(tid)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->abort"); exit (1); } break; default: /* Error: run recovery. */ dbenv->err(dbenv, ret, "dbc->put: %s/%s", fruit, name); exit (1); } } } void add_color(DB_ENV *dbenv, DB *dbp, char *color, int increment) { DBT key, data; DB_TXN *tid; int original, ret; char buf[64]; /* Initialization. */ memset(&key, 0, sizeof(key)); key.data = color; key.size = strlen(color); memset(&data, 0, sizeof(data)); data.flags = DB_DBT_MALLOC; for (;;) { /* Begin the transaction. */ if ((ret = dbenv->txn_begin(dbenv, NULL, &tid, 0)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->txn_begin"); exit (1); } /* * Get the key. If it exists, we increment the value. If it * doesn't exist, we create it. */ switch (ret = dbp->get(dbp, tid, &key, &data, 0)) { case 0: original = atoi(data.data); break; case DB_LOCK_DEADLOCK: /* Deadlock: retry the operation. */ if ((ret = tid->abort(tid)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->abort"); exit (1); } continue; case DB_NOTFOUND: original = 0; break; default: /* Error: run recovery. */ dbenv->err( dbenv, ret, "dbc->get: %s/%d", color, increment); exit (1); } if (data.data != NULL) free(data.data); /* Create the new data item. */ (void)snprintf(buf, sizeof(buf), "%d", original + increment); data.data = buf; data.size = strlen(buf) + 1; /* Store the new value. */ switch (ret = dbp->put(dbp, tid, &key, &data, 0)) { case 0: /* Success: commit the change. */ if ((ret = tid->commit(tid, 0)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->commit"); exit (1); } return; case DB_LOCK_DEADLOCK: /* Deadlock: retry the operation. */ if ((ret = tid->abort(tid)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->abort"); exit (1); } break; default: /* Error: run recovery. */ dbenv->err( dbenv, ret, "dbc->put: %s/%d", color, increment); exit (1); } } } void add_cat(DB_ENV *dbenv, DB *db, char *name, ...) { va_list ap; DBC *dbc; DBT key, data; DB_TXN *tid; int ret; char *s; /* Initialization. */ memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data)); key.data = name; key.size = strlen(name); retry: /* Begin the transaction. */ if ((ret = dbenv->txn_begin(dbenv, NULL, &tid, 0)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->txn_begin"); exit (1); } /* Delete any previously existing item. */ switch (ret = db->del(db, tid, &key, 0)) { case 0: case DB_NOTFOUND: break; case DB_LOCK_DEADLOCK: /* Deadlock: retry the operation. */ if ((ret = tid->abort(tid)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->abort"); exit (1); } goto retry; default: dbenv->err(dbenv, ret, "db->del: %s", name); exit (1); } /* Create a cursor. */ if ((ret = db->cursor(db, tid, &dbc, 0)) != 0) { dbenv->err(dbenv, ret, "db->cursor"); exit (1); } /* Append the items, in order. */ va_start(ap, name); while ((s = va_arg(ap, char *)) != NULL) { data.data = s; data.size = strlen(s); switch (ret = dbc->c_put(dbc, &key, &data, DB_KEYLAST)) { case 0: break; case DB_LOCK_DEADLOCK: va_end(ap); /* Deadlock: retry the operation. */ if ((ret = dbc->c_close(dbc)) != 0) { dbenv->err( dbenv, ret, "dbc->c_close"); exit (1); } if ((ret = tid->abort(tid)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->abort"); exit (1); } goto retry; default: /* Error: run recovery. */ dbenv->err(dbenv, ret, "dbc->put: %s/%s", name, s); exit (1); } } va_end(ap); /* Success: commit the change. */ if ((ret = dbc->c_close(dbc)) != 0) { dbenv->err(dbenv, ret, "dbc->c_close"); exit (1); } if ((ret = tid->commit(tid, 0)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->commit"); exit (1); } } void run_xact(DB_ENV *dbenv, DB *db, int offset, int count) { va_list ap; DBC *dbc; DBT key, data; DB_TXN *tid; int ret; char *s; /* Initialization. */ memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data)); int keyPtr; int valPtr; key.data = &keyPtr; key.size = sizeof(int);/*strlen(name);*/ data.data = &valPtr; data.size = sizeof(int); retry: /* Begin the transaction. */ if ((ret = dbenv->txn_begin(dbenv, NULL, &tid, 0)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->txn_begin"); exit (1); } /* Delete any previously existing item. */ /* switch (ret = db->del(db, tid, &key, 0)) { case 0: case DB_NOTFOUND: break; case DB_LOCK_DEADLOCK: / * Deadlock: retry the operation. * / if ((ret = tid->abort(tid)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->abort"); exit (1); } goto retry; default: dbenv->err(dbenv, ret, "db->del: %s", name); exit (1); } */ /* Create a cursor. */ if ((ret = db->cursor(db, tid, &dbc, 0)) != 0) { dbenv->err(dbenv, ret, "db->cursor"); exit (1); } /* Append the items, in order. */ // va_start(ap, name); // while ((s = va_arg(ap, char *)) != NULL) { int q; for(q = offset; q < offset + count; q++) { keyPtr = q; valPtr = q; /* data.data = s; data.size = strlen(s); */ // printf("A"); fflush(NULL); switch (ret = dbc->c_put(dbc, &key, &data, DB_KEYLAST)) { case 0: // printf("B"); fflush(NULL); break; case DB_LOCK_DEADLOCK: va_end(ap); /* Deadlock: retry the operation. */ if ((ret = dbc->c_close(dbc)) != 0) { dbenv->err( dbenv, ret, "dbc->c_close"); exit (1); } if ((ret = tid->abort(tid)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->abort"); exit (1); } goto retry; default: /* Error: run recovery. */ dbenv->err(dbenv, ret, "dbc->put: %d/%d", q, q); exit (1); } } va_end(ap); /* Success: commit the change. */ if ((ret = dbc->c_close(dbc)) != 0) { dbenv->err(dbenv, ret, "dbc->c_close"); exit (1); } if ((ret = tid->commit(tid, 0)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->commit"); exit (1); } } void usage() { (void)fprintf(stderr, "usage: txnapp\n"); exit(1); }
the_stack_data/139121.c
#include <stdio.h> #ifndef DEPUTY #define DEPUTY_NUM_CHECKS_ADDED 0 #endif #define SIZE 16384 int localfunc() { // A local array of integers int array[SIZE]; int acc = 0; int i; for(i=0;i<SIZE;i++) { acc += array[i]; } return acc; } int main() { int i; for(i=0;i<100000;i++) { localfunc(); } //All checks in this program should have been optimized away. if (DEPUTY_NUM_CHECKS_ADDED != 0) { return 3; } return 0; }
the_stack_data/150144224.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_iterative_power.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: angmarti <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/13 12:07:30 by sblanco- #+# #+# */ /* Updated: 2021/08/25 13:41:56 by angmarti ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> int ft_iterative_power(int nb, int power) { int acc; acc = 1; if (power < 0) acc = 0; while (power > 0) { acc *= nb; power--; } return (acc); } // int main(void) // { // int i = 0; // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // printf("%d\n", ft_iterative_power(3, i++)); // }
the_stack_data/212644223.c
/* ***************************************************************** * * Copyright 2017 Microsoft. All Rights Reserved. * * * * 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 defined(__WITH_TLS__) || defined(__WITH_DTLS__) #include "iotivity_config.h" #include "experimental/logger.h" #include <stddef.h> #include <string.h> #include <assert.h> #include <inttypes.h> #include "oic_malloc.h" #include "oic_string.h" #include "cacommon.h" #include "experimental/ocrandom.h" #include "cacommonutil.h" #include "ocpayload.h" #include "experimental/payload_logging.h" #include "pmutility.h" #include "srmutility.h" #include "srmresourcestrings.h" // headers required for mbed TLS #include "mbedtls/config.h" #include "mbedtls/platform.h" #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/x509_csr.h" #include "mbedtls/oid.h" #include "mbedtls/x509_crt.h" #include "mbedtls/oid.h" #include "mbedtls/pem.h" #include "mbedtls/base64.h" #ifndef NDEBUG #include "mbedtls/debug.h" #include "mbedtls/version.h" #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <fcntl.h> #include "certhelpers.h" #include "occertutility.h" #define TAG "OIC_OCCERTUTILITY" /** * @def PERSONALIZATION_STRING * @brief Personalization string for the mbedtls RNG */ #define PERSONALIZATION_STRING "IOTIVITY_RND" #define MAX_URI_QUERY MAX_URI_LENGTH + MAX_QUERY_LENGTH #define MAX_STRING_LEN 254 /* ASN.1 DER encoding of the EKU for identity certificates (1.3.6.1.4.1.44924.1.6) */ static const unsigned char s_ekuIdentity[] = { 0x30, 0x0C, 0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xDE, 0x7C, 0x01, 0x06 }; /* ASN.1 DER encoding of the EKU for role certificates (1.3.6.1.4.1.44924.1.7) */ static const unsigned char s_ekuRole[] = { 0x30, 0x0C, 0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xDE, 0x7C, 0x01, 0x07 }; /* ASN.1 DER encoding of the EKU for both identity and roles (for use by CAs) */ static const unsigned char s_ekuCA[] = { 0x30, 0x18, 0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xDE, 0x7C, 0x01, 0x06, 0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xDE, 0x7C, 0x01, 0x07 }; OCStackResult OC_CALL OCGenerateRandomSerialNumber(char **serial, size_t *serialLen) { int ret = 0; OCStackResult res = OC_STACK_ERROR; unsigned char random[20]; /* Per RFC 5280, 20 octets is the maximum length of a serial number. */ mbedtls_mpi serialMpi; VERIFY_NOT_NULL_RETURN(TAG, serial, ERROR, OC_STACK_INVALID_PARAM); VERIFY_NOT_NULL_RETURN(TAG, serialLen, ERROR, OC_STACK_INVALID_PARAM); mbedtls_mpi_init(&serialMpi); memset(serial, 0, sizeof(*serial)); VERIFY_SUCCESS(TAG, OCGetRandomBytes(random, sizeof(random)), ERROR); /* Per RFC 5280, 20 octets is the maximum length of a serial number. In ASN.1, if the highest-order * bit is set it causes a padding octet to be written, which would be 21 and non-compliant. * Therefore, always clear the highest-order bit. Integers in ASN.1 are always big-Endian. */ random[0] &= 0x7F; /* Import into a large integer object and then output as a string. */ ret = mbedtls_mpi_read_binary(&serialMpi, random, sizeof(random)); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); /* Get the needed string length and allocate. */ ret = mbedtls_mpi_write_string(&serialMpi, 10, NULL, 0, serialLen); VERIFY_SUCCESS(TAG, ret == MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL, ERROR); *serial = OICCalloc(1, *serialLen); VERIFY_NOT_NULL(TAG, *serial, ERROR); /* Do the write for real. */ ret = mbedtls_mpi_write_string(&serialMpi, 10, *serial, *serialLen, serialLen); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); res = OC_STACK_OK; exit: if (OC_STACK_OK != res) { OICFree(*serial); *serial = NULL; *serialLen = 0; } mbedtls_mpi_free(&serialMpi); return res; } OCStackResult OC_CALL OCGenerateKeyPair(char **publicKey, size_t *publicKeyLen, char **privateKey, size_t *privateKeyLen) { int ret = 0; mbedtls_pk_context keyPair; unsigned char buf[2048]; mbedtls_pk_init(&keyPair); VERIFY_NOT_NULL_RETURN(TAG, publicKey, ERROR, OC_STACK_INVALID_PARAM); VERIFY_NOT_NULL_RETURN(TAG, publicKeyLen, ERROR, OC_STACK_INVALID_PARAM); VERIFY_NOT_NULL_RETURN(TAG, privateKey, ERROR, OC_STACK_INVALID_PARAM); VERIFY_NOT_NULL_RETURN(TAG, privateKeyLen, ERROR, OC_STACK_INVALID_PARAM); *publicKey = NULL; *publicKeyLen = 0; *privateKey = NULL; *privateKeyLen = 0; ret = OCInternalGenerateKeyPair(&keyPair); if (ret != 0) { OIC_LOG_V(ERROR, TAG, "Failed to generate key pair: %d", ret); goto exit; } ret = mbedtls_pk_write_pubkey_pem(&keyPair, buf, sizeof(buf)); if (ret != 0) { OIC_LOG_V(ERROR, TAG, "Failed to export public key as PEM: %d", ret); goto exit; } *publicKeyLen = strlen((char *)buf) + 1; *publicKey = OICCalloc(1, *publicKeyLen); if (NULL == *publicKey) { OIC_LOG(ERROR, TAG, "Could not allocate memory for public key"); ret = -1; goto exit; } memcpy(*publicKey, buf, *publicKeyLen); ret = mbedtls_pk_write_key_pem(&keyPair, buf, sizeof(buf)); if (ret != 0) { OIC_LOG_V(ERROR, TAG, "Failed to export private key as PEM: %d", ret); goto exit; } *privateKeyLen = strlen((char *)buf) + 1; *privateKey = OICCalloc(1, *privateKeyLen); if (NULL == *privateKey) { OIC_LOG(ERROR, TAG, "Could not allocate memory for private key"); ret = -1; goto exit; } memcpy(*privateKey, buf, *privateKeyLen); exit: mbedtls_pk_free(&keyPair); OICClearMemory(buf, sizeof(buf)); if (ret != 0) { OICFree(*publicKey); OICClearMemory(*privateKey, *privateKeyLen); OICFree(*privateKey); *publicKey = NULL; *publicKeyLen = 0; *privateKey = NULL; *privateKeyLen = 0; return OC_STACK_ERROR; } else { return OC_STACK_OK; } } typedef enum { CERT_TYPE_CA, CERT_TYPE_IDENTITY, CERT_TYPE_ROLE } CertificateType_t; static OCStackResult GenerateCertificate( CertificateType_t certType, const char *subject, const char *subjectPublicKey, const char *issuerCert, const char *issuerPrivateKey, const char *serial, const char *notValidBefore, const char *notValidAfter, const char *role, const char *authority, OCByteString *certificate) { OCStackResult res = OC_STACK_INVALID_PARAM; int ret = 0; mbedtls_x509write_cert outCertCtx; mbedtls_pk_context subjKeyCtx; mbedtls_pk_context issKeyCtx; mbedtls_x509_crt issCertCtx; mbedtls_mpi serialMpi; mbedtls_x509_general_names names; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; char buf[2048]; if (NULL == subjectPublicKey || NULL == issuerPrivateKey || NULL == subject || NULL == serial || NULL == notValidBefore || NULL == notValidAfter) { return OC_STACK_INVALID_PARAM; } mbedtls_x509write_crt_init(&outCertCtx); mbedtls_pk_init(&subjKeyCtx); mbedtls_pk_init(&issKeyCtx); mbedtls_x509_crt_init(&issCertCtx); mbedtls_mpi_init(&serialMpi); memset(&names, 0, sizeof(names)); mbedtls_ctr_drbg_init(&ctr_drbg); mbedtls_entropy_init(&entropy); memset(certificate, 0, sizeof(*certificate)); ret = mbedtls_mpi_read_string(&serialMpi, 10, serial); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); ret = mbedtls_pk_parse_public_key(&subjKeyCtx, (const uint8_t *)subjectPublicKey, strlen(subjectPublicKey) + 1); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); ret = mbedtls_pk_parse_key(&issKeyCtx, (const uint8_t *)issuerPrivateKey, strlen(issuerPrivateKey) + 1, NULL, 0); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); /* If issuerCert is NULL, then the cert will be self-signed. */ if (NULL != issuerCert) { ret = mbedtls_x509_crt_parse(&issCertCtx, (const uint8_t *)issuerCert, strlen(issuerCert) + 1); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); } ret = mbedtls_x509write_crt_set_validity(&outCertCtx, notValidBefore, notValidAfter); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); mbedtls_x509write_crt_set_version(&outCertCtx, MBEDTLS_X509_CRT_VERSION_3); mbedtls_x509write_crt_set_md_alg(&outCertCtx, MBEDTLS_MD_SHA256); res = OC_STACK_ERROR; ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, (const uint8_t *)PERSONALIZATION_STRING, sizeof(PERSONALIZATION_STRING)); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); mbedtls_ctr_drbg_set_prediction_resistance(&ctr_drbg, MBEDTLS_CTR_DRBG_PR_ON); ret = mbedtls_x509write_crt_set_serial(&outCertCtx, &serialMpi); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); ret = mbedtls_x509write_crt_set_subject_name(&outCertCtx, subject); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); if (NULL != issuerCert) { // mbedtls_x509_dn_gets returns the number of bytes written to buf. ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &issCertCtx.subject); VERIFY_SUCCESS(TAG, 0 < ret, ERROR); ret = mbedtls_x509write_crt_set_issuer_name(&outCertCtx, buf); } else { /* If self-signed, use the same contents of subject for the issuer name. */ ret = mbedtls_x509write_crt_set_issuer_name(&outCertCtx, subject); } VERIFY_SUCCESS(TAG, 0 == ret, ERROR); mbedtls_x509write_crt_set_subject_key(&outCertCtx, &subjKeyCtx); mbedtls_x509write_crt_set_issuer_key(&outCertCtx, &issKeyCtx); if (certType == CERT_TYPE_CA) { ret = mbedtls_x509write_crt_set_basic_constraints(&outCertCtx, 1, -1); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); ret = mbedtls_x509write_crt_set_key_usage(&outCertCtx, MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); } else { ret = mbedtls_x509write_crt_set_basic_constraints(&outCertCtx, 0, 0); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); ret = mbedtls_x509write_crt_set_key_usage(&outCertCtx, MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_ENCIPHERMENT | MBEDTLS_X509_KU_DATA_ENCIPHERMENT | MBEDTLS_X509_KU_KEY_AGREEMENT); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); } switch (certType) { case CERT_TYPE_ROLE: ret = mbedtls_x509write_crt_set_extension(&outCertCtx, MBEDTLS_OID_EXTENDED_KEY_USAGE, MBEDTLS_OID_SIZE(MBEDTLS_OID_EXTENDED_KEY_USAGE), 0, s_ekuRole, sizeof(s_ekuRole)); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); ret = snprintf(buf, sizeof(buf), "CN=%s%s%s", role, (NULL != authority) ? ",OU=" : "", (NULL != authority) ? authority : ""); // To prevent sign-compare warning sizeof(buf) is cast to int. This is safe because the max size of buf fits into int. // Note ret value from snprintf may be negative if there was an error so it should not be cast to size_t. VERIFY_SUCCESS(TAG, ret < (int)sizeof(buf), ERROR); names.next = NULL; names.general_name.name_type = MBEDTLS_X509_GENERALNAME_DIRECTORYNAME; ret = mbedtls_x509_string_to_names(&names.general_name.directory_name, buf); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); ret = mbedtls_x509write_crt_set_subject_alt_names(&outCertCtx, &names); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); break; case CERT_TYPE_IDENTITY: ret = mbedtls_x509write_crt_set_extension(&outCertCtx, MBEDTLS_OID_EXTENDED_KEY_USAGE, MBEDTLS_OID_SIZE(MBEDTLS_OID_EXTENDED_KEY_USAGE), 0, s_ekuIdentity, sizeof(s_ekuIdentity)); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); break; case CERT_TYPE_CA: ret = mbedtls_x509write_crt_set_extension(&outCertCtx, MBEDTLS_OID_EXTENDED_KEY_USAGE, MBEDTLS_OID_SIZE(MBEDTLS_OID_EXTENDED_KEY_USAGE), 0, s_ekuCA, sizeof(s_ekuCA)); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); break; default: assert(false); VERIFY_SUCCESS(TAG, false, ERROR); } ret = mbedtls_x509write_crt_pem(&outCertCtx, (uint8_t *)buf, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg); VERIFY_SUCCESS(TAG, 0 == ret, ERROR); certificate->len = strlen(buf) + 1; certificate->bytes = (uint8_t *)OICCalloc(1, certificate->len); VERIFY_NOT_NULL(TAG, certificate->bytes, ERROR); memcpy(certificate->bytes, buf, certificate->len); res = OC_STACK_OK; exit: if (OC_STACK_OK != res) { OICFree(certificate->bytes); certificate->bytes = NULL; certificate->len = 0; } mbedtls_ctr_drbg_free(&ctr_drbg); mbedtls_entropy_free(&entropy); mbedtls_asn1_free_named_data_list(&names.general_name.directory_name); mbedtls_mpi_free(&serialMpi); mbedtls_x509_crt_free(&issCertCtx); mbedtls_pk_free(&issKeyCtx); mbedtls_pk_free(&subjKeyCtx); mbedtls_x509write_crt_free(&outCertCtx); return res; } OCStackResult OC_CALL OCGenerateCACertificate( const char *subject, const char *subjectPublicKey, const char *issuerCert, const char *issuerPrivateKey, const char *serial, const char *notValidBefore, const char *notValidAfter, char **certificate, size_t *certificateLen) { OCStackResult res = OC_STACK_OK; OCByteString byteStr = { 0 }; res = GenerateCertificate( CERT_TYPE_CA, subject, subjectPublicKey, issuerCert, issuerPrivateKey, serial, notValidBefore, notValidAfter, NULL, NULL, &byteStr); if (OC_STACK_OK == res) { *certificate = (char *)byteStr.bytes; *certificateLen = byteStr.len; } return res; } OCStackResult OC_CALL OCGenerateIdentityCertificate( const OicUuid_t *subjectUuid, const char *subjectPublicKey, const char *issuerCert, const char *issuerPrivateKey, const char *serial, const char *notValidBefore, const char *notValidAfter, char **certificate, size_t *certificateLen) { OCStackResult res = OC_STACK_OK; OCByteString byteStr = { 0 }; char uuidStr[UUID_STRING_SIZE] = { 0 } ; char subject[sizeof(uuidStr) + sizeof(SUBJECT_PREFIX)] = { 0 } ; if (NULL == issuerCert) { return OC_STACK_INVALID_PARAM; } if (!OCConvertUuidToString(subjectUuid->id, uuidStr)) { OIC_LOG(ERROR, TAG, "Could not convert UUID"); return OC_STACK_INVALID_PARAM; } if (snprintf(subject, sizeof(subject), "%s%s", SUBJECT_PREFIX, uuidStr) == sizeof(subject)) { OIC_LOG(ERROR, TAG, "Could not write subject string"); return OC_STACK_INVALID_PARAM; } res = GenerateCertificate( CERT_TYPE_IDENTITY, subject, subjectPublicKey, issuerCert, issuerPrivateKey, serial, notValidBefore, notValidAfter, NULL, NULL, &byteStr); if (OC_STACK_OK == res) { *certificate = (char *)byteStr.bytes; *certificateLen = byteStr.len; } return res; } OCStackResult OC_CALL OCGenerateRoleCertificate( const OicUuid_t *subjectUuid, const char *subjectPublicKey, const char *issuerCert, const char *issuerPrivateKey, const char *serial, const char *notValidBefore, const char *notValidAfter, const char *role, const char *authority, char **certificate, size_t *certificateLen) { OCStackResult res = OC_STACK_ERROR; OCByteString byteStr; char uuidStr[UUID_STRING_SIZE] = { 0 }; char subject[sizeof(uuidStr) + sizeof(SUBJECT_PREFIX)] = { 0 }; memset(&byteStr, 0, sizeof(byteStr)); if (NULL == role || NULL == issuerCert) { return OC_STACK_INVALID_PARAM; } if (!OCConvertUuidToString(subjectUuid->id, uuidStr)) { OIC_LOG(ERROR, TAG, "Could not convert UUID"); return OC_STACK_INVALID_PARAM; } if (snprintf(subject, sizeof(subject), "%s%s", SUBJECT_PREFIX, uuidStr) == sizeof(subject)) { OIC_LOG(ERROR, TAG, "Could not write subject string"); return OC_STACK_INVALID_PARAM; } res = GenerateCertificate( CERT_TYPE_ROLE, subject, subjectPublicKey, issuerCert, issuerPrivateKey, serial, notValidBefore, notValidAfter, role, authority, &byteStr); if (OC_STACK_OK == res) { *certificate = (char *)byteStr.bytes; *certificateLen = byteStr.len; } return res; } /* Verify the signature in a CSR is valid. */ static int VerifyCSRSignature(mbedtls_x509_csr* csr) { unsigned char hash[MBEDTLS_MD_MAX_SIZE]; if (csr->sig_md != MBEDTLS_MD_SHA256) { OIC_LOG(ERROR, TAG, "Unexpected digest used in CSR\n"); return -1; } if ((csr->cri.len == 0) || (csr->cri.p == NULL)) { OIC_LOG(ERROR, TAG, "Missing CertificateRequestInfo field in CSR\n"); return -1; } if ((csr->sig.len == 0) || (csr->sig.p == NULL)) { OIC_LOG(ERROR, TAG, "Missing signature field in CSR\n"); return -1; } if (MBEDTLS_OID_CMP(MBEDTLS_OID_ECDSA_SHA256, &csr->sig_oid) != 0) { char buf[256]; if (mbedtls_oid_get_numeric_string(buf, sizeof(buf), &csr->sig_oid) > 0) { OIC_LOG_V(ERROR, TAG, "Unexpected signature OID in CSR (got %s)\n", buf); } else { OIC_LOG(ERROR, TAG, "Unexpected signature OID in CSR\n"); } return -1; } if (mbedtls_pk_get_type(&csr->pk) != MBEDTLS_PK_ECKEY) { OIC_LOG(ERROR, TAG, "Unexpected public key type in CSR\n"); return -1; } /* mbedtls_pk_get_bitlen returns the bit length of the curve */ if (mbedtls_pk_get_bitlen(&csr->pk) != 256) { OIC_LOG(ERROR, TAG, "Unexpected public length in CSR\n"); return -1; } mbedtls_ecp_keypair* ecKey = mbedtls_pk_ec(csr->pk); if ((ecKey != NULL) && (ecKey->grp.id != MBEDTLS_ECP_DP_SECP256R1)) { OIC_LOG(ERROR, TAG, "Unexpected curve parameters in CSR\n"); return -1; } /* Hash the CertificateRequestInfoField (https://tools.ietf.org/html/rfc2986#section-3) */ int ret = mbedtls_md(mbedtls_md_info_from_type(csr->sig_md), csr->cri.p, csr->cri.len, hash); if (ret != 0) { OIC_LOG(ERROR, TAG, "Failed to hash CertificateRequestInfoField\n"); return ret; } /* the length of hash is determined from csr->sig_md*/ ret = mbedtls_pk_verify(&csr->pk, csr->sig_md, hash, 0, csr->sig.p, csr->sig.len); return ret; } OCStackResult OC_CALL OCVerifyCSRSignature(const char* csr) { mbedtls_x509_csr csrObj; mbedtls_x509_csr_init(&csrObj); int ret = mbedtls_x509_csr_parse(&csrObj, (const unsigned char*)csr, strlen(csr) + 1); if (ret < 0) { OIC_LOG_V(ERROR, TAG, "Couldn't parse CSR: %d", ret); mbedtls_x509_csr_free(&csrObj); return OC_STACK_ERROR; } ret = VerifyCSRSignature(&csrObj); mbedtls_x509_csr_free(&csrObj); if (ret != 0) { return OC_STACK_ERROR; } return OC_STACK_OK; } OCStackResult OC_CALL OCGetUuidFromCSR(const char* csr, OicUuid_t* uuid) { mbedtls_x509_csr csrObj; mbedtls_x509_csr_init(&csrObj); int ret = mbedtls_x509_csr_parse(&csrObj, (const unsigned char*)csr, strlen(csr) + 1); if (ret < 0) { OIC_LOG_V(ERROR, TAG, "Couldn't parse CSR: %d", ret); mbedtls_x509_csr_free(&csrObj); return OC_STACK_ERROR; } char uuidStr[UUID_STRING_SIZE + sizeof(SUBJECT_PREFIX) - 1] = { 0 }; // Both constants count NULL, subtract one ret = mbedtls_x509_dn_gets(uuidStr, sizeof(uuidStr), &csrObj.subject); if (ret != (sizeof(uuidStr) - 1)) { OIC_LOG_V(ERROR, TAG, "mbedtls_x509_dn_gets returned length or error: %d, expected %" PRIuPTR, ret, sizeof(uuidStr) - 1); mbedtls_x509_csr_free(&csrObj); return OC_STACK_ERROR; } if (!OCConvertStringToUuid(uuidStr + sizeof(SUBJECT_PREFIX) - 1, uuid->id)) { OIC_LOG_V(ERROR, TAG, "Failed to convert UUID: '%s'", uuidStr); mbedtls_x509_csr_free(&csrObj); return OC_STACK_ERROR; } if (memcmp(uuid->id, &WILDCARD_SUBJECT_ID, sizeof(uuid->id)) == 0) { OIC_LOG(ERROR, TAG, "Invalid UUID in CSR: '*'"); mbedtls_x509_csr_free(&csrObj); return OC_STACK_ERROR; } mbedtls_x509_csr_free(&csrObj); return OC_STACK_OK; } OCStackResult OC_CALL OCGetPublicKeyFromCSR(const char* csr, char** publicKey) { mbedtls_x509_csr csrObj; mbedtls_x509_csr_init(&csrObj); int ret = mbedtls_x509_csr_parse(&csrObj, (const unsigned char*)csr, strlen(csr) + 1); if (ret < 0) { OIC_LOG_V(ERROR, TAG, "Couldn't parse CSR: %d", ret); mbedtls_x509_csr_free(&csrObj); return OC_STACK_ERROR; } char subjectPublicKey[500] = { 0 }; ret = mbedtls_pk_write_pubkey_pem(&csrObj.pk, (unsigned char*)subjectPublicKey, sizeof(subjectPublicKey)); if (ret != 0) { OIC_LOG_V(ERROR, TAG, "Failed to write subject public key as PEM: %d", ret); mbedtls_x509_csr_free(&csrObj); return OC_STACK_ERROR; } size_t pkLen = strlen(subjectPublicKey) + 1; *publicKey = (char*) OICCalloc(1, pkLen); if (*publicKey == NULL) { OIC_LOG(ERROR, TAG, "Failed to allocate memory for public key"); mbedtls_x509_csr_free(&csrObj); return OC_STACK_ERROR; } memcpy(*publicKey, subjectPublicKey, pkLen); mbedtls_x509_csr_free(&csrObj); return OC_STACK_OK; } OCStackResult OC_CALL OCConvertDerCSRToPem(const char* derCSR, size_t derCSRLen, char** pemCSR) { const char* pemHeader = "-----BEGIN CERTIFICATE REQUEST-----\n"; const char* pemFooter = "-----END CERTIFICATE REQUEST-----\n"; /* Get the length required for output*/ size_t pemCSRLen; int ret = mbedtls_pem_write_buffer(pemHeader, pemFooter, (const unsigned char*)derCSR, derCSRLen, NULL, 0, &pemCSRLen); if (ret != MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) { OIC_LOG_V(ERROR, TAG, "Couldn't convert CSR into PEM, failed getting required length: %d", ret); return OC_STACK_ERROR; } *pemCSR = OICCalloc(1, pemCSRLen + 1); if (*pemCSR == NULL) { OIC_LOG(ERROR, TAG, "Failed to allocate memory for PEM CSR"); return OC_STACK_ERROR; } /* Try the conversion */ ret = mbedtls_pem_write_buffer(pemHeader, pemFooter, (const unsigned char *)derCSR, derCSRLen, (unsigned char*) *pemCSR, pemCSRLen, &pemCSRLen); if (ret < 0) { OIC_LOG_V(ERROR, TAG, "Couldn't convert CSR into PEM, failed getting required length: %d", ret); OICFree(*pemCSR); *pemCSR = NULL; return OC_STACK_ERROR; } return OC_STACK_OK; } #endif /* defined(__WITH_TLS__) || defined(__WITH_DTLS__) */
the_stack_data/103265615.c
#include <stdio.h> int main(void) { // if - else문 int num; printf("정수 입력: "); scanf("%d", &num); if (num > 0) { printf("%d는 양수입니다.\n", num); } else { printf("%d는 음수입니다.\n", num); } return 0; }