file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/12636497.c
#include <stdio.h> int main(){ int n, c, multi; scanf("%i", &n); for (c=1; c <= 10; c++){ multi = c * n; printf("%i x %i = %i\n", c, n, multi); } return 0; }
the_stack_data/72769.c
#include <stdio.h> long factorial(int n) { long r; for (int c = 1; c <= n; c++) { r = r * c; } return r; } int fib_rec(int n) { int r = n; if (n >= 2) { r = fib_rec(n-1) + fib_rec(n-2); } return r; } int fib_dyn(int n) { int f[n+1]; int i; f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i-1] + f[i-2]; } return f[n]; } int gcd(int n1, int n2) { int a = n1, b = n2; while (a != b) { if (a > b) { a -= b; } else { b -= a; } } return a; } void print_floyd_triangle(int n) { int i, j, c = 1; for (i = 1; i <= n; i++) { for (j = 0; j <= i; j++) { printf("%d ", c); c++; } printf("\n"); } } void print_pascal_triangle(int n) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < (n - i - 2); j++) { printf(" "); } for (j = 0; j <= i; j++) { printf("%ld ", factorial(i)/(factorial(j)*factorial(i-j))); } printf("\n"); } }
the_stack_data/26698971.c
/** * @file Memory/sample.c Program to show addresses in memory * @brief * Small program to show internal memory addresses. * * @author George Heineman * @date 6/15/08 */ #include <stdlib.h> int f(char *newArray) { char temp[132]; int i; for (i=0; i<132; i++) { newArray[i] = temp[i]; } printf ("-----\n"); printf (" newArray [%u] i [%u] j[%u]\n", &newArray, &temp, &i); } int main (int argc, char **argv) { char *newArray = (char *) malloc(132); int i = 17, j; f (newArray); printf ("-----\n"); printf (" argc [%u] argv [%u]\n", &argc, &argv); printf (" newArray [%u] i [%u] j[%u]\n", newArray, &i, &j); }
the_stack_data/176705451.c
/*Source Code From Laure Gonnord*/ //dummy ex from the aspic distribution int dummy4(){ int t,t0,z; assume(t0>0); t=t0; z=0; while(z<=53) {++t;z+=3;}; return 0; } //Invariant inside the while loop : {t0>0, 3t<=3t0+56, t>=t0, 3t=3t0+z} // at the stop point : {t>=t0+18, t0>0, 3t<=3t0+56, 3t=3t0+z}
the_stack_data/1012030.c
// Tests assigning a literal word pointer void main() { print("qwe"); } void print(char* str) { *(char**)0x80 = (char*)str; }
the_stack_data/50138683.c
/* Copyright (C) 2007-2014 Free Software Foundation, Inc. This file is part of GNU Binutils. 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, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ /* Linked with objcopy.o to flag that this program is 'strip' (not 'objcopy'). */ int is_strip = 1;
the_stack_data/15763589.c
typedef enum {false,true} bool; extern int __VERIFIER_nondet_int(void); int main() { int i; int j; i = __VERIFIER_nondet_int(); j = __VERIFIER_nondet_int(); while (i*j > 0) { i = i - 1; j = j - 1; } return 0; }
the_stack_data/37636878.c
/** ****************************************************************************** * @file stm32f7xx_ll_pwr.c * @author MCD Application Team * @version V1.2.0 * @date 30-December-2016 * @brief PWR LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f7xx_ll_pwr.h" #include "stm32f7xx_ll_bus.h" /** @addtogroup STM32F7xx_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); WRITE_REG(PWR->CR2, (PWR_CR2_CWUPF1 | PWR_CR2_CWUPF2 | PWR_CR2_CWUPF3 | PWR_CR2_CWUPF4 | PWR_CR2_CWUPF5 | PWR_CR2_CWUPF6)); return SUCCESS; } /** * @} */ /** * @} */ /** * @} */ #endif /* defined(PWR) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/179829760.c
#ifdef _WIN32 #define DO_EXPORT __declspec(dllexport) #else #define DO_EXPORT #endif DO_EXPORT int foo(void) { return 0; }
the_stack_data/15762601.c
// names3.c -- using pointer and malloc() #include <stdio.h> #include <string.h> // providing function prototypes of strcpy() and strlen() #include <stdlib.h> // providing function prototypes of malloc() and free() #define SLEN 81 struct namect { char *fname; // using pointer char *lname; int letters; }; void getinfo(struct namect *); // allocate memory void makeinfo(struct namect *); void showinfo(const struct namect *); void cleanup(struct namect *); // release memory when calling this function char *s_gets(char *st, int n); int main(void) { struct namect person; getinfo(&person); makeinfo(&person); showinfo(&person); cleanup(&person); return 0; } void getinfo(struct namect *pst) { char temp[SLEN]; printf("Please enter your first name.\n"); s_gets(temp, SLEN); // allocate memory to store name pst->fname = (char *) malloc(strlen(temp) + 1); // copy the name into the dynamic-allocated memory strcpy(pst->fname, temp); printf("Please enter your last name.\n"); s_gets(temp, SLEN); pst->lname = (char *) malloc(strlen(temp) + 1); strcpy(pst->lname, temp); } void makeinfo(struct namect *pst) { pst->letters = strlen(pst->fname) + strlen(pst->lname); } void showinfo(const struct namect *pst) { printf("%s %s, your name contains %d letters.\n", pst->fname, pst->lname, pst->letters); } void cleanup(struct namect *pst) { free(pst->fname); free(pst->lname); } char *s_gets(char *st, int n) { char *ret_val; char *find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // search the new-line character if (find) // if the address is not NULL *find = '\0'; // place an empty character here else while (getchar() != '\n') continue; // deal with the remain characters in the input } return ret_val; }
the_stack_data/234518014.c
/* $OpenBSD: send.c,v 1.5 2005/08/06 20:30:04 espie Exp $ */ /* * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/types.h> #include <sys/socket.h> #include <stddef.h> ssize_t send(int s, const void *msg, size_t len, int flags) { return (sendto(s, msg, len, flags, NULL, 0)); }
the_stack_data/20672.c
#line 2 "./SSdict2ABdict.c" #line 4 "./SSdict2ABdict.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif extern yy_size_t yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) #define YY_LINENO_REWIND_TO(ptr) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ yy_size_t yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart (FILE *input_file ); void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); void yy_delete_buffer (YY_BUFFER_STATE b ); void yy_flush_buffer (YY_BUFFER_STATE b ); void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); void yypop_buffer_state (void ); static void yyensure_buffer_stack (void ); static void yy_load_buffer_state (void ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len ); void *yyalloc (yy_size_t ); void *yyrealloc (void *,yy_size_t ); void yyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ typedef unsigned char YY_CHAR; FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char *yytext; #ifdef yytext_ptr #undef yytext_ptr #endif #define yytext_ptr yytext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 118 #define YY_END_OF_BUFFER 119 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[148] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 119, 118, 1, 2, 5, 3, 4, 8, 7, 6, 10, 9, 118, 118, 118, 118, 118, 21, 20, 19, 71, 76, 118, 78, 79, 87, 88, 89, 83, 90, 91, 92, 93, 94, 96, 102, 103, 104, 106, 109, 113, 114, 115, 116, 24, 29, 118, 31, 32, 40, 41, 42, 36, 43, 44, 45, 46, 47, 49, 55, 56, 57, 59, 62, 66, 67, 68, 69, 22, 23, 7, 10, 0, 0, 0, 0, 0, 21, 72, 74, 75, 77, 108, 80, 81, 84, 86, 95, 97, 99, 100, 101, 105, 107, 110, 112, 117, 25, 27, 28, 30, 61, 33, 34, 37, 39, 48, 50, 52, 53, 54, 58, 60, 63, 65, 70, 11, 12, 13, 14, 15, 16, 17, 18, 73, 82, 85, 98, 111, 26, 35, 38, 51, 64, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 22, 29, 30, 1, 1, 1, 1, 1, 1, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 22, 47, 48, 49, 50, 51, 52, 22, 53, 54, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[55] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[153] = { 0, 0, 0, 157, 156, 4, 6, 8, 11, 62, 0, 155, 154, 156, 161, 161, 161, 161, 161, 161, 161, 153, 161, 152, 161, 119, 108, 112, 106, 102, 146, 161, 161, 2, 161, 134, 133, 6, 161, 161, 161, 4, 161, 161, 161, 161, 133, 7, 161, 161, 131, 130, 8, 161, 161, 161, 129, 0, 161, 103, 102, 2, 161, 161, 161, 5, 161, 161, 161, 161, 102, 79, 161, 161, 100, 99, 10, 161, 161, 161, 98, 161, 161, 133, 132, 10, 1, 91, 72, 98, 127, 105, 161, 161, 161, 161, 161, 104, 103, 161, 161, 102, 161, 161, 161, 161, 161, 100, 161, 161, 75, 161, 161, 161, 161, 161, 74, 72, 161, 161, 9, 161, 161, 161, 161, 161, 4, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 24, 23, 22, 17, 11 } ; static yyconst flex_int16_t yy_def[153] = { 0, 148, 149, 150, 150, 151, 151, 148, 148, 147, 9, 152, 152, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 0, 147, 147, 147, 147, 147 } ; static yyconst flex_uint16_t yy_nxt[216] = { 0, 14, 14, 15, 16, 14, 21, 22, 21, 22, 23, 24, 81, 23, 24, 91, 96, 98, 20, 97, 101, 107, 92, 18, 17, 14, 147, 102, 147, 147, 147, 93, 147, 99, 108, 103, 104, 115, 110, 25, 116, 26, 25, 117, 26, 111, 147, 131, 126, 132, 129, 146, 27, 112, 28, 27, 145, 28, 118, 29, 127, 130, 29, 14, 30, 31, 14, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 14, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 120, 134, 144, 135, 143, 142, 141, 121, 140, 139, 138, 137, 90, 136, 122, 123, 133, 84, 83, 128, 125, 124, 119, 114, 113, 109, 106, 105, 100, 95, 94, 90, 89, 88, 87, 86, 85, 84, 83, 147, 82, 82, 19, 19, 13, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147 } ; static yyconst flex_int16_t yy_chk[216] = { 0, 2, 2, 2, 2, 2, 5, 5, 6, 6, 7, 7, 152, 8, 8, 33, 37, 41, 151, 37, 47, 52, 33, 150, 149, 148, 0, 47, 0, 0, 0, 33, 0, 41, 52, 47, 47, 61, 57, 7, 61, 7, 8, 65, 8, 57, 0, 86, 76, 86, 85, 126, 7, 57, 7, 8, 120, 8, 65, 7, 76, 85, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 71, 88, 117, 88, 116, 110, 107, 71, 101, 98, 97, 91, 90, 89, 71, 71, 87, 84, 83, 80, 75, 74, 70, 60, 59, 56, 51, 50, 46, 36, 35, 30, 29, 28, 27, 26, 25, 23, 21, 13, 12, 11, 4, 3, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147 } ; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "./SSdict2ABdict.lex" /****************************************************************************** ** File : SSdict2ABdict.lex ** Project : BibleVox ** Date : 2016.09.03 ** Author : MEAdams ** Purpose : Convert a SndSpell dictionary to an ArpaBet dictionary ** Usage : 1. echo "WORD POST SNDSPELL [MARKUP]" | ./SSdict2ABdict ** : --or-- ** : 2. cat inputFileName | ./SSdict2ABdict > outputFileName ******************************************************************************* ** Notes & : 1. This is FLEX (Fast Lexical Analysis) source code. The file ** Assumes : name extension of ".lex" has nothing to do with a BibleVox ** : lexicon or lex. The FLEX interpreter will convert this code ** : into "C" code, which will be compiled in order to create the ** : SSdict2ABdict executable program. See makeFlexExec.bash. ** : ** : 2. BibleVox SndSpell is a spelling syntax in some ways similar to ** : the many other re-spelling guides that have been devised over ** : many years and seen on the Internet. However, they all seem to ** : "borrow" from similar sets of respellings of english sounds ** : and I am unable to discover which system appeared first. The ** : BibleVox SndSpell is an attempt to simplify and regularize to ** : facilitate ease of memorization and computer use. The other ** : systems define multiple spellings for many sounds or sound ** : combinations in order to provide varieties more suitable for ** : visual recognition within particular word spellings and then ** : copyright notices are stamped on them claiming to be unique. ** : Such action makes little legal sense since all of these ** : "various" systems are very similar (i.e. are not sufficiently ** : unique) nor is there an identifiable audit trail allowing the ** : "original" system to be identified and credited. The British ** : Broadcasting Corporation (BBC) "Text Spelling Guide" might ** : have been the original system devised. However, similarities ** : can be seen between it and the DARPA ArpaBet as well. The ** : BibleVox SndSpell system is specifically reduced in size with ** : an increase in logical spelling pattern regularity for ease ** : in programming without significant compromise in visual word ** : recognition (so says the author). It is developed primarily ** : as a means for scripting word pronunciations able to be easily ** : translated into English language speech engine specific ** : pronunciation lexicon syntax (e.g. the Festival speech engine ** : implementation of the DARPA ArpaBet). ** : ** : 3. There are three acceptable input line formats: ** : Comment and blank lines: ** : # Comment text lines begin with "#" in the first column. ** : ** : # Comment text lines and blank lines are simply discarded. ** : ** : Dictionary entries (note that markup comment is optional): ** : Word Part_Of_Speech_Tag SndSpell [Syllable/Accent_markup] ** : ** : Example input entries: ** : # SndSpell dictionary entries for my name. ** : Michael pns MIY-kuhl Mi'chael ** : Edward pns ED-wuhrd Ed'ward ** : Adams pns AD-uhmz Ad'ams ** : ** : # Note that blank lines also are permitted. ** : ** : Output results from example input entries: ** : ("Michael" nnp (((m ay) 1) ((k ax l) 0))) ** : ("Edward" nnp (((eh d) 1) ((w er d) 0))) ** : ("Adams" nnp (((ae d) 1) ((ax m z) 0))) ** : ** : 4. Supported principle Parts-Of-Speech Tags (POST): ** : cns - common noun singular ** : cnp - common noun plural ** : pns - proper noun singular ** : pnp - proper noun plural ** : vrb - verb ** : adj - adjective ** : adv - adverb ** : nil - undefined ** : ** : It is not deemed necessary to support pronoun, preposition, ** : conjunction and interjection directly. However, such words ** : can be included by declaring their POST as type "nil". ** : ** : 5. In actuality, any text beyond the MARKUP field also will be ** : ignored. Therefore, further useful information or comments ** : within the SndSpell dictionary are permitted and will not ** : affect the resulting ArpaBet dictionary output. ** : ** : 6. This code provides minimal (hardly any) error handling. ** : ******************************************************************************* ** To Do : 1. Add error handling code. ;) ** : *******************************************************************************/ /* Definitions */ #line 99 "./SSdict2ABdict.lex" int stress = 0; int spc = 1; void space() { if (spc) { printf(" "); } } #line 670 "./SSdict2ABdict.c" #define INITIAL 0 #define TEXT 1 #define NAME 2 #define POST 3 #define ABET 4 #define DUMP 5 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy (void ); int yyget_debug (void ); void yyset_debug (int debug_flag ); YY_EXTRA_TYPE yyget_extra (void ); void yyset_extra (YY_EXTRA_TYPE user_defined ); FILE *yyget_in (void ); void yyset_in (FILE * _in_str ); FILE *yyget_out (void ); void yyset_out (FILE * _out_str ); yy_size_t yyget_leng (void ); char *yyget_text (void ); int yyget_lineno (void ); void yyset_lineno (int _line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (void ); #else extern int yywrap (void ); #endif #endif #ifndef YY_NO_UNPUT static void yyunput (int c,char *buf_ptr ); #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ if ( yyleng > 0 ) \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \ (yytext[yyleng - 1] == '\n'); \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_load_buffer_state( ); } { #line 110 "./SSdict2ABdict.lex" /* Rules */ #line 899 "./SSdict2ABdict.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_current_state += YY_AT_BOL(); yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 148 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 161 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: /* rule 1 can match eol */ YY_RULE_SETUP #line 112 "./SSdict2ABdict.lex" { } YY_BREAK case 2: YY_RULE_SETUP #line 113 "./SSdict2ABdict.lex" { BEGIN TEXT; } YY_BREAK case 3: YY_RULE_SETUP #line 114 "./SSdict2ABdict.lex" { } YY_BREAK case 4: /* rule 4 can match eol */ YY_RULE_SETUP #line 115 "./SSdict2ABdict.lex" { BEGIN INITIAL; } YY_BREAK case 5: YY_RULE_SETUP #line 117 "./SSdict2ABdict.lex" { BEGIN NAME; printf("(\"%s", yytext); } YY_BREAK case 6: /* rule 6 can match eol */ YY_RULE_SETUP #line 118 "./SSdict2ABdict.lex" { printf("\")\n"); BEGIN INITIAL; } YY_BREAK case 7: YY_RULE_SETUP #line 119 "./SSdict2ABdict.lex" { BEGIN POST; printf("\" "); } YY_BREAK case 8: YY_RULE_SETUP #line 120 "./SSdict2ABdict.lex" { printf("%s", yytext); } YY_BREAK case 9: /* rule 9 can match eol */ YY_RULE_SETUP #line 122 "./SSdict2ABdict.lex" { printf(")\n"); BEGIN INITIAL; } YY_BREAK case 10: YY_RULE_SETUP #line 123 "./SSdict2ABdict.lex" { BEGIN ABET; spc=0; printf(" ((("); } YY_BREAK case 11: YY_RULE_SETUP #line 125 "./SSdict2ABdict.lex" { printf("jj"); } YY_BREAK case 12: YY_RULE_SETUP #line 126 "./SSdict2ABdict.lex" { printf("rb"); } YY_BREAK case 13: YY_RULE_SETUP #line 127 "./SSdict2ABdict.lex" { printf("nns"); } YY_BREAK case 14: YY_RULE_SETUP #line 128 "./SSdict2ABdict.lex" { printf("nn"); } YY_BREAK case 15: YY_RULE_SETUP #line 129 "./SSdict2ABdict.lex" { printf("nil"); } YY_BREAK case 16: YY_RULE_SETUP #line 130 "./SSdict2ABdict.lex" { printf("nnps"); } YY_BREAK case 17: YY_RULE_SETUP #line 131 "./SSdict2ABdict.lex" { printf("nnp"); } YY_BREAK case 18: YY_RULE_SETUP #line 132 "./SSdict2ABdict.lex" { printf("vb"); } YY_BREAK case 19: YY_RULE_SETUP #line 134 "./SSdict2ABdict.lex" { spc=0; printf(") %d) ((", stress); } YY_BREAK case 20: /* rule 20 can match eol */ YY_RULE_SETUP #line 135 "./SSdict2ABdict.lex" { spc=0; printf(") %d)))\n", stress); BEGIN INITIAL; } YY_BREAK case 21: YY_RULE_SETUP #line 136 "./SSdict2ABdict.lex" { spc=0; printf(") %d)))", stress); BEGIN DUMP; } YY_BREAK case 22: YY_RULE_SETUP #line 138 "./SSdict2ABdict.lex" { } YY_BREAK case 23: /* rule 23 can match eol */ YY_RULE_SETUP #line 139 "./SSdict2ABdict.lex" { printf("\n"); BEGIN INITIAL; } YY_BREAK case 24: YY_RULE_SETUP #line 141 "./SSdict2ABdict.lex" { stress=0; space(); printf("ae"); spc=1; } YY_BREAK case 25: YY_RULE_SETUP #line 142 "./SSdict2ABdict.lex" { stress=0; space(); printf("aa"); spc=1; } YY_BREAK case 26: YY_RULE_SETUP #line 143 "./SSdict2ABdict.lex" { stress=0; space(); printf("aa r"); spc=1; } YY_BREAK case 27: YY_RULE_SETUP #line 144 "./SSdict2ABdict.lex" { stress=0; space(); printf("ao"); spc=1; } YY_BREAK case 28: YY_RULE_SETUP #line 145 "./SSdict2ABdict.lex" { stress=0; space(); printf("ey"); spc=1; } YY_BREAK case 29: YY_RULE_SETUP #line 146 "./SSdict2ABdict.lex" { stress=0; space(); printf("b"); spc=1; } YY_BREAK case 30: YY_RULE_SETUP #line 147 "./SSdict2ABdict.lex" { stress=0; space(); printf("ch"); spc=1; } YY_BREAK case 31: YY_RULE_SETUP #line 148 "./SSdict2ABdict.lex" { stress=0; space(); printf("d"); spc=1; } YY_BREAK case 32: YY_RULE_SETUP #line 149 "./SSdict2ABdict.lex" { stress=0; space(); printf("eh"); spc=1; } YY_BREAK case 33: YY_RULE_SETUP #line 150 "./SSdict2ABdict.lex" { stress=0; space(); printf("iy"); spc=1; } YY_BREAK case 34: YY_RULE_SETUP #line 151 "./SSdict2ABdict.lex" { stress=0; space(); printf("eh"); spc=1; } YY_BREAK case 35: YY_RULE_SETUP #line 152 "./SSdict2ABdict.lex" { stress=0; space(); printf("eh r"); spc=1; } YY_BREAK case 36: YY_RULE_SETUP #line 153 "./SSdict2ABdict.lex" { stress=0; space(); printf("ih"); spc=1; } YY_BREAK case 37: YY_RULE_SETUP #line 154 "./SSdict2ABdict.lex" { stress=0; space(); printf("ih"); spc=1; } YY_BREAK case 38: YY_RULE_SETUP #line 155 "./SSdict2ABdict.lex" { stress=0; space(); printf("ih r"); spc=1; } YY_BREAK case 39: YY_RULE_SETUP #line 156 "./SSdict2ABdict.lex" { stress=0; space(); printf("ay"); spc=1; } YY_BREAK case 40: YY_RULE_SETUP #line 157 "./SSdict2ABdict.lex" { stress=0; space(); printf("f"); spc=1; } YY_BREAK case 41: YY_RULE_SETUP #line 158 "./SSdict2ABdict.lex" { stress=0; space(); printf("g"); spc=1; } YY_BREAK case 42: YY_RULE_SETUP #line 159 "./SSdict2ABdict.lex" { stress=0; space(); printf("hh"); spc=1; } YY_BREAK case 43: YY_RULE_SETUP #line 160 "./SSdict2ABdict.lex" { stress=0; space(); printf("jh"); spc=1; } YY_BREAK case 44: YY_RULE_SETUP #line 161 "./SSdict2ABdict.lex" { stress=0; space(); printf("k"); spc=1; } YY_BREAK case 45: YY_RULE_SETUP #line 162 "./SSdict2ABdict.lex" { stress=0; space(); printf("l"); spc=1; } YY_BREAK case 46: YY_RULE_SETUP #line 163 "./SSdict2ABdict.lex" { stress=0; space(); printf("m"); spc=1; } YY_BREAK case 47: YY_RULE_SETUP #line 164 "./SSdict2ABdict.lex" { stress=0; space(); printf("n"); spc=1; } YY_BREAK case 48: YY_RULE_SETUP #line 165 "./SSdict2ABdict.lex" { stress=0; space(); printf("ng"); spc=1; } YY_BREAK case 49: YY_RULE_SETUP #line 166 "./SSdict2ABdict.lex" { stress=0; space(); printf("aa"); spc=1; } YY_BREAK case 50: YY_RULE_SETUP #line 167 "./SSdict2ABdict.lex" { stress=0; space(); printf("ow"); spc=1; } YY_BREAK case 51: YY_RULE_SETUP #line 168 "./SSdict2ABdict.lex" { stress=0; space(); printf("ao r"); spc=1; } YY_BREAK case 52: YY_RULE_SETUP #line 169 "./SSdict2ABdict.lex" { stress=0; space(); printf("uw"); spc=1; } YY_BREAK case 53: YY_RULE_SETUP #line 170 "./SSdict2ABdict.lex" { stress=0; space(); printf("aw"); spc=1; } YY_BREAK case 54: YY_RULE_SETUP #line 171 "./SSdict2ABdict.lex" { stress=0; space(); printf("oy"); spc=1; } YY_BREAK case 55: YY_RULE_SETUP #line 172 "./SSdict2ABdict.lex" { stress=0; space(); printf("p"); spc=1; } YY_BREAK case 56: YY_RULE_SETUP #line 173 "./SSdict2ABdict.lex" { stress=0; space(); printf("r"); spc=1; } YY_BREAK case 57: YY_RULE_SETUP #line 174 "./SSdict2ABdict.lex" { stress=0; space(); printf("s"); spc=1; } YY_BREAK case 58: YY_RULE_SETUP #line 175 "./SSdict2ABdict.lex" { stress=0; space(); printf("sh"); spc=1; } YY_BREAK case 59: YY_RULE_SETUP #line 176 "./SSdict2ABdict.lex" { stress=0; space(); printf("t"); spc=1; } YY_BREAK case 60: YY_RULE_SETUP #line 177 "./SSdict2ABdict.lex" { stress=0; space(); printf("th"); spc=1; } YY_BREAK case 61: YY_RULE_SETUP #line 178 "./SSdict2ABdict.lex" { stress=0; space(); printf("dh"); spc=1; } YY_BREAK case 62: YY_RULE_SETUP #line 179 "./SSdict2ABdict.lex" { stress=0; space(); printf("ah"); spc=1; } YY_BREAK case 63: YY_RULE_SETUP #line 180 "./SSdict2ABdict.lex" { stress=0; space(); printf("ax"); spc=1; } YY_BREAK case 64: YY_RULE_SETUP #line 181 "./SSdict2ABdict.lex" { stress=0; space(); printf("er"); spc=1; } YY_BREAK case 65: YY_RULE_SETUP #line 182 "./SSdict2ABdict.lex" { stress=0; space(); printf("uh"); spc=1; } YY_BREAK case 66: YY_RULE_SETUP #line 183 "./SSdict2ABdict.lex" { stress=0; space(); printf("v"); spc=1; } YY_BREAK case 67: YY_RULE_SETUP #line 184 "./SSdict2ABdict.lex" { stress=0; space(); printf("w"); spc=1; } YY_BREAK case 68: YY_RULE_SETUP #line 185 "./SSdict2ABdict.lex" { stress=0; space(); printf("y"); spc=1; } YY_BREAK case 69: YY_RULE_SETUP #line 186 "./SSdict2ABdict.lex" { stress=0; space(); printf("z"); spc=1; } YY_BREAK case 70: YY_RULE_SETUP #line 187 "./SSdict2ABdict.lex" { stress=0; space(); printf("zh"); spc=1; } YY_BREAK case 71: YY_RULE_SETUP #line 189 "./SSdict2ABdict.lex" { stress=1; space(); printf("ae"); spc=1; } YY_BREAK case 72: YY_RULE_SETUP #line 190 "./SSdict2ABdict.lex" { stress=1; space(); printf("aa"); spc=1; } YY_BREAK case 73: YY_RULE_SETUP #line 191 "./SSdict2ABdict.lex" { stress=1; space(); printf("aa r"); spc=1; } YY_BREAK case 74: YY_RULE_SETUP #line 192 "./SSdict2ABdict.lex" { stress=1; space(); printf("ao"); spc=1; } YY_BREAK case 75: YY_RULE_SETUP #line 193 "./SSdict2ABdict.lex" { stress=1; space(); printf("ey"); spc=1; } YY_BREAK case 76: YY_RULE_SETUP #line 194 "./SSdict2ABdict.lex" { stress=1; space(); printf("b"); spc=1; } YY_BREAK case 77: YY_RULE_SETUP #line 195 "./SSdict2ABdict.lex" { stress=1; space(); printf("ch"); spc=1; } YY_BREAK case 78: YY_RULE_SETUP #line 196 "./SSdict2ABdict.lex" { stress=1; space(); printf("d"); spc=1; } YY_BREAK case 79: YY_RULE_SETUP #line 197 "./SSdict2ABdict.lex" { stress=1; space(); printf("eh"); spc=1; } YY_BREAK case 80: YY_RULE_SETUP #line 198 "./SSdict2ABdict.lex" { stress=1; space(); printf("iy"); spc=1; } YY_BREAK case 81: YY_RULE_SETUP #line 199 "./SSdict2ABdict.lex" { stress=1; space(); printf("eh"); spc=1; } YY_BREAK case 82: YY_RULE_SETUP #line 200 "./SSdict2ABdict.lex" { stress=1; space(); printf("eh r"); spc=1; } YY_BREAK case 83: YY_RULE_SETUP #line 201 "./SSdict2ABdict.lex" { stress=1; space(); printf("ih"); spc=1; } YY_BREAK case 84: YY_RULE_SETUP #line 202 "./SSdict2ABdict.lex" { stress=1; space(); printf("ih"); spc=1; } YY_BREAK case 85: YY_RULE_SETUP #line 203 "./SSdict2ABdict.lex" { stress=1; space(); printf("ih r"); spc=1; } YY_BREAK case 86: YY_RULE_SETUP #line 204 "./SSdict2ABdict.lex" { stress=1; space(); printf("ay"); spc=1; } YY_BREAK case 87: YY_RULE_SETUP #line 205 "./SSdict2ABdict.lex" { stress=1; space(); printf("f"); spc=1; } YY_BREAK case 88: YY_RULE_SETUP #line 206 "./SSdict2ABdict.lex" { stress=1; space(); printf("g"); spc=1; } YY_BREAK case 89: YY_RULE_SETUP #line 207 "./SSdict2ABdict.lex" { stress=1; space(); printf("hh"); spc=1; } YY_BREAK case 90: YY_RULE_SETUP #line 208 "./SSdict2ABdict.lex" { stress=1; space(); printf("jh"); spc=1; } YY_BREAK case 91: YY_RULE_SETUP #line 209 "./SSdict2ABdict.lex" { stress=1; space(); printf("k"); spc=1; } YY_BREAK case 92: YY_RULE_SETUP #line 210 "./SSdict2ABdict.lex" { stress=1; space(); printf("l"); spc=1; } YY_BREAK case 93: YY_RULE_SETUP #line 211 "./SSdict2ABdict.lex" { stress=1; space(); printf("m"); spc=1; } YY_BREAK case 94: YY_RULE_SETUP #line 212 "./SSdict2ABdict.lex" { stress=1; space(); printf("n"); spc=1; } YY_BREAK case 95: YY_RULE_SETUP #line 213 "./SSdict2ABdict.lex" { stress=1; space(); printf("ng"); spc=1; } YY_BREAK case 96: YY_RULE_SETUP #line 214 "./SSdict2ABdict.lex" { stress=1; space(); printf("aa"); spc=1; } YY_BREAK case 97: YY_RULE_SETUP #line 215 "./SSdict2ABdict.lex" { stress=1; space(); printf("ow"); spc=1; } YY_BREAK case 98: YY_RULE_SETUP #line 216 "./SSdict2ABdict.lex" { stress=1; space(); printf("ao r"); spc=1; } YY_BREAK case 99: YY_RULE_SETUP #line 217 "./SSdict2ABdict.lex" { stress=1; space(); printf("uw"); spc=1; } YY_BREAK case 100: YY_RULE_SETUP #line 218 "./SSdict2ABdict.lex" { stress=1; space(); printf("aw"); spc=1; } YY_BREAK case 101: YY_RULE_SETUP #line 219 "./SSdict2ABdict.lex" { stress=1; space(); printf("oy"); spc=1; } YY_BREAK case 102: YY_RULE_SETUP #line 220 "./SSdict2ABdict.lex" { stress=1; space(); printf("p"); spc=1; } YY_BREAK case 103: YY_RULE_SETUP #line 221 "./SSdict2ABdict.lex" { stress=1; space(); printf("r"); spc=1; } YY_BREAK case 104: YY_RULE_SETUP #line 222 "./SSdict2ABdict.lex" { stress=1; space(); printf("s"); spc=1; } YY_BREAK case 105: YY_RULE_SETUP #line 223 "./SSdict2ABdict.lex" { stress=1; space(); printf("sh"); spc=1; } YY_BREAK case 106: YY_RULE_SETUP #line 224 "./SSdict2ABdict.lex" { stress=1; space(); printf("t"); spc=1; } YY_BREAK case 107: YY_RULE_SETUP #line 225 "./SSdict2ABdict.lex" { stress=1; space(); printf("th"); spc=1; } YY_BREAK case 108: YY_RULE_SETUP #line 226 "./SSdict2ABdict.lex" { stress=1; space(); printf("dh"); spc=1; } YY_BREAK case 109: YY_RULE_SETUP #line 227 "./SSdict2ABdict.lex" { stress=1; space(); printf("ah"); spc=1; } YY_BREAK case 110: YY_RULE_SETUP #line 228 "./SSdict2ABdict.lex" { stress=1; space(); printf("ax"); spc=1; } YY_BREAK case 111: YY_RULE_SETUP #line 229 "./SSdict2ABdict.lex" { stress=1; space(); printf("er"); spc=1; } YY_BREAK case 112: YY_RULE_SETUP #line 230 "./SSdict2ABdict.lex" { stress=1; space(); printf("uh"); spc=1; } YY_BREAK case 113: YY_RULE_SETUP #line 231 "./SSdict2ABdict.lex" { stress=1; space(); printf("v"); spc=1; } YY_BREAK case 114: YY_RULE_SETUP #line 232 "./SSdict2ABdict.lex" { stress=1; space(); printf("w"); spc=1; } YY_BREAK case 115: YY_RULE_SETUP #line 233 "./SSdict2ABdict.lex" { stress=1; space(); printf("y"); spc=1; } YY_BREAK case 116: YY_RULE_SETUP #line 234 "./SSdict2ABdict.lex" { stress=1; space(); printf("z"); spc=1; } YY_BREAK case 117: YY_RULE_SETUP #line 235 "./SSdict2ABdict.lex" { stress=1; space(); printf("zh"); spc=1; } YY_BREAK case 118: YY_RULE_SETUP #line 237 "./SSdict2ABdict.lex" ECHO; YY_BREAK #line 1553 "./SSdict2ABdict.c" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(TEXT): case YY_STATE_EOF(NAME): case YY_STATE_EOF(POST): case YY_STATE_EOF(ABET): case YY_STATE_EOF(DUMP): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = (yytext_ptr); yy_size_t number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((int) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { yy_state_type yy_current_state; char *yy_cp; yy_current_state = (yy_start); yy_current_state += YY_AT_BOL(); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 148 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { int yy_is_jam; char *yy_cp = (yy_c_buf_p); YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 148 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 147); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT static void yyunput (int c, char * yy_bp ) { char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up yytext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ yy_size_t number_to_move = (yy_n_chars) + 2; char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ yy_size_t offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n'); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ); yyfree((void *) b ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { yy_size_t num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) { return yy_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) yyalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ yy_size_t yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param _line_number line number * */ void yyset_lineno (int _line_number ) { yylineno = _line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * _in_str ) { yyin = _in_str ; } void yyset_out (FILE * _out_str ) { yyout = _out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int _bdebug ) { yy_flex_debug = _bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return (void *) malloc( size ); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 237 "./SSdict2ABdict.lex" /* Subroutines */
the_stack_data/148576714.c
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2. * * 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. * * Test that the function: * int shmctl(int, int, struct shmid_ds *) * is declared. */ #include <sys/shm.h> typedef int (*shmctl_test)(int, int, struct shmid_ds *); int dummyfcn (void) { shmctl_test dummyvar; dummyvar = shmctl; return 0; }
the_stack_data/125139422.c
#include <stdbool.h> #include <string.h> /* greedy solution to only expand the last * we met */ bool isMatch(char *s, char *p) { int i = 0, j = 0, m = 0, n = 0; //n is the last * position while (s[i]) { if (p[j] == '?' || p[j] == s[i]) { ++i; ++j; } else if (p[j] == '*') { n = j++; m = i; } else if (p[n] == '*') { i = ++m; j = n + 1; } else return false; } while (p[j] == '*') ++j; return !p[j]; }
the_stack_data/1238573.c
#include <stdio.h> int main(void) { int n,i; scanf("%d",&n); getchar(); for(i=0;i<n;i++) { int count=0; int x; while((x=getchar())!='\n') if(x>='0'&&x<='9') count++; printf("%d\n",count); } return 0; }
the_stack_data/1171754.c
/* Test structures passed by value, including to a function with a variable-length argument list. This test is based on one contributed by Alan Modra. */ extern void struct_by_value_2_x (void); extern void exit (int); int fails; int main () { struct_by_value_2_x (); exit (0); }
the_stack_data/140981.c
/* { dg-options "-O1 -floop-parallelize-all" } */ double lagrange(const double x[], const double y[], long n, double xval) { long i, j; double yval = 0.; for( i=0; i < n; i++ ) { double l = 1.; for( j=0; j < n; j++ ) if( i != j ) l *= (xval-x[j])/(x[i]-x[j]); yval += y[i]*l; } return yval; }
the_stack_data/7950107.c
/* text version of maze 'mazefiles/binary/japan1990.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 japan1990_maz[] ={ 0x0E, 0x0A, 0x0A, 0x0A, 0x08, 0x0A, 0x09, 0x0E, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x08, 0x0A, 0x09, 0x0D, 0x0E, 0x0A, 0x0B, 0x05, 0x0F, 0x05, 0x0F, 0x04, 0x0A, 0x0A, 0x0A, 0x09, 0x05, 0x0F, 0x05, 0x04, 0x0A, 0x0A, 0x0A, 0x03, 0x0E, 0x02, 0x0A, 0x03, 0x0C, 0x0A, 0x0A, 0x03, 0x05, 0x0C, 0x01, 0x05, 0x0E, 0x08, 0x0A, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x03, 0x0E, 0x0A, 0x0A, 0x01, 0x05, 0x05, 0x04, 0x0A, 0x01, 0x0F, 0x05, 0x0C, 0x0A, 0x08, 0x0A, 0x0A, 0x08, 0x0A, 0x0B, 0x06, 0x01, 0x05, 0x07, 0x0F, 0x05, 0x0C, 0x01, 0x05, 0x0F, 0x05, 0x0C, 0x0A, 0x02, 0x0A, 0x08, 0x09, 0x05, 0x07, 0x0C, 0x0A, 0x01, 0x05, 0x05, 0x05, 0x0C, 0x03, 0x05, 0x0C, 0x0A, 0x09, 0x05, 0x05, 0x06, 0x09, 0x05, 0x0F, 0x05, 0x05, 0x05, 0x05, 0x05, 0x0C, 0x01, 0x05, 0x0D, 0x05, 0x07, 0x05, 0x0F, 0x05, 0x04, 0x0A, 0x01, 0x05, 0x05, 0x05, 0x05, 0x04, 0x03, 0x05, 0x07, 0x05, 0x0F, 0x04, 0x0A, 0x01, 0x05, 0x0C, 0x03, 0x05, 0x05, 0x05, 0x05, 0x05, 0x0D, 0x06, 0x0A, 0x03, 0x0D, 0x05, 0x0F, 0x05, 0x05, 0x05, 0x0F, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, 0x0A, 0x0A, 0x0A, 0x01, 0x04, 0x0A, 0x01, 0x05, 0x04, 0x0A, 0x02, 0x03, 0x05, 0x05, 0x06, 0x08, 0x0A, 0x08, 0x0B, 0x05, 0x05, 0x0D, 0x05, 0x05, 0x05, 0x0C, 0x0A, 0x0A, 0x02, 0x02, 0x0B, 0x05, 0x0D, 0x05, 0x0F, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, 0x0A, 0x08, 0x08, 0x0A, 0x0A, 0x03, 0x05, 0x04, 0x0A, 0x02, 0x01, 0x05, 0x05, 0x05, 0x06, 0x0A, 0x0A, 0x03, 0x04, 0x0A, 0x0A, 0x0A, 0x03, 0x05, 0x0E, 0x0B, 0x05, 0x07, 0x05, 0x06, 0x0A, 0x0A, 0x0A, 0x0A, 0x02, 0x0A, 0x0A, 0x0A, 0x0A, 0x02, 0x0A, 0x0A, 0x02, 0x0A, 0x03, }; /* end of mazefile */
the_stack_data/151705635.c
#include <stdlib.h> #include <string.h> #include <stdio.h> char ** split(char string[], int * num, char * sep) { char * pch; char ** out = 0; int i = 0; pch = strtok (string, sep ); while (pch != 0 ) { out = realloc(out, ( i + 1 ) * sizeof( char * )); out[i] = malloc( strlen(pch ) + 1 ); strcpy( out[i], pch ); ++i; pch = strtok (NULL, sep); } *num = i; return out; } int main() { char str[255] = "one, two, tree, four,five six"; int num = 0; int i = 0; char ** tokens = split( str, &num, " ,"); for( i = 0; i < num; ++i ) printf("%s\n", tokens[i] ); for( i = 0; i < num; ++i ) free( tokens[i] ); free(tokens); }
the_stack_data/14200716.c
#include<stdio.h> int main (){ //variavรฉis int vetor[20], soma = 0; for (int i = 0; i < 20; i++) { printf("Informe o nรบmero para o vetor %d/20: ", (i+1)); scanf("%d", &vetor[i]); soma = soma + vetor[i]; } printf("A soma do vetor รฉ %d", soma); }
the_stack_data/217962.c
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> int main(int argc, char **argv) { if (argc <= 1) { printf("Too few arguments\n"); exit(EXIT_FAILURE); } FILE *file = fopen(argv[1], "r"); if (!file) { printf("%s\n", strerror(errno)); exit(EXIT_FAILURE); } char c; while ((c = fgetc(file)) != EOF) printf("%c", c); fclose(file); return 0; }
the_stack_data/36074282.c
#include<stdio.h> void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } int partition (int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j <= high- 1; j++) { if (arr[j] <= pivot) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int n; printf("\nEnter the no of elements : "); scanf("%d",&n); int arr[n]; printf("\nEnter the elements : "); for(int i=0;i<n;i++) scanf("%d",&arr[i]); quickSort(arr, 0, n-1); printf("Sorted array: \n"); printArray(arr, n); return 0; }
the_stack_data/18078.c
/* * Copyright 2014 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* * Stub routine for `sched_get_priority_max' for porting support. */ #include <errno.h> #include <sched.h> int sched_get_priority_max(int policy) { errno = ENOSYS; return -1; }
the_stack_data/150144214.c
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #define BufferSize 500 #define MaxLineSize 250 #define PrintLineCount 24 int main(int argc, char *argv[]) { char pidIndex[10]; int pidValue = getpid(); sprintf(pidIndex, "%d", pidValue); char ppidIndex[10]; int ppidValue = getppid(); sprintf(ppidIndex, "%d", ppidValue); char *pidIndexParent = argv[2]; // Parent รผzerinden parametre olarak gรถnderilen pid id'ler alฤฑnฤฑr. char *ppidIndexParent = argv[3]; // Process รงalฤฑลŸan process id alฤฑnฤฑr. if (strcmp(pidIndex, pidIndexParent) != 0 && strcmp(ppidIndex, ppidIndexParent) != 0) // Parent ve child process id'ler kontrol edilir. { printf("myMore dosyasi parenti olmadan calisamaz...\n"); } else { int readEnd = atoi(argv[1]); char readMessage[MaxLineSize][BufferSize]; read(readEnd, &readMessage, PrintLineCount * BufferSize); for (int i = 0; i < PrintLineCount; ++i) { printf("%s", readMessage[i]); } close(readEnd); return 0; } }
the_stack_data/212644213.c
/* * Copyright (c) 2013, Juniper Networks, Inc. * All rights reserved. * * You may distribute under the terms of : * * the BSD 2-Clause license * * Any patches released for this software are to be released under these * same license terms. * * BSD 2-Clause license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ int host_signal_to_gdb(int sig) { int ret = -1; return ret; } int host_signal_from_gdb(int gdb) { int ret = -1; return ret; }
the_stack_data/247017581.c
/** * @file gl-threads.c * @brief Glue based doubly linked-list * @details * In traditional a doubly linked-list each node will have a left and right * pointer and a pointer to the data, so the structure of the node will contain * 3 data members(next, prev, data). In Glue based doubly linked-list there will * only be 2 data members left and right pointers. As for the data, it will be * glued on top of the node. * * Illustration * ------------- * Traditional doubly linked-list: * _____________ _____________ * ___ | application | ___| application | * | | data | | | data | * | |_____________| | |_____________| * __________|_________ __________|_________ * | prev | data | next |____________| prev | data | next | * |______|______|______| |______|______|______| * * * Glue based doubly linked-list: * _____________ _____________ * | application | | application | * | data | | data | * |_____________| |_____________| * | prev | next |___________| prev | next | * |______|______| |______|______| * * @author [Ashborn-SM](https://github.com/Ashborn-SM) */ #include <stdlib.h> #include <stdio.h> #include <string.h> #define HEAD(list) (list->head) #define OFFSETOF(structure, field) (long)&((structure*)0)->field #define POP_FRONT(list, structure, offset){ \ glthread_node* _cur = HEAD(list), *temp = HEAD(list)->next; \ structure* per = (structure*)((char*)_cur - offset); \ free(per); \ HEAD(list) = temp; \ } #define ITERATE_GL_THREADS_BEGIN(lstptr, struct_type, ptr) \ { \ glthread_node *_glnode = NULL, *_next = NULL; \ for(_glnode = lstptr->head; _glnode; _glnode = _next){ \ _next = _glnode->next; \ ptr = (struct_type *)((char *)_glnode - lstptr->offset); #define END }} /** * @struct glthread_node * @brief node for the glue based doubly linked list */ typedef struct glthread_node_{ struct glthread_node_* next; struct glthread_node_* prev; }glthread_node; /** * @struct gldll * @brief the doubly linked-list */ typedef struct{ glthread_node* head; unsigned int offset; }gldll; /** * @brief initialise the node * @details set the node members to NULL * @param node linked-list node */ void init_glthread_node(glthread_node* node){ node->next = NULL; node->prev = NULL; } /** * @brief initialise the linked-list * @details set the head and offset * @param list linked-list * @param offset offset of the data member */ void init_glthread_list(gldll* list, unsigned int offset){ list->head = NULL; list->offset = offset; } /** * @brief insertion of node * @details insert the node at the front of the list * @param list linked-list * @param node node to be inserted */ void glthread_pushfront(gldll* list, glthread_node* node){ glthread_node* cur = HEAD(list); if(cur == NULL){ HEAD(list) = node; return; } cur->prev = node; node->next = cur; HEAD(list) = node; } /** * @struct person * @brief a structure with attributes of a person */ typedef struct{ char name[30]; int age, weight, height; glthread_node glnode; }person; /** * @brief print the details of the person * @param per person structure */ void print(person* per){ printf("Name: %s\n", per->name); printf("Height: %i\n", per->height); printf("Age: %i\n", per->age); printf("Weight: %i\n", per->weight); printf("------------\n"); } /** * @brief allocate memory * @returns memory with type person */ person* allocate(){ person* new = malloc(sizeof(*new)); if(new == NULL){ printf("Allocation Failure"); exit(0); } return new; } /** * @brief test the program * @param list linked-list */ void test(gldll* list){ char passed[10] = "[PASSED]:\0"; char failed[10] = "[FAILED]:\0"; char expected[9] = "EXPECTED\0"; char returned[9] = "RETURNED\0"; glthread_node* cur = HEAD(list); person* per = NULL; ITERATE_GL_THREADS_BEGIN(list, person, per){ if(strcmp(per->name, "rohit") == 0){ printf("%s: %s -> %s, %s -> %s\n", passed, expected, "rohit", returned, per->name); } else{ printf("%s: %s -> %s, %s -> %s\n", failed, expected, "rohit", returned, per->name); } if(per->age == 23){ printf("%s: %s -> %i, %s -> %i\n", passed, expected, 23, returned, per->age); } else{ printf("%s: %s -> %i, %s -> %i\n", failed, expected, 23, returned, per->age); } if(per->height == 174){ printf("%s: %s -> %i, %s -> %i\n", passed, expected, 174, returned, per->height); } else{ printf("%s: %s -> %i, %s -> %i\n", failed, expected, 174, returned, per->height); } if(per->weight == 67){ printf("%s: %s -> %i, %s -> %i\n", passed, expected, 67, returned, per->weight); } else{ printf("%s: %s -> %i, %s -> %i\n", failed, expected, 67, returned, per->weight); } break; }END; } int main(){ gldll* list = malloc(sizeof(*list)); if(list == NULL){ printf("Allocation Failure"); exit(0); } person* rahul = allocate(); person* rohit = allocate(); strcpy(rahul->name, "rahul"); strcpy(rohit->name, "rohit"); rahul->age = 19; rohit->age = 23; rahul->height = 170; rohit->height = 174; rahul->weight = 60; rohit->weight = 67; init_glthread_list(list, OFFSETOF(person, glnode)); init_glthread_node(&(rahul->glnode)); init_glthread_node(&(rohit->glnode)); glthread_pushfront(list, &(rohit->glnode)); glthread_pushfront(list, &(rahul->glnode)); person* temp = NULL; ITERATE_GL_THREADS_BEGIN(list, person, temp){ // uncomment the below line to print the details of the person print(temp); }END; /* Output: Name: rahul Height: 170 Age:19 Weight: 60 ------------- Name: rohit Height: 174 Age: 23 Weight: 77 ------------- */ POP_FRONT(list, person, OFFSETOF(person, glnode)); test(list); }
the_stack_data/103265625.c
/* Verify that the scheduler does not discard the lexical block. */ /* { dg-do compile } */ /* { dg-options "-dA" } */ /* { dg-final { scan-assembler "xyzzy" } } */ long foo(long p) { { long xyzzy = 0; if (p) xyzzy = 2; return xyzzy; } }
the_stack_data/111641.c
/* * UFC-crypt: ultra fast crypt(3) implementation * * Copyright (C) 1991, 1992, 1993, 1996 Free Software Foundation, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with the GNU C Library; see the file COPYING.LIB. If not, * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * @(#)ufc.c 2.7 9/10/96 * * Stub main program for debugging * and benchmarking. * */ #include <stdio.h> char *crypt(); main(argc, argv) int argc; char **argv; { char *s; unsigned long i,iterations; if(argc != 2) { fprintf(stderr, "usage: ufc iterations\n"); exit(1); } argv++; iterations = atoi(*argv); printf("ufc: running %d iterations\n", iterations); for(i=0; i<iterations; i++) s=crypt("foob","ar"); if(strcmp(s, "arlEKn0OzVJn.") == 0) printf("OK\n"); else { printf("wrong result: %s!!\n", s); exit(1); } exit(0); }
the_stack_data/136107.c
#include <stdio.h> typedef struct Point { int x; int y; } Point; void test(int a, int b) { printf("Test: %d %d\n", a, b); } void wooh(int a, int b) __attribute__((alias("test"))); int main(int argc, char **argv) { Point point = {123, 321}; point.x = 5; printf("Point: %d %d\n", point.x, point.y); test(123, 321); wooh(321, 123); return 0; }
the_stack_data/119078.c
#include <stdio.h> int singleNumber(int* nums, int numsSize) { int i; int ans = 0; for ( i = 0; i < numsSize; i++ ) ans ^= nums[i]; return ans; } int main() { int arr[] = {3,4,5,4,5,3,7,7,2}; printf("%d\n", singleNumber(arr, sizeof(arr)/sizeof(arr[0]))); return 0; }
the_stack_data/922797.c
#include <stdlib.h> int main () { int *x = (int *) malloc (sizeof (int)); int *y = (int *) malloc (sizeof (int)); *x = 0; *y = 0; if (nondet ()) { x = y; } *x = 1; if (*x == *y) { csolve_assert (*x == *y); } return 0; }
the_stack_data/140764305.c
/* { dg-require-effective-target untyped_assembly } */ foo (a, b, c, d, e, f, g, h, i) { return foo () + i; }
the_stack_data/276691.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strlowcase.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cado-car <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/14 23:11:20 by cado-car #+# #+# */ /* Updated: 2021/06/14 23:11:21 by cado-car ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_strlowcase(char *str) { int i; i = 0; while (str[i] != '\0') { if ((str[i] >= 'A') && (str[i] <= 'Z')) str[i] += 'a' - 'A'; i++; } return (str); }
the_stack_data/242330526.c
// 3.C program to find the number occurring odd number of times? /*Pass these test cases. 1) Input: 10,20,30,40,10,20,30 2)Input:1,4,7,2,4,7,1,2,7 */ #include <stdio.h> int oddOccurrence(int arr[], int arr_size) { for (int i = 0; i < arr_size; i++) { int count = 0; for (int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return 0; } int main() { int arr[10]; for(int i = 0; i < 10;i++) { scanf("%d", &arr[i]); } int n = sizeof(arr) / sizeof(arr[0]); printf("%d", oddOccurrence(arr, n)); return 0; } /* (1) Input: 10 20 30 40 10 20 30 Output: 40 (2) Input: 1 4 7 2 4 7 1 2 7 Output:7 */
the_stack_data/37107.c
#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char input; while(1) { fflush(stdin); printf("่ฏท่พ“ๅ…ฅไธ€ไธชๅญ—็ฌฆ:\n"); input = getchar(); getchar();//ๆถˆ้™คๆข่กŒๆˆ–่€…ๅ›ž่ฝฆ //scanf("%c",&input); printf("%c %sๆ•ฐๅญ—\n",input,isdigit(input)?"ๆ˜ฏ":"ไธๆ˜ฏ"); } return 0; }
the_stack_data/98945.c
// // client10.c // LearnSocket // // Created by Zhang Yuanming on 3/8/18. // Copyright ยฉ 2018 HansonStudio. All rights reserved. // #include <stdio.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <stdlib.h> #include <errno.h> #include <netinet/in.h> #include <unistd.h> #include <string.h> #define ERR_EXIT(m) \ do \ { \ perror(m); \ exit(EXIT_FAILURE); \ } while(0) ssize_t recv_peak(int sockfd, void *buf, size_t len) { while (1) { int ret = recv(sockfd, buf, len, MSG_PEEK); if (ret == -1 && errno == EINTR) { continue; } return ret; } } // ไธบไบ†่งฃๅ†ณ็ฒ˜ๅŒ…้—ฎ้ข˜ ssize_t writen(int fd, const void *buf, size_t count) { size_t nleft = count; ssize_t nwriten; char *bufp = (char *)buf; while (nleft > 0) { if ((nwriten = write(fd, bufp, nleft)) < 0) { if (errno == EINTR) { continue; } else { return -1; } } else if (nwriten == 0) { continue; } bufp += nwriten; nleft -= nwriten; } return count; } // ไธบไบ†่งฃๅ†ณ็ฒ˜ๅŒ…้—ฎ้ข˜ ssize_t readn(int fd, const void *buf, size_t count) { size_t nleft = count; ssize_t nreadn; char *bufp = (char *)buf; while (nleft > 0) { if ((nreadn = read(fd, bufp, nleft)) < 0) { if (errno == EINTR) { continue; } else if (nreadn == 0) { continue; } else { return -1; } } bufp += nreadn; nleft -= nreadn; } return count; } // ่ฏปๅ–ไธ€่กŒๆ•ฐๆฎไธบไธ€ๆกไฟกๆฏ,่งฃๅ†ณ็ฒ˜ๅŒ…้—ฎ้ข˜็š„ไธ€ไธชๆ–นๆณ• ssize_t readline(int sockfd, void *buf, size_t maxline) { int ret; int nread; char *bufp = buf; int nleft = maxline; while (1) { ret = recv_peak(sockfd, bufp, nleft); if (ret < 0) { return ret; } else if (ret == 0) { return ret; } nread = ret; int i; for (i = 0; i < nread; i++) { if (bufp[i] == '\n') { ret = readn(sockfd, bufp, i+1); if (ret != i+1) { exit(EXIT_FAILURE); } return ret; } } if (nread > nleft) { exit(EXIT_FAILURE); } nleft -= nread; ret = readn(sockfd, bufp, nread); if (ret != nread) { exit(EXIT_FAILURE); } bufp += nread; } return -1; } void echo_cli(int sock) { char sendbuf[1024] = {0}; char recvbuf[1024] = {0}; while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL) { writen(sock, sendbuf, strlen(sendbuf)); int ret = readline(sock, recvbuf, sizeof(recvbuf)); if (ret == -1) { ERR_EXIT("readline"); } else if (ret == 0) { printf("client close\n"); break; } fputs(recvbuf, stdout); printf("reset...."); memset(sendbuf, 0, sizeof(sendbuf)); memset(recvbuf, 0, sizeof(recvbuf)); } close(sock); } // gcc -Wall -g main.c -o main int main(int argc, const char * argv[]) { int sock[5] = {0}; int i; for (i = 0; i < 5; i++) { if ((sock[i] = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { ERR_EXIT("socket"); } struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if (connect(sock[i], (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { ERR_EXIT("connect"); } struct sockaddr_in localaddr; socklen_t addrlen = sizeof(localaddr); if (getsockname(sock[i], (struct sockaddr*)&localaddr, &addrlen) < 0) { ERR_EXIT("getsockname"); } printf("ip=%s port=%d\n", inet_ntoa(localaddr.sin_addr), ntohs(localaddr.sin_port)); } echo_cli(sock[0]); return 0; }
the_stack_data/10641.c
#include <unistd.h> int issetugid(void) { return 0; }
the_stack_data/268455.c
/*- * Copyright (c) 1992, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint static char copyright[] = "@(#) Copyright (c) 1992, 1993, 1994\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint static char sccsid[] = "@(#)dump.c 8.1 (Berkeley) 8/31/94"; #endif /* not lint */ #include <ctype.h> #include <stdio.h> static void parse(fp) FILE *fp; { int ch, s1, s2, s3; #define TESTD(s) { \ if ((s = getc(fp)) == EOF) \ return; \ if (!isdigit(s)) \ continue; \ } #define TESTP { \ if ((ch = getc(fp)) == EOF) \ return; \ if (ch != '|') \ continue; \ } #define MOVEC(t) { \ do { \ if ((ch = getc(fp)) == EOF) \ return; \ } while (ch != (t)); \ } for (;;) { MOVEC('"'); TESTD(s1); TESTD(s2); TESTD(s3); TESTP; putchar('"'); putchar(s1); putchar(s2); putchar(s3); putchar('|'); for (;;) { /* dump to end quote. */ if ((ch = getc(fp)) == EOF) return; putchar(ch); if (ch == '"') break; if (ch == '\\') { if ((ch = getc(fp)) == EOF) return; putchar(ch); } } putchar('\n'); } } int main(argc, argv) int argc; char *argv[]; { FILE *fp; for (; *argv != NULL; ++argv) { if ((fp = fopen(*argv, "r")) == NULL) { perror(*argv); return (1); } parse(fp); (void)fclose(fp); } return (0); }
the_stack_data/121672.c
// Copyright (c) Cesanta Software Limited // All rights reserved. // This program is used to pack arbitrary data into a C binary. It takes // a list of files as an input, and produces a .c data file that contains // contents of all these files as a collection of byte arrays. // // Usage: // 1. Compile this file: // cc -o pack pack.c // // 2. Convert list of files into single .c: // ./pack file1.data file2.data > fs.c // // 3. In your application code, you can access files using this function: // const char *mg_unpack(const char *file_name, size_t *size); // // 4. Build your app with fs.c: // cc -o my_app my_app.c fs.c #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> static const char *code = "const char *mg_unlist(size_t no) {\n" " return packed_files[no].name;\n" "}\n" "const char *mg_unpack(const char *name, size_t *size, time_t *mtime) {\n" " const struct packed_file *p;\n" " for (p = packed_files; p->name != NULL; p++) {\n" " if (strcmp(p->name, name) != 0) continue;\n" " if (size != NULL) *size = p->size - 1;\n" " if (mtime != NULL) *mtime = p->mtime;\n" " return (const char *) p->data;\n" " }\n" " return NULL;\n" "}\n"; int main(int argc, char *argv[]) { int i, j, ch; const char *zip_cmd = NULL, *strip_prefix = ""; printf("%s", "#include <stddef.h>\n"); printf("%s", "#include <string.h>\n"); printf("%s", "#include <time.h>\n"); printf("%s", "\n"); for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-z") == 0 && i + 1 < argc) { zip_cmd = argv[++i]; } else if (strcmp(argv[i], "-s") == 0) { strip_prefix = argv[++i]; } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { fprintf(stderr, "Usage: %s [-z ZIP_CMD] [-s STRIP_PREFIX] files...\n", argv[0]); exit(EXIT_FAILURE); } else { char ascii[12], cmd[2048]; FILE *fp; if (zip_cmd == NULL) { fp = fopen(argv[i], "rb"); } else { snprintf(cmd, sizeof(cmd), "%s %s", zip_cmd, argv[i]); fp = popen(cmd, "r"); } if (fp == NULL) { fprintf(stderr, "Cannot open [%s]: %s\n", zip_cmd ? cmd : argv[i], strerror(errno)); exit(EXIT_FAILURE); } printf("static const unsigned char v%d[] = {\n", i); for (j = 0; (ch = fgetc(fp)) != EOF; j++) { if (j == (int) sizeof(ascii)) { printf(" // %.*s\n", j, ascii); j = 0; } ascii[j] = (char) ((ch >= ' ' && ch <= '~' && ch != '\\') ? ch : '.'); printf(" %3u,", ch); } // Append zero byte at the end, to make text files appear in memory // as nul-terminated strings. // printf(" 0 // %.*s\n", (int) sizeof(ascii), ascii); printf(" 0 // %.*s\n};\n", j, ascii); if (zip_cmd == NULL) fclose(fp); if (zip_cmd != NULL) pclose(fp); } } printf("%s", "\nstatic const struct packed_file {\n"); printf("%s", " const char *name;\n"); printf("%s", " const unsigned char *data;\n"); printf("%s", " size_t size;\n"); printf("%s", " time_t mtime;\n"); printf("%s", " int zipped;\n"); printf("%s", "} packed_files[] = {\n"); for (i = 1; i < argc; i++) { struct stat st; const char *name = argv[i]; size_t n = strlen(strip_prefix); if (strcmp(argv[i], "-z") == 0 || strcmp(argv[i], "-s") == 0) { i++; continue; } stat(argv[i], &st); if (strncmp(name, strip_prefix, n) == 0) name += n; printf(" {\"/%s\", v%d, sizeof(v%d), %lu, %d},\n", name, i, i, st.st_mtime, zip_cmd == NULL ? 0 : 1); } printf("%s", " {NULL, NULL, 0, 0, 0}\n"); printf("%s", "};\n\n"); printf("%s", code); return EXIT_SUCCESS; }
the_stack_data/106134.c
/* $NetBSD: _ftello.c,v 1.5 2009/10/21 01:07:45 snj Exp $ */ /* * Copyright (c) 1996 Christos Zoulas. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> #if defined(LIBC_SCCS) && !defined(lint) __RCSID("$NetBSD: _ftello.c,v 1.5 2009/10/21 01:07:45 snj Exp $"); #endif /* LIBC_SCCS and not lint */ #if defined(__indr_reference) __indr_reference(_ftello, ftello) #else #include <stdio.h> off_t _ftello(FILE *); off_t ftello(FILE *stream) { return _ftello(stream); } #endif
the_stack_data/31388139.c
/* { dg-do run } */ /* { dg-options "-fsanitize=null -fno-sanitize-recover=null -w" } */ /* { dg-shouldfail "ubsan" } */ struct S { int i; long long j; long long m; }; union U { int k; struct S l; }; __attribute__((noinline, noclone)) int foo (struct S s) { return s.i + s.j + s.m; } __attribute__((noinline, noclone)) int bar (union U *u) { foo (u->l); } union U v; int main (void) { union U *u = 0; asm volatile ("" : "+r" (u) : "r" (&v) : "memory"); return bar (u); } /* { dg-output "member access within null pointer of type 'union U'" } */
the_stack_data/14199044.c
/* * Copyright (c) 2009 by Martin Fuzzey * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* this file is part of imx21-hcd.c */ #ifndef DEBUG static inline void create_debug_files(struct imx21 *imx21) { } static inline void remove_debug_files(struct imx21 *imx21) { } static inline void debug_urb_submitted(struct imx21 *imx21, struct urb *urb) {} static inline void debug_urb_completed(struct imx21 *imx21, struct urb *urb, int status) {} static inline void debug_urb_unlinked(struct imx21 *imx21, struct urb *urb) {} static inline void debug_urb_queued_for_etd(struct imx21 *imx21, struct urb *urb) {} static inline void debug_urb_queued_for_dmem(struct imx21 *imx21, struct urb *urb) {} static inline void debug_etd_allocated(struct imx21 *imx21) {} static inline void debug_etd_freed(struct imx21 *imx21) {} static inline void debug_dmem_allocated(struct imx21 *imx21, int size) {} static inline void debug_dmem_freed(struct imx21 *imx21, int size) {} static inline void debug_isoc_submitted(struct imx21 *imx21, int frame, struct td *td) {} static inline void debug_isoc_completed(struct imx21 *imx21, int frame, struct td *td, int cc, int len) {} #else #include <linux/debugfs.h> #include <linux/seq_file.h> static const char *dir_labels[] = { "TD 0", "OUT", "IN", "TD 1" }; static const char *speed_labels[] = { "Full", "Low" }; static const char *format_labels[] = { "Control", "ISO", "Bulk", "Interrupt" }; static inline struct debug_stats *stats_for_urb(struct imx21 *imx21, struct urb *urb) { return usb_pipeisoc(urb->pipe) ? &imx21->isoc_stats : &imx21->nonisoc_stats; } static void debug_urb_submitted(struct imx21 *imx21, struct urb *urb) { stats_for_urb(imx21, urb)->submitted++; } static void debug_urb_completed(struct imx21 *imx21, struct urb *urb, int st) { if (st) stats_for_urb(imx21, urb)->completed_failed++; else stats_for_urb(imx21, urb)->completed_ok++; } static void debug_urb_unlinked(struct imx21 *imx21, struct urb *urb) { stats_for_urb(imx21, urb)->unlinked++; } static void debug_urb_queued_for_etd(struct imx21 *imx21, struct urb *urb) { stats_for_urb(imx21, urb)->queue_etd++; } static void debug_urb_queued_for_dmem(struct imx21 *imx21, struct urb *urb) { stats_for_urb(imx21, urb)->queue_dmem++; } static inline void debug_etd_allocated(struct imx21 *imx21) { imx21->etd_usage.maximum = max( ++(imx21->etd_usage.value), imx21->etd_usage.maximum); } static inline void debug_etd_freed(struct imx21 *imx21) { imx21->etd_usage.value--; } static inline void debug_dmem_allocated(struct imx21 *imx21, int size) { imx21->dmem_usage.value += size; imx21->dmem_usage.maximum = max( imx21->dmem_usage.value, imx21->dmem_usage.maximum); } static inline void debug_dmem_freed(struct imx21 *imx21, int size) { imx21->dmem_usage.value -= size; } static void debug_isoc_submitted(struct imx21 *imx21, int frame, struct td *td) { struct debug_isoc_trace *trace = &imx21->isoc_trace[ imx21->isoc_trace_index++]; imx21->isoc_trace_index %= ARRAY_SIZE(imx21->isoc_trace); trace->schedule_frame = td->frame; trace->submit_frame = frame; trace->request_len = td->len; trace->td = td; } static inline void debug_isoc_completed(struct imx21 *imx21, int frame, struct td *td, int cc, int len) { struct debug_isoc_trace *trace, *trace_failed; int i; int found = 0; trace = imx21->isoc_trace; for (i = 0; i < ARRAY_SIZE(imx21->isoc_trace); i++, trace++) { if (trace->td == td) { trace->done_frame = frame; trace->done_len = len; trace->cc = cc; trace->td = NULL; found = 1; break; } } if (found && cc) { trace_failed = &imx21->isoc_trace_failed[ imx21->isoc_trace_index_failed++]; imx21->isoc_trace_index_failed %= ARRAY_SIZE( imx21->isoc_trace_failed); *trace_failed = *trace; } } static char *format_ep(struct usb_host_endpoint *ep, char *buf, int bufsize) { if (ep) snprintf(buf, bufsize, "ep_%02x (type:%02X kaddr:%p)", ep->desc.bEndpointAddress, usb_endpoint_type(&ep->desc), ep); else snprintf(buf, bufsize, "none"); return buf; } static char *format_etd_dword0(u32 value, char *buf, int bufsize) { snprintf(buf, bufsize, "addr=%d ep=%d dir=%s speed=%s format=%s halted=%d", value & 0x7F, (value >> DW0_ENDPNT) & 0x0F, dir_labels[(value >> DW0_DIRECT) & 0x03], speed_labels[(value >> DW0_SPEED) & 0x01], format_labels[(value >> DW0_FORMAT) & 0x03], (value >> DW0_HALTED) & 0x01); return buf; } static int debug_status_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; int etds_allocated = 0; int etds_sw_busy = 0; int etds_hw_busy = 0; int dmem_blocks = 0; int queued_for_etd = 0; int queued_for_dmem = 0; unsigned int dmem_bytes = 0; int i; struct etd_priv *etd; u32 etd_enable_mask; unsigned long flags; struct imx21_dmem_area *dmem; struct ep_priv *ep_priv; spin_lock_irqsave(&imx21->lock, flags); etd_enable_mask = readl(imx21->regs + USBH_ETDENSET); for (i = 0, etd = imx21->etd; i < USB_NUM_ETD; i++, etd++) { if (etd->alloc) etds_allocated++; if (etd->urb) etds_sw_busy++; if (etd_enable_mask & (1<<i)) etds_hw_busy++; } list_for_each_entry(dmem, &imx21->dmem_list, list) { dmem_bytes += dmem->size; dmem_blocks++; } list_for_each_entry(ep_priv, &imx21->queue_for_etd, queue) queued_for_etd++; list_for_each_entry(etd, &imx21->queue_for_dmem, queue) queued_for_dmem++; spin_unlock_irqrestore(&imx21->lock, flags); seq_printf(s, "Frame: %d\n" "ETDs allocated: %d/%d (max=%d)\n" "ETDs in use sw: %d\n" "ETDs in use hw: %d\n" "DMEM alocated: %d/%d (max=%d)\n" "DMEM blocks: %d\n" "Queued waiting for ETD: %d\n" "Queued waiting for DMEM: %d\n", readl(imx21->regs + USBH_FRMNUB) & 0xFFFF, etds_allocated, USB_NUM_ETD, imx21->etd_usage.maximum, etds_sw_busy, etds_hw_busy, dmem_bytes, DMEM_SIZE, imx21->dmem_usage.maximum, dmem_blocks, queued_for_etd, queued_for_dmem); return 0; } static int debug_dmem_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; struct imx21_dmem_area *dmem; unsigned long flags; char ep_text[40]; spin_lock_irqsave(&imx21->lock, flags); list_for_each_entry(dmem, &imx21->dmem_list, list) seq_printf(s, "%04X: size=0x%X " "ep=%s\n", dmem->offset, dmem->size, format_ep(dmem->ep, ep_text, sizeof(ep_text))); spin_unlock_irqrestore(&imx21->lock, flags); return 0; } static int debug_etd_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; struct etd_priv *etd; char buf[60]; u32 dword; int i, j; unsigned long flags; spin_lock_irqsave(&imx21->lock, flags); for (i = 0, etd = imx21->etd; i < USB_NUM_ETD; i++, etd++) { int state = -1; struct urb_priv *urb_priv; if (etd->urb) { urb_priv = etd->urb->hcpriv; if (urb_priv) state = urb_priv->state; } seq_printf(s, "etd_num: %d\n" "ep: %s\n" "alloc: %d\n" "len: %d\n" "busy sw: %d\n" "busy hw: %d\n" "urb state: %d\n" "current urb: %p\n", i, format_ep(etd->ep, buf, sizeof(buf)), etd->alloc, etd->len, etd->urb != NULL, (readl(imx21->regs + USBH_ETDENSET) & (1 << i)) > 0, state, etd->urb); for (j = 0; j < 4; j++) { dword = etd_readl(imx21, i, j); switch (j) { case 0: format_etd_dword0(dword, buf, sizeof(buf)); break; case 2: snprintf(buf, sizeof(buf), "cc=0X%02X", dword >> DW2_COMPCODE); break; default: *buf = 0; break; } seq_printf(s, "dword %d: submitted=%08X cur=%08X [%s]\n", j, etd->submitted_dwords[j], dword, buf); } seq_printf(s, "\n"); } spin_unlock_irqrestore(&imx21->lock, flags); return 0; } static void debug_statistics_show_one(struct seq_file *s, const char *name, struct debug_stats *stats) { seq_printf(s, "%s:\n" "submitted URBs: %lu\n" "completed OK: %lu\n" "completed failed: %lu\n" "unlinked: %lu\n" "queued for ETD: %lu\n" "queued for DMEM: %lu\n\n", name, stats->submitted, stats->completed_ok, stats->completed_failed, stats->unlinked, stats->queue_etd, stats->queue_dmem); } static int debug_statistics_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; unsigned long flags; spin_lock_irqsave(&imx21->lock, flags); debug_statistics_show_one(s, "nonisoc", &imx21->nonisoc_stats); debug_statistics_show_one(s, "isoc", &imx21->isoc_stats); seq_printf(s, "unblock kludge triggers: %lu\n", imx21->debug_unblocks); spin_unlock_irqrestore(&imx21->lock, flags); return 0; } static void debug_isoc_show_one(struct seq_file *s, const char *name, int index, struct debug_isoc_trace *trace) { seq_printf(s, "%s %d:\n" "cc=0X%02X\n" "scheduled frame %d (%d)\n" "submitted frame %d (%d)\n" "completed frame %d (%d)\n" "requested length=%d\n" "completed length=%d\n\n", name, index, trace->cc, trace->schedule_frame, trace->schedule_frame & 0xFFFF, trace->submit_frame, trace->submit_frame & 0xFFFF, trace->done_frame, trace->done_frame & 0xFFFF, trace->request_len, trace->done_len); } static int debug_isoc_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; struct debug_isoc_trace *trace; unsigned long flags; int i; spin_lock_irqsave(&imx21->lock, flags); trace = imx21->isoc_trace_failed; for (i = 0; i < ARRAY_SIZE(imx21->isoc_trace_failed); i++, trace++) debug_isoc_show_one(s, "isoc failed", i, trace); trace = imx21->isoc_trace; for (i = 0; i < ARRAY_SIZE(imx21->isoc_trace); i++, trace++) debug_isoc_show_one(s, "isoc", i, trace); spin_unlock_irqrestore(&imx21->lock, flags); return 0; } static int debug_status_open(struct inode *inode, struct file *file) { return single_open(file, debug_status_show, inode->i_private); } static int debug_dmem_open(struct inode *inode, struct file *file) { return single_open(file, debug_dmem_show, inode->i_private); } static int debug_etd_open(struct inode *inode, struct file *file) { return single_open(file, debug_etd_show, inode->i_private); } static int debug_statistics_open(struct inode *inode, struct file *file) { return single_open(file, debug_statistics_show, inode->i_private); } static int debug_isoc_open(struct inode *inode, struct file *file) { return single_open(file, debug_isoc_show, inode->i_private); } static const struct file_operations debug_status_fops = { .open = debug_status_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static const struct file_operations debug_dmem_fops = { .open = debug_dmem_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static const struct file_operations debug_etd_fops = { .open = debug_etd_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static const struct file_operations debug_statistics_fops = { .open = debug_statistics_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static const struct file_operations debug_isoc_fops = { .open = debug_isoc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static void create_debug_files(struct imx21 *imx21) { imx21->debug_root = debugfs_create_dir(dev_name(imx21->dev), NULL); if (!imx21->debug_root) goto failed_create_rootdir; if (!debugfs_create_file("status", S_IRUGO, imx21->debug_root, imx21, &debug_status_fops)) goto failed_create; if (!debugfs_create_file("dmem", S_IRUGO, imx21->debug_root, imx21, &debug_dmem_fops)) goto failed_create; if (!debugfs_create_file("etd", S_IRUGO, imx21->debug_root, imx21, &debug_etd_fops)) goto failed_create; if (!debugfs_create_file("statistics", S_IRUGO, imx21->debug_root, imx21, &debug_statistics_fops)) goto failed_create; if (!debugfs_create_file("isoc", S_IRUGO, imx21->debug_root, imx21, &debug_isoc_fops)) goto failed_create; return; failed_create: debugfs_remove_recursive(imx21->debug_root); failed_create_rootdir: imx21->debug_root = NULL; } static void remove_debug_files(struct imx21 *imx21) { if (imx21->debug_root) { debugfs_remove_recursive(imx21->debug_root); imx21->debug_root = NULL; } } #endif
the_stack_data/835526.c
/* Morse code decoder automaton * This is free and unencumbered software released into the public domain. */ /* Advance to the next state for an input, '.', '-'. or 0 (terminal). * The initial state is zero. Returns the next state, or the result: * < 0 when more input is needed (i.e. next state) * = 0 for invalid input * > 0 the ASCII result */ int morse_decode(int state, int c) { static const unsigned char t[] = { 0x03, 0x3f, 0x7b, 0x4f, 0x2f, 0x63, 0x5f, 0x77, 0x7f, 0x72, 0x87, 0x3b, 0x57, 0x47, 0x67, 0x4b, 0x81, 0x40, 0x01, 0x58, 0x00, 0x68, 0x51, 0x32, 0x88, 0x34, 0x8c, 0x92, 0x6c, 0x02, 0x03, 0x18, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x24, 0x00, 0x28, 0x04, 0x00, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a }; int v = t[-state]; switch (c) { case 0x00: return v >> 2 ? t[(v >> 2) + 63] : 0; case 0x2e: return v & 2 ? state*2 - 1 : 0; case 0x2d: return v & 1 ? state*2 - 2 : 0; default: return 0; } } #ifdef TEST #include <stdio.h> #include <string.h> #define CR(s) "\x1b[91;1m" s "\x1b[0m" #define CG(s) "\x1b[92;1m" s "\x1b[0m" int main(void) { #ifdef _WIN32 /* Best effort enable ANSI escape processing. */ void *GetStdHandle(unsigned); int GetConsoleMode(void *, unsigned *); int SetConsoleMode(void *, unsigned); void *handle; unsigned mode; handle = GetStdHandle(-11); /* STD_OUTPUT_HANDLE */ if (GetConsoleMode(handle, &mode)) { mode |= 0x0004; /* ENABLE_VIRTUAL_TERMINAL_PROCESSING */ SetConsoleMode(handle, mode); /* ignore errors */ } #endif static const struct { char input[6]; char expect; } tests[] = { {"", 0 }, {".", 'E'}, {"-", 'T'}, {"..", 'I'}, {".-", 'A'}, {"-.", 'N'}, {"--", 'M'}, {"...", 'S'}, {"..-", 'U'}, {".-.", 'R'}, {".--", 'W'}, {"-..", 'D'}, {"-.-", 'K'}, {"--.", 'G'}, {"---", 'O'}, {"....", 'H'}, {"...-", 'V'}, {"..-.", 'F'}, {"..--", 0 }, {".-..", 'L'}, {".-.-", 0 }, {".--.", 'P'}, {".---", 'J'}, {"-...", 'B'}, {"-..-", 'X'}, {"-.-.", 'C'}, {"-.--", 'Y'}, {"--..", 'Z'}, {"--.-", 'Q'}, {"---.", 0 }, {"----", 0 }, {".....", '5'}, {"....-", '4'}, {"...-.", 0 }, {"...--", '3'}, {"..-..", 0 }, {"..-.-", 0 }, {"..--.", 0 }, {"..---", '2'}, {".-...", 0 }, {".-..-", 0 }, {".-.-.", 0 }, {".-.--", 0 }, {".--..", 0 }, {".--.-", 0 }, {".---.", 0 }, {".----", '1'}, {"-....", '6'}, {"-...-", 0 }, {"-..-.", 0 }, {"-..--", 0 }, {"-.-..", 0 }, {"-.-.-", 0 }, {"-.--.", 0 }, {"-.---", 0 }, {"--...", '7'}, {"--..-", 0 }, {"--.-.", 0 }, {"--.--", 0 }, {"---..", '8'}, {"---.-", 0 }, {"----.", '9'}, {"-----", '0'}, }; int fails = 0; int n, ntests = sizeof(tests) / sizeof(*tests); for (n = 0; n < ntests; n++) { const char *s = tests[n].input; int expect = tests[n].expect; int pass = 1; int state = 0; while (*s) { state = morse_decode(state, *s++); if (!state) { if (expect) { printf(CR("FAIL") ": %s, want %c, got early error\n", tests[n].input, expect); pass = 0; } break; } if (state > 0) { printf(CR("FAIL") ": %s, want %c, got early 0x%02x\n", tests[n].input, expect, state); pass = 0; break; } } if (state < 0) { state = morse_decode(state, 0); if (!state) { if (expect) { printf(CR("FAIL") ": %s, want %c, got error\n", tests[n].input, expect); pass = 0; } } else if (state < 0) { printf(CR("FAIL") ": %s, want %c, got continuation\n", tests[n].input, expect); pass = 0; } else if (state != expect) { if (expect) { printf(CR("FAIL") ": %s, want %c, got 0x%02x\n", tests[n].input, expect, state); } else { printf(CR("FAIL") ": %s, want error, got 0x%02x (%c)\n", tests[n].input, state, state); } pass = 0; } } if (pass) { if (expect) { printf(CG("PASS") ": %c %s\n", expect, tests[n].input); } else { printf(CG("PASS") ": ? %s\n", tests[n].input); } } fails += !pass; } if (!fails) { printf("All %d tests pass\n", ntests); } return !!fails; } #endif
the_stack_data/288113.c
// succeeds int main(void) { int i = 0; return i; }
the_stack_data/32949009.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) */ /* Table of constant values */ static integer c__1 = 1; static real c_b18 = .003f; /* > \brief \b SSTEMR */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download SSTEMR + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/sstemr. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/sstemr. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/sstemr. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE SSTEMR( JOBZ, RANGE, N, D, E, VL, VU, IL, IU, */ /* M, W, Z, LDZ, NZC, ISUPPZ, TRYRAC, WORK, LWORK, */ /* IWORK, LIWORK, INFO ) */ /* CHARACTER JOBZ, RANGE */ /* LOGICAL TRYRAC */ /* INTEGER IL, INFO, IU, LDZ, NZC, LIWORK, LWORK, M, N */ /* REAL VL, VU */ /* INTEGER ISUPPZ( * ), IWORK( * ) */ /* REAL D( * ), E( * ), W( * ), WORK( * ) */ /* REAL Z( LDZ, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > SSTEMR computes selected eigenvalues and, optionally, eigenvectors */ /* > of a real symmetric tridiagonal matrix T. Any such unreduced matrix has */ /* > a well defined set of pairwise different real eigenvalues, the corresponding */ /* > real eigenvectors are pairwise orthogonal. */ /* > */ /* > The spectrum may be computed either completely or partially by specifying */ /* > either an interval (VL,VU] or a range of indices IL:IU for the desired */ /* > eigenvalues. */ /* > */ /* > Depending on the number of desired eigenvalues, these are computed either */ /* > by bisection or the dqds algorithm. Numerically orthogonal eigenvectors are */ /* > computed by the use of various suitable L D L^T factorizations near clusters */ /* > of close eigenvalues (referred to as RRRs, Relatively Robust */ /* > Representations). An informal sketch of the algorithm follows. */ /* > */ /* > For each unreduced block (submatrix) of T, */ /* > (a) Compute T - sigma I = L D L^T, so that L and D */ /* > define all the wanted eigenvalues to high relative accuracy. */ /* > This means that small relative changes in the entries of D and L */ /* > cause only small relative changes in the eigenvalues and */ /* > eigenvectors. The standard (unfactored) representation of the */ /* > tridiagonal matrix T does not have this property in general. */ /* > (b) Compute the eigenvalues to suitable accuracy. */ /* > If the eigenvectors are desired, the algorithm attains full */ /* > accuracy of the computed eigenvalues only right before */ /* > the corresponding vectors have to be computed, see steps c) and d). */ /* > (c) For each cluster of close eigenvalues, select a new */ /* > shift close to the cluster, find a new factorization, and refine */ /* > the shifted eigenvalues to suitable accuracy. */ /* > (d) For each eigenvalue with a large enough relative separation compute */ /* > the corresponding eigenvector by forming a rank revealing twisted */ /* > factorization. Go back to (c) for any clusters that remain. */ /* > */ /* > For more details, see: */ /* > - Inderjit S. Dhillon and Beresford N. Parlett: "Multiple representations */ /* > to compute orthogonal eigenvectors of symmetric tridiagonal matrices," */ /* > Linear Algebra and its Applications, 387(1), pp. 1-28, August 2004. */ /* > - Inderjit Dhillon and Beresford Parlett: "Orthogonal Eigenvectors and */ /* > Relative Gaps," SIAM Journal on Matrix Analysis and Applications, Vol. 25, */ /* > 2004. Also LAPACK Working Note 154. */ /* > - Inderjit Dhillon: "A new O(n^2) algorithm for the symmetric */ /* > tridiagonal eigenvalue/eigenvector problem", */ /* > Computer Science Division Technical Report No. UCB/CSD-97-971, */ /* > UC Berkeley, May 1997. */ /* > */ /* > Further Details */ /* > 1.SSTEMR works only on machines which follow IEEE-754 */ /* > floating-point standard in their handling of infinities and NaNs. */ /* > This permits the use of efficient inner loops avoiding a check for */ /* > zero divisors. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] JOBZ */ /* > \verbatim */ /* > JOBZ is CHARACTER*1 */ /* > = 'N': Compute eigenvalues only; */ /* > = 'V': Compute eigenvalues and eigenvectors. */ /* > \endverbatim */ /* > */ /* > \param[in] RANGE */ /* > \verbatim */ /* > RANGE is CHARACTER*1 */ /* > = 'A': all eigenvalues will be found. */ /* > = 'V': all eigenvalues in the half-open interval (VL,VU] */ /* > will be found. */ /* > = 'I': the IL-th through IU-th eigenvalues will be found. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] D */ /* > \verbatim */ /* > D is REAL array, dimension (N) */ /* > On entry, the N diagonal elements of the tridiagonal matrix */ /* > T. On exit, D is overwritten. */ /* > \endverbatim */ /* > */ /* > \param[in,out] E */ /* > \verbatim */ /* > E is REAL array, dimension (N) */ /* > On entry, the (N-1) subdiagonal elements of the tridiagonal */ /* > matrix T in elements 1 to N-1 of E. E(N) need not be set on */ /* > input, but is used internally as workspace. */ /* > On exit, E is overwritten. */ /* > \endverbatim */ /* > */ /* > \param[in] VL */ /* > \verbatim */ /* > VL is REAL */ /* > */ /* > If RANGE='V', the lower bound of the interval to */ /* > be searched for eigenvalues. VL < VU. */ /* > Not referenced if RANGE = 'A' or 'I'. */ /* > \endverbatim */ /* > */ /* > \param[in] VU */ /* > \verbatim */ /* > VU is REAL */ /* > */ /* > If RANGE='V', the upper bound of the interval to */ /* > be searched for eigenvalues. VL < VU. */ /* > Not referenced if RANGE = 'A' or 'I'. */ /* > \endverbatim */ /* > */ /* > \param[in] IL */ /* > \verbatim */ /* > IL is INTEGER */ /* > */ /* > If RANGE='I', the index of the */ /* > smallest eigenvalue to be returned. */ /* > 1 <= IL <= IU <= N, if N > 0. */ /* > Not referenced if RANGE = 'A' or 'V'. */ /* > \endverbatim */ /* > */ /* > \param[in] IU */ /* > \verbatim */ /* > IU is INTEGER */ /* > */ /* > If RANGE='I', the index of the */ /* > largest eigenvalue to be returned. */ /* > 1 <= IL <= IU <= N, if N > 0. */ /* > Not referenced if RANGE = 'A' or 'V'. */ /* > \endverbatim */ /* > */ /* > \param[out] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The total number of eigenvalues found. 0 <= M <= N. */ /* > If RANGE = 'A', M = N, and if RANGE = 'I', M = IU-IL+1. */ /* > \endverbatim */ /* > */ /* > \param[out] W */ /* > \verbatim */ /* > W is REAL array, dimension (N) */ /* > The first M elements contain the selected eigenvalues in */ /* > ascending order. */ /* > \endverbatim */ /* > */ /* > \param[out] Z */ /* > \verbatim */ /* > Z is REAL array, dimension (LDZ, f2cmax(1,M) ) */ /* > If JOBZ = 'V', and if INFO = 0, then the first M columns of Z */ /* > contain the orthonormal eigenvectors of the matrix T */ /* > corresponding to the selected eigenvalues, with the i-th */ /* > column of Z holding the eigenvector associated with W(i). */ /* > If JOBZ = 'N', then Z is not referenced. */ /* > Note: the user must ensure that at least f2cmax(1,M) columns are */ /* > supplied in the array Z; if RANGE = 'V', the exact value of M */ /* > is not known in advance and can be computed with a workspace */ /* > query by setting NZC = -1, see below. */ /* > \endverbatim */ /* > */ /* > \param[in] LDZ */ /* > \verbatim */ /* > LDZ is INTEGER */ /* > The leading dimension of the array Z. LDZ >= 1, and if */ /* > JOBZ = 'V', then LDZ >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in] NZC */ /* > \verbatim */ /* > NZC is INTEGER */ /* > The number of eigenvectors to be held in the array Z. */ /* > If RANGE = 'A', then NZC >= f2cmax(1,N). */ /* > If RANGE = 'V', then NZC >= the number of eigenvalues in (VL,VU]. */ /* > If RANGE = 'I', then NZC >= IU-IL+1. */ /* > If NZC = -1, then a workspace query is assumed; the */ /* > routine calculates the number of columns of the array Z that */ /* > are needed to hold the eigenvectors. */ /* > This value is returned as the first entry of the Z array, and */ /* > no error message related to NZC is issued by XERBLA. */ /* > \endverbatim */ /* > */ /* > \param[out] ISUPPZ */ /* > \verbatim */ /* > ISUPPZ is INTEGER array, dimension ( 2*f2cmax(1,M) ) */ /* > The support of the eigenvectors in Z, i.e., the indices */ /* > indicating the nonzero elements in Z. The i-th computed eigenvector */ /* > is nonzero only in elements ISUPPZ( 2*i-1 ) through */ /* > ISUPPZ( 2*i ). This is relevant in the case when the matrix */ /* > is split. ISUPPZ is only accessed when JOBZ is 'V' and N > 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] TRYRAC */ /* > \verbatim */ /* > TRYRAC is LOGICAL */ /* > If TRYRAC = .TRUE., indicates that the code should check whether */ /* > the tridiagonal matrix defines its eigenvalues to high relative */ /* > accuracy. If so, the code uses relative-accuracy preserving */ /* > algorithms that might be (a bit) slower depending on the matrix. */ /* > If the matrix does not define its eigenvalues to high relative */ /* > accuracy, the code can uses possibly faster algorithms. */ /* > If TRYRAC = .FALSE., the code is not required to guarantee */ /* > relatively accurate eigenvalues and can use the fastest possible */ /* > techniques. */ /* > On exit, a .TRUE. TRYRAC will be set to .FALSE. if the matrix */ /* > does not define its eigenvalues to high relative accuracy. */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is REAL array, dimension (LWORK) */ /* > On exit, if INFO = 0, WORK(1) returns the optimal */ /* > (and minimal) LWORK. */ /* > \endverbatim */ /* > */ /* > \param[in] LWORK */ /* > \verbatim */ /* > LWORK is INTEGER */ /* > The dimension of the array WORK. LWORK >= f2cmax(1,18*N) */ /* > if JOBZ = 'V', and LWORK >= f2cmax(1,12*N) if JOBZ = 'N'. */ /* > If LWORK = -1, then a workspace query is assumed; the routine */ /* > only calculates the optimal size of the WORK array, returns */ /* > this value as the first entry of the WORK array, and no error */ /* > message related to LWORK is issued by XERBLA. */ /* > \endverbatim */ /* > */ /* > \param[out] IWORK */ /* > \verbatim */ /* > IWORK is INTEGER array, dimension (LIWORK) */ /* > On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. */ /* > \endverbatim */ /* > */ /* > \param[in] LIWORK */ /* > \verbatim */ /* > LIWORK is INTEGER */ /* > The dimension of the array IWORK. LIWORK >= f2cmax(1,10*N) */ /* > if the eigenvectors are desired, and LIWORK >= f2cmax(1,8*N) */ /* > if only the eigenvalues are to be computed. */ /* > If LIWORK = -1, then a workspace query is assumed; the */ /* > routine only calculates the optimal size of the IWORK array, */ /* > returns this value as the first entry of the IWORK array, and */ /* > no error message related to LIWORK is issued by XERBLA. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > On exit, INFO */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > > 0: if INFO = 1X, internal error in SLARRE, */ /* > if INFO = 2X, internal error in SLARRV. */ /* > Here, the digit X = ABS( IINFO ) < 10, where IINFO is */ /* > the nonzero error code returned by SLARRE or */ /* > SLARRV, respectively. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date June 2016 */ /* > \ingroup realOTHERcomputational */ /* > \par Contributors: */ /* ================== */ /* > */ /* > Beresford Parlett, University of California, Berkeley, USA \n */ /* > Jim Demmel, University of California, Berkeley, USA \n */ /* > Inderjit Dhillon, University of Texas, Austin, USA \n */ /* > Osni Marques, LBNL/NERSC, USA \n */ /* > Christof Voemel, University of California, Berkeley, USA */ /* ===================================================================== */ /* Subroutine */ int sstemr_(char *jobz, char *range, integer *n, real *d__, real *e, real *vl, real *vu, integer *il, integer *iu, integer *m, real *w, real *z__, integer *ldz, integer *nzc, integer *isuppz, logical *tryrac, real *work, integer *lwork, integer *iwork, integer * liwork, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2; real r__1, r__2; /* Local variables */ integer indd, iend, jblk, wend; real rmin, rmax; integer itmp; real tnrm; integer inde2; extern /* Subroutine */ int slae2_(real *, real *, real *, real *, real *) ; integer itmp2; real rtol1, rtol2; integer i__, j; real scale; integer indgp; extern logical lsame_(char *, char *); integer iinfo; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); integer iindw, ilast, lwmin; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *), sswap_(integer *, real *, integer *, real *, integer * ); logical wantz; real r1, r2; extern /* Subroutine */ int slaev2_(real *, real *, real *, real *, real * , real *, real *); integer jj; real cs; integer in; logical alleig, indeig; integer ibegin, iindbl; real sn, wl; logical valeig; extern real slamch_(char *); integer wbegin; real safmin, wu; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); real bignum; integer inderr, iindwk, indgrs, offset; extern /* Subroutine */ int slarrc_(char *, integer *, real *, real *, real *, real *, real *, integer *, integer *, integer *, integer * ), slarre_(char *, integer *, real *, real *, integer *, integer *, real *, real *, real *, real *, real *, real *, integer *, integer *, integer *, real *, real *, real *, integer * , integer *, real *, real *, real *, integer *, integer *) ; real thresh; integer iinspl, indwrk, ifirst, liwmin, nzcmin; real pivmin; extern real slanst_(char *, integer *, real *, real *); extern /* Subroutine */ int slarrj_(integer *, real *, real *, integer *, integer *, real *, integer *, real *, real *, real *, integer *, real *, real *, integer *), slarrr_(integer *, real *, real *, integer *); integer nsplit; extern /* Subroutine */ int slarrv_(integer *, real *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, real * , real *, real *, real *, real *, real *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer * ); real smlnum; extern /* Subroutine */ int slasrt_(char *, integer *, real *, integer *); logical lquery, zquery; integer iil, iiu; real eps, tmp; /* -- LAPACK computational routine (version 3.7.1) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* June 2016 */ /* ===================================================================== */ /* Test the input parameters. */ /* Parameter adjustments */ --d__; --e; --w; z_dim1 = *ldz; z_offset = 1 + z_dim1 * 1; z__ -= z_offset; --isuppz; --work; --iwork; /* Function Body */ wantz = lsame_(jobz, "V"); alleig = lsame_(range, "A"); valeig = lsame_(range, "V"); indeig = lsame_(range, "I"); lquery = *lwork == -1 || *liwork == -1; zquery = *nzc == -1; /* SSTEMR needs WORK of size 6*N, IWORK of size 3*N. */ /* In addition, SLARRE needs WORK of size 6*N, IWORK of size 5*N. */ /* Furthermore, SLARRV needs WORK of size 12*N, IWORK of size 7*N. */ if (wantz) { lwmin = *n * 18; liwmin = *n * 10; } else { /* need less workspace if only the eigenvalues are wanted */ lwmin = *n * 12; liwmin = *n << 3; } wl = 0.f; wu = 0.f; iil = 0; iiu = 0; nsplit = 0; if (valeig) { /* We do not reference VL, VU in the cases RANGE = 'I','A' */ /* The interval (WL, WU] contains all the wanted eigenvalues. */ /* It is either given by the user or computed in SLARRE. */ wl = *vl; wu = *vu; } else if (indeig) { /* We do not reference IL, IU in the cases RANGE = 'V','A' */ iil = *il; iiu = *iu; } *info = 0; if (! (wantz || lsame_(jobz, "N"))) { *info = -1; } else if (! (alleig || valeig || indeig)) { *info = -2; } else if (*n < 0) { *info = -3; } else if (valeig && *n > 0 && wu <= wl) { *info = -7; } else if (indeig && (iil < 1 || iil > *n)) { *info = -8; } else if (indeig && (iiu < iil || iiu > *n)) { *info = -9; } else if (*ldz < 1 || wantz && *ldz < *n) { *info = -13; } else if (*lwork < lwmin && ! lquery) { *info = -17; } else if (*liwork < liwmin && ! lquery) { *info = -19; } /* Get machine constants. */ safmin = slamch_("Safe minimum"); eps = slamch_("Precision"); smlnum = safmin / eps; bignum = 1.f / smlnum; rmin = sqrt(smlnum); /* Computing MIN */ r__1 = sqrt(bignum), r__2 = 1.f / sqrt(sqrt(safmin)); rmax = f2cmin(r__1,r__2); if (*info == 0) { work[1] = (real) lwmin; iwork[1] = liwmin; if (wantz && alleig) { nzcmin = *n; } else if (wantz && valeig) { slarrc_("T", n, vl, vu, &d__[1], &e[1], &safmin, &nzcmin, &itmp, & itmp2, info); } else if (wantz && indeig) { nzcmin = iiu - iil + 1; } else { /* WANTZ .EQ. FALSE. */ nzcmin = 0; } if (zquery && *info == 0) { z__[z_dim1 + 1] = (real) nzcmin; } else if (*nzc < nzcmin && ! zquery) { *info = -14; } } if (*info != 0) { i__1 = -(*info); xerbla_("SSTEMR", &i__1, (ftnlen)6); return 0; } else if (lquery || zquery) { return 0; } /* Handle N = 0, 1, and 2 cases immediately */ *m = 0; if (*n == 0) { return 0; } if (*n == 1) { if (alleig || indeig) { *m = 1; w[1] = d__[1]; } else { if (wl < d__[1] && wu >= d__[1]) { *m = 1; w[1] = d__[1]; } } if (wantz && ! zquery) { z__[z_dim1 + 1] = 1.f; isuppz[1] = 1; isuppz[2] = 1; } return 0; } if (*n == 2) { if (! wantz) { slae2_(&d__[1], &e[1], &d__[2], &r1, &r2); } else if (wantz && ! zquery) { slaev2_(&d__[1], &e[1], &d__[2], &r1, &r2, &cs, &sn); } if (alleig || valeig && r2 > wl && r2 <= wu || indeig && iil == 1) { ++(*m); w[*m] = r2; if (wantz && ! zquery) { z__[*m * z_dim1 + 1] = -sn; z__[*m * z_dim1 + 2] = cs; /* Note: At most one of SN and CS can be zero. */ if (sn != 0.f) { if (cs != 0.f) { isuppz[(*m << 1) - 1] = 1; isuppz[*m * 2] = 2; } else { isuppz[(*m << 1) - 1] = 1; isuppz[*m * 2] = 1; } } else { isuppz[(*m << 1) - 1] = 2; isuppz[*m * 2] = 2; } } } if (alleig || valeig && r1 > wl && r1 <= wu || indeig && iiu == 2) { ++(*m); w[*m] = r1; if (wantz && ! zquery) { z__[*m * z_dim1 + 1] = cs; z__[*m * z_dim1 + 2] = sn; /* Note: At most one of SN and CS can be zero. */ if (sn != 0.f) { if (cs != 0.f) { isuppz[(*m << 1) - 1] = 1; isuppz[*m * 2] = 2; } else { isuppz[(*m << 1) - 1] = 1; isuppz[*m * 2] = 1; } } else { isuppz[(*m << 1) - 1] = 2; isuppz[*m * 2] = 2; } } } } else { /* Continue with general N */ indgrs = 1; inderr = (*n << 1) + 1; indgp = *n * 3 + 1; indd = (*n << 2) + 1; inde2 = *n * 5 + 1; indwrk = *n * 6 + 1; iinspl = 1; iindbl = *n + 1; iindw = (*n << 1) + 1; iindwk = *n * 3 + 1; /* Scale matrix to allowable range, if necessary. */ /* The allowable range is related to the PIVMIN parameter; see the */ /* comments in SLARRD. The preference for scaling small values */ /* up is heuristic; we expect users' matrices not to be close to the */ /* RMAX threshold. */ scale = 1.f; tnrm = slanst_("M", n, &d__[1], &e[1]); if (tnrm > 0.f && tnrm < rmin) { scale = rmin / tnrm; } else if (tnrm > rmax) { scale = rmax / tnrm; } if (scale != 1.f) { sscal_(n, &scale, &d__[1], &c__1); i__1 = *n - 1; sscal_(&i__1, &scale, &e[1], &c__1); tnrm *= scale; if (valeig) { /* If eigenvalues in interval have to be found, */ /* scale (WL, WU] accordingly */ wl *= scale; wu *= scale; } } /* Compute the desired eigenvalues of the tridiagonal after splitting */ /* into smaller subblocks if the corresponding off-diagonal elements */ /* are small */ /* THRESH is the splitting parameter for SLARRE */ /* A negative THRESH forces the old splitting criterion based on the */ /* size of the off-diagonal. A positive THRESH switches to splitting */ /* which preserves relative accuracy. */ if (*tryrac) { /* Test whether the matrix warrants the more expensive relative approach. */ slarrr_(n, &d__[1], &e[1], &iinfo); } else { /* The user does not care about relative accurately eigenvalues */ iinfo = -1; } /* Set the splitting criterion */ if (iinfo == 0) { thresh = eps; } else { thresh = -eps; /* relative accuracy is desired but T does not guarantee it */ *tryrac = FALSE_; } if (*tryrac) { /* Copy original diagonal, needed to guarantee relative accuracy */ scopy_(n, &d__[1], &c__1, &work[indd], &c__1); } /* Store the squares of the offdiagonal values of T */ i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { /* Computing 2nd power */ r__1 = e[j]; work[inde2 + j - 1] = r__1 * r__1; /* L5: */ } /* Set the tolerance parameters for bisection */ if (! wantz) { /* SLARRE computes the eigenvalues to full precision. */ rtol1 = eps * 4.f; rtol2 = eps * 4.f; } else { /* SLARRE computes the eigenvalues to less than full precision. */ /* SLARRV will refine the eigenvalue approximations, and we can */ /* need less accurate initial bisection in SLARRE. */ /* Note: these settings do only affect the subset case and SLARRE */ /* Computing MAX */ r__1 = sqrt(eps) * .05f, r__2 = eps * 4.f; rtol1 = f2cmax(r__1,r__2); /* Computing MAX */ r__1 = sqrt(eps) * .005f, r__2 = eps * 4.f; rtol2 = f2cmax(r__1,r__2); } slarre_(range, n, &wl, &wu, &iil, &iiu, &d__[1], &e[1], &work[inde2], &rtol1, &rtol2, &thresh, &nsplit, &iwork[iinspl], m, &w[1], & work[inderr], &work[indgp], &iwork[iindbl], &iwork[iindw], & work[indgrs], &pivmin, &work[indwrk], &iwork[iindwk], &iinfo); if (iinfo != 0) { *info = abs(iinfo) + 10; return 0; } /* Note that if RANGE .NE. 'V', SLARRE computes bounds on the desired */ /* part of the spectrum. All desired eigenvalues are contained in */ /* (WL,WU] */ if (wantz) { /* Compute the desired eigenvectors corresponding to the computed */ /* eigenvalues */ slarrv_(n, &wl, &wu, &d__[1], &e[1], &pivmin, &iwork[iinspl], m, & c__1, m, &c_b18, &rtol1, &rtol2, &w[1], &work[inderr], & work[indgp], &iwork[iindbl], &iwork[iindw], &work[indgrs], &z__[z_offset], ldz, &isuppz[1], &work[indwrk], &iwork[ iindwk], &iinfo); if (iinfo != 0) { *info = abs(iinfo) + 20; return 0; } } else { /* SLARRE computes eigenvalues of the (shifted) root representation */ /* SLARRV returns the eigenvalues of the unshifted matrix. */ /* However, if the eigenvectors are not desired by the user, we need */ /* to apply the corresponding shifts from SLARRE to obtain the */ /* eigenvalues of the original matrix. */ i__1 = *m; for (j = 1; j <= i__1; ++j) { itmp = iwork[iindbl + j - 1]; w[j] += e[iwork[iinspl + itmp - 1]]; /* L20: */ } } if (*tryrac) { /* Refine computed eigenvalues so that they are relatively accurate */ /* with respect to the original matrix T. */ ibegin = 1; wbegin = 1; i__1 = iwork[iindbl + *m - 1]; for (jblk = 1; jblk <= i__1; ++jblk) { iend = iwork[iinspl + jblk - 1]; in = iend - ibegin + 1; wend = wbegin - 1; /* check if any eigenvalues have to be refined in this block */ L36: if (wend < *m) { if (iwork[iindbl + wend] == jblk) { ++wend; goto L36; } } if (wend < wbegin) { ibegin = iend + 1; goto L39; } offset = iwork[iindw + wbegin - 1] - 1; ifirst = iwork[iindw + wbegin - 1]; ilast = iwork[iindw + wend - 1]; rtol2 = eps * 4.f; slarrj_(&in, &work[indd + ibegin - 1], &work[inde2 + ibegin - 1], &ifirst, &ilast, &rtol2, &offset, &w[wbegin], & work[inderr + wbegin - 1], &work[indwrk], &iwork[ iindwk], &pivmin, &tnrm, &iinfo); ibegin = iend + 1; wbegin = wend + 1; L39: ; } } /* If matrix was scaled, then rescale eigenvalues appropriately. */ if (scale != 1.f) { r__1 = 1.f / scale; sscal_(m, &r__1, &w[1], &c__1); } } /* If eigenvalues are not in increasing order, then sort them, */ /* possibly along with eigenvectors. */ if (nsplit > 1 || *n == 2) { if (! wantz) { slasrt_("I", m, &w[1], &iinfo); if (iinfo != 0) { *info = 3; return 0; } } else { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { i__ = 0; tmp = w[j]; i__2 = *m; for (jj = j + 1; jj <= i__2; ++jj) { if (w[jj] < tmp) { i__ = jj; tmp = w[jj]; } /* L50: */ } if (i__ != 0) { w[i__] = w[j]; w[j] = tmp; if (wantz) { sswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[j * z_dim1 + 1], &c__1); itmp = isuppz[(i__ << 1) - 1]; isuppz[(i__ << 1) - 1] = isuppz[(j << 1) - 1]; isuppz[(j << 1) - 1] = itmp; itmp = isuppz[i__ * 2]; isuppz[i__ * 2] = isuppz[j * 2]; isuppz[j * 2] = itmp; } } /* L60: */ } } } work[1] = (real) lwmin; iwork[1] = liwmin; return 0; /* End of SSTEMR */ } /* sstemr_ */
the_stack_data/82950735.c
/* Returning a pointer from a function Your task is to write a subroutine that takes a pointer to the first element of an integer array, as well as an integer variable. The arguments are passed to the subroutine in this order. The integer variable passed as an argument holds the number of elements in an array, while the actual array holds the number of integers specified by the variable. The subroutine must go through the table and return the address of the element holding the smallest value to the calling program. After receiving the address, the main program uses it to print the smallest number contained in the array. The prototype of the subroutine is the following: int *address_of_smallest_value(int *numbers, int size); In the above, the * operator indicates that the function's return value is a pointer. */ //solution #include<stdio.h> int *address_of_smallest_value(int *numbers, int size); int main(void) { int numbers[] = { 21, 55, 5, 3, 43}; int size = 5; int *smallest = address_of_smallest_value(numbers, size); printf("The smallest number in the array is: %d", *smallest); return 0; } // pointer int *address_of_smallest_value(int *numbers, int size){ int *p_smallest = &numbers[0]; int i = 0; int smallest = numbers[0]; for(i;i<size;i++){ if(numbers[i]<smallest){ smallest=numbers[i]; } } p_smallest = &smallest; return p_smallest; }
the_stack_data/173578610.c
int f(int i, int * arr) { if(i < 0) return 0; if(i > 10 && arr) return arr[i]; return f(i + 1, arr); }
the_stack_data/41981.c
// memory leak in edge_startup // https://syzkaller.appspot.com/bug?id=59f777bdcbdd7eea5305 // status:6 // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/usb/ch9.h> static unsigned long long procid; 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 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; } #define MAX_FDS 30 #define USB_MAX_IFACE_NUM 4 #define USB_MAX_EP_NUM 32 #define USB_MAX_FDS 6 struct usb_endpoint_index { struct usb_endpoint_descriptor desc; int handle; }; struct usb_iface_index { struct usb_interface_descriptor* iface; uint8_t bInterfaceNumber; uint8_t bAlternateSetting; uint8_t bInterfaceClass; struct usb_endpoint_index eps[USB_MAX_EP_NUM]; int eps_num; }; struct usb_device_index { struct usb_device_descriptor* dev; struct usb_config_descriptor* config; uint8_t bDeviceClass; uint8_t bMaxPower; int config_length; struct usb_iface_index ifaces[USB_MAX_IFACE_NUM]; int ifaces_num; int iface_cur; }; struct usb_info { int fd; struct usb_device_index index; }; static struct usb_info usb_devices[USB_MAX_FDS]; static int usb_devices_num; static bool parse_usb_descriptor(const char* buffer, size_t length, struct usb_device_index* index) { if (length < sizeof(*index->dev) + sizeof(*index->config)) return false; memset(index, 0, sizeof(*index)); index->dev = (struct usb_device_descriptor*)buffer; index->config = (struct usb_config_descriptor*)(buffer + sizeof(*index->dev)); index->bDeviceClass = index->dev->bDeviceClass; index->bMaxPower = index->config->bMaxPower; index->config_length = length - sizeof(*index->dev); index->iface_cur = -1; size_t offset = 0; while (true) { if (offset + 1 >= length) break; uint8_t desc_length = buffer[offset]; uint8_t desc_type = buffer[offset + 1]; if (desc_length <= 2) break; if (offset + desc_length > length) break; if (desc_type == USB_DT_INTERFACE && index->ifaces_num < USB_MAX_IFACE_NUM) { struct usb_interface_descriptor* iface = (struct usb_interface_descriptor*)(buffer + offset); index->ifaces[index->ifaces_num].iface = iface; index->ifaces[index->ifaces_num].bInterfaceNumber = iface->bInterfaceNumber; index->ifaces[index->ifaces_num].bAlternateSetting = iface->bAlternateSetting; index->ifaces[index->ifaces_num].bInterfaceClass = iface->bInterfaceClass; index->ifaces_num++; } if (desc_type == USB_DT_ENDPOINT && index->ifaces_num > 0) { struct usb_iface_index* iface = &index->ifaces[index->ifaces_num - 1]; if (iface->eps_num < USB_MAX_EP_NUM) { memcpy(&iface->eps[iface->eps_num].desc, buffer + offset, sizeof(iface->eps[iface->eps_num].desc)); iface->eps_num++; } } offset += desc_length; } return true; } static struct usb_device_index* add_usb_index(int fd, const char* dev, size_t dev_len) { int i = __atomic_fetch_add(&usb_devices_num, 1, __ATOMIC_RELAXED); if (i >= USB_MAX_FDS) return NULL; if (!parse_usb_descriptor(dev, dev_len, &usb_devices[i].index)) return NULL; __atomic_store_n(&usb_devices[i].fd, fd, __ATOMIC_RELEASE); return &usb_devices[i].index; } static struct usb_device_index* lookup_usb_index(int fd) { for (int i = 0; i < USB_MAX_FDS; i++) { if (__atomic_load_n(&usb_devices[i].fd, __ATOMIC_ACQUIRE) == fd) { return &usb_devices[i].index; } } return NULL; } struct vusb_connect_string_descriptor { uint32_t len; char* str; } __attribute__((packed)); struct vusb_connect_descriptors { uint32_t qual_len; char* qual; uint32_t bos_len; char* bos; uint32_t strs_len; struct vusb_connect_string_descriptor strs[0]; } __attribute__((packed)); static const char default_string[] = {8, USB_DT_STRING, 's', 0, 'y', 0, 'z', 0}; static const char default_lang_id[] = {4, USB_DT_STRING, 0x09, 0x04}; static bool lookup_connect_response_in(int fd, const struct vusb_connect_descriptors* descs, const struct usb_ctrlrequest* ctrl, char** response_data, uint32_t* response_length) { struct usb_device_index* index = lookup_usb_index(fd); uint8_t str_idx; if (!index) return false; switch (ctrl->bRequestType & USB_TYPE_MASK) { case USB_TYPE_STANDARD: switch (ctrl->bRequest) { case USB_REQ_GET_DESCRIPTOR: switch (ctrl->wValue >> 8) { case USB_DT_DEVICE: *response_data = (char*)index->dev; *response_length = sizeof(*index->dev); return true; case USB_DT_CONFIG: *response_data = (char*)index->config; *response_length = index->config_length; return true; case USB_DT_STRING: str_idx = (uint8_t)ctrl->wValue; if (descs && str_idx < descs->strs_len) { *response_data = descs->strs[str_idx].str; *response_length = descs->strs[str_idx].len; return true; } if (str_idx == 0) { *response_data = (char*)&default_lang_id[0]; *response_length = default_lang_id[0]; return true; } *response_data = (char*)&default_string[0]; *response_length = default_string[0]; return true; case USB_DT_BOS: *response_data = descs->bos; *response_length = descs->bos_len; return true; case USB_DT_DEVICE_QUALIFIER: if (!descs->qual) { struct usb_qualifier_descriptor* qual = (struct usb_qualifier_descriptor*)response_data; qual->bLength = sizeof(*qual); qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER; qual->bcdUSB = index->dev->bcdUSB; qual->bDeviceClass = index->dev->bDeviceClass; qual->bDeviceSubClass = index->dev->bDeviceSubClass; qual->bDeviceProtocol = index->dev->bDeviceProtocol; qual->bMaxPacketSize0 = index->dev->bMaxPacketSize0; qual->bNumConfigurations = index->dev->bNumConfigurations; qual->bRESERVED = 0; *response_length = sizeof(*qual); return true; } *response_data = descs->qual; *response_length = descs->qual_len; return true; default: break; } break; default: break; } break; default: break; } return false; } typedef bool (*lookup_connect_out_response_t)( int fd, const struct vusb_connect_descriptors* descs, const struct usb_ctrlrequest* ctrl, bool* done); static bool lookup_connect_response_out_generic( int fd, const struct vusb_connect_descriptors* descs, const struct usb_ctrlrequest* ctrl, bool* done) { switch (ctrl->bRequestType & USB_TYPE_MASK) { case USB_TYPE_STANDARD: switch (ctrl->bRequest) { case USB_REQ_SET_CONFIGURATION: *done = true; return true; default: break; } break; } return false; } struct vusb_descriptor { uint8_t req_type; uint8_t desc_type; uint32_t len; char data[0]; } __attribute__((packed)); struct vusb_descriptors { uint32_t len; struct vusb_descriptor* generic; struct vusb_descriptor* descs[0]; } __attribute__((packed)); struct vusb_response { uint8_t type; uint8_t req; uint32_t len; char data[0]; } __attribute__((packed)); struct vusb_responses { uint32_t len; struct vusb_response* generic; struct vusb_response* resps[0]; } __attribute__((packed)); static bool lookup_control_response(const struct vusb_descriptors* descs, const struct vusb_responses* resps, struct usb_ctrlrequest* ctrl, char** response_data, uint32_t* response_length) { int descs_num = 0; int resps_num = 0; if (descs) descs_num = (descs->len - offsetof(struct vusb_descriptors, descs)) / sizeof(descs->descs[0]); if (resps) resps_num = (resps->len - offsetof(struct vusb_responses, resps)) / sizeof(resps->resps[0]); uint8_t req = ctrl->bRequest; uint8_t req_type = ctrl->bRequestType & USB_TYPE_MASK; uint8_t desc_type = ctrl->wValue >> 8; if (req == USB_REQ_GET_DESCRIPTOR) { int i; for (i = 0; i < descs_num; i++) { struct vusb_descriptor* desc = descs->descs[i]; if (!desc) continue; if (desc->req_type == req_type && desc->desc_type == desc_type) { *response_length = desc->len; if (*response_length != 0) *response_data = &desc->data[0]; else *response_data = NULL; return true; } } if (descs && descs->generic) { *response_data = &descs->generic->data[0]; *response_length = descs->generic->len; return true; } } else { int i; for (i = 0; i < resps_num; i++) { struct vusb_response* resp = resps->resps[i]; if (!resp) continue; if (resp->type == req_type && resp->req == req) { *response_length = resp->len; if (*response_length != 0) *response_data = &resp->data[0]; else *response_data = NULL; return true; } } if (resps && resps->generic) { *response_data = &resps->generic->data[0]; *response_length = resps->generic->len; return true; } } return false; } #define UDC_NAME_LENGTH_MAX 128 struct usb_raw_init { __u8 driver_name[UDC_NAME_LENGTH_MAX]; __u8 device_name[UDC_NAME_LENGTH_MAX]; __u8 speed; }; enum usb_raw_event_type { USB_RAW_EVENT_INVALID = 0, USB_RAW_EVENT_CONNECT = 1, USB_RAW_EVENT_CONTROL = 2, }; struct usb_raw_event { __u32 type; __u32 length; __u8 data[0]; }; struct usb_raw_ep_io { __u16 ep; __u16 flags; __u32 length; __u8 data[0]; }; #define USB_RAW_EPS_NUM_MAX 30 #define USB_RAW_EP_NAME_MAX 16 #define USB_RAW_EP_ADDR_ANY 0xff struct usb_raw_ep_caps { __u32 type_control : 1; __u32 type_iso : 1; __u32 type_bulk : 1; __u32 type_int : 1; __u32 dir_in : 1; __u32 dir_out : 1; }; struct usb_raw_ep_limits { __u16 maxpacket_limit; __u16 max_streams; __u32 reserved; }; struct usb_raw_ep_info { __u8 name[USB_RAW_EP_NAME_MAX]; __u32 addr; struct usb_raw_ep_caps caps; struct usb_raw_ep_limits limits; }; struct usb_raw_eps_info { struct usb_raw_ep_info eps[USB_RAW_EPS_NUM_MAX]; }; #define USB_RAW_IOCTL_INIT _IOW('U', 0, struct usb_raw_init) #define USB_RAW_IOCTL_RUN _IO('U', 1) #define USB_RAW_IOCTL_EVENT_FETCH _IOR('U', 2, struct usb_raw_event) #define USB_RAW_IOCTL_EP0_WRITE _IOW('U', 3, struct usb_raw_ep_io) #define USB_RAW_IOCTL_EP0_READ _IOWR('U', 4, struct usb_raw_ep_io) #define USB_RAW_IOCTL_EP_ENABLE _IOW('U', 5, struct usb_endpoint_descriptor) #define USB_RAW_IOCTL_EP_DISABLE _IOW('U', 6, __u32) #define USB_RAW_IOCTL_EP_WRITE _IOW('U', 7, struct usb_raw_ep_io) #define USB_RAW_IOCTL_EP_READ _IOWR('U', 8, struct usb_raw_ep_io) #define USB_RAW_IOCTL_CONFIGURE _IO('U', 9) #define USB_RAW_IOCTL_VBUS_DRAW _IOW('U', 10, __u32) #define USB_RAW_IOCTL_EPS_INFO _IOR('U', 11, struct usb_raw_eps_info) #define USB_RAW_IOCTL_EP0_STALL _IO('U', 12) #define USB_RAW_IOCTL_EP_SET_HALT _IOW('U', 13, __u32) #define USB_RAW_IOCTL_EP_CLEAR_HALT _IOW('U', 14, __u32) #define USB_RAW_IOCTL_EP_SET_WEDGE _IOW('U', 15, __u32) static int usb_raw_open() { return open("/dev/raw-gadget", O_RDWR); } static int usb_raw_init(int fd, uint32_t speed, const char* driver, const char* device) { struct usb_raw_init arg; strncpy((char*)&arg.driver_name[0], driver, sizeof(arg.driver_name)); strncpy((char*)&arg.device_name[0], device, sizeof(arg.device_name)); arg.speed = speed; return ioctl(fd, USB_RAW_IOCTL_INIT, &arg); } static int usb_raw_run(int fd) { return ioctl(fd, USB_RAW_IOCTL_RUN, 0); } static int usb_raw_event_fetch(int fd, struct usb_raw_event* event) { return ioctl(fd, USB_RAW_IOCTL_EVENT_FETCH, event); } static int usb_raw_ep0_write(int fd, struct usb_raw_ep_io* io) { return ioctl(fd, USB_RAW_IOCTL_EP0_WRITE, io); } static int usb_raw_ep0_read(int fd, struct usb_raw_ep_io* io) { return ioctl(fd, USB_RAW_IOCTL_EP0_READ, io); } static int usb_raw_ep_enable(int fd, struct usb_endpoint_descriptor* desc) { return ioctl(fd, USB_RAW_IOCTL_EP_ENABLE, desc); } static int usb_raw_ep_disable(int fd, int ep) { return ioctl(fd, USB_RAW_IOCTL_EP_DISABLE, ep); } static int usb_raw_configure(int fd) { return ioctl(fd, USB_RAW_IOCTL_CONFIGURE, 0); } static int usb_raw_vbus_draw(int fd, uint32_t power) { return ioctl(fd, USB_RAW_IOCTL_VBUS_DRAW, power); } static int usb_raw_ep0_stall(int fd) { return ioctl(fd, USB_RAW_IOCTL_EP0_STALL, 0); } static int lookup_interface(int fd, uint8_t bInterfaceNumber, uint8_t bAlternateSetting) { struct usb_device_index* index = lookup_usb_index(fd); if (!index) return -1; for (int i = 0; i < index->ifaces_num; i++) { if (index->ifaces[i].bInterfaceNumber == bInterfaceNumber && index->ifaces[i].bAlternateSetting == bAlternateSetting) return i; } return -1; } static void set_interface(int fd, int n) { struct usb_device_index* index = lookup_usb_index(fd); if (!index) return; if (index->iface_cur >= 0 && index->iface_cur < index->ifaces_num) { for (int ep = 0; ep < index->ifaces[index->iface_cur].eps_num; ep++) { int rv = usb_raw_ep_disable( fd, index->ifaces[index->iface_cur].eps[ep].handle); if (rv < 0) { } else { } } } if (n >= 0 && n < index->ifaces_num) { for (int ep = 0; ep < index->ifaces[n].eps_num; ep++) { int rv = usb_raw_ep_enable(fd, &index->ifaces[n].eps[ep].desc); if (rv < 0) { } else { index->ifaces[n].eps[ep].handle = rv; } } index->iface_cur = n; } } static int configure_device(int fd) { struct usb_device_index* index = lookup_usb_index(fd); if (!index) return -1; int rv = usb_raw_vbus_draw(fd, index->bMaxPower); if (rv < 0) { return rv; } rv = usb_raw_configure(fd); if (rv < 0) { return rv; } set_interface(fd, 0); return 0; } #define USB_MAX_PACKET_SIZE 4096 struct usb_raw_control_event { struct usb_raw_event inner; struct usb_ctrlrequest ctrl; char data[USB_MAX_PACKET_SIZE]; }; struct usb_raw_ep_io_data { struct usb_raw_ep_io inner; char data[USB_MAX_PACKET_SIZE]; }; static volatile long syz_usb_connect_impl(uint64_t speed, uint64_t dev_len, const char* dev, const struct vusb_connect_descriptors* descs, lookup_connect_out_response_t lookup_connect_response_out) { if (!dev) { return -1; } int fd = usb_raw_open(); if (fd < 0) { return fd; } if (fd >= MAX_FDS) { close(fd); return -1; } struct usb_device_index* index = add_usb_index(fd, dev, dev_len); if (!index) { return -1; } char device[32]; sprintf(&device[0], "dummy_udc.%llu", procid); int rv = usb_raw_init(fd, speed, "dummy_udc", &device[0]); if (rv < 0) { return rv; } rv = usb_raw_run(fd); if (rv < 0) { return rv; } bool done = false; while (!done) { struct usb_raw_control_event event; event.inner.type = 0; event.inner.length = sizeof(event.ctrl); rv = usb_raw_event_fetch(fd, (struct usb_raw_event*)&event); if (rv < 0) { return rv; } if (event.inner.type != USB_RAW_EVENT_CONTROL) continue; char* response_data = NULL; uint32_t response_length = 0; if (event.ctrl.bRequestType & USB_DIR_IN) { if (!lookup_connect_response_in(fd, descs, &event.ctrl, &response_data, &response_length)) { usb_raw_ep0_stall(fd); continue; } } else { if (!lookup_connect_response_out(fd, descs, &event.ctrl, &done)) { usb_raw_ep0_stall(fd); continue; } response_data = NULL; response_length = event.ctrl.wLength; } if ((event.ctrl.bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD && event.ctrl.bRequest == USB_REQ_SET_CONFIGURATION) { rv = configure_device(fd); if (rv < 0) { return rv; } } struct usb_raw_ep_io_data response; response.inner.ep = 0; response.inner.flags = 0; if (response_length > sizeof(response.data)) response_length = 0; if (event.ctrl.wLength < response_length) response_length = event.ctrl.wLength; response.inner.length = response_length; if (response_data) memcpy(&response.data[0], response_data, response_length); else memset(&response.data[0], 0, response_length); if (event.ctrl.bRequestType & USB_DIR_IN) { rv = usb_raw_ep0_write(fd, (struct usb_raw_ep_io*)&response); } else { rv = usb_raw_ep0_read(fd, (struct usb_raw_ep_io*)&response); } if (rv < 0) { return rv; } } sleep_ms(200); return fd; } static volatile long syz_usb_connect(volatile long a0, volatile long a1, volatile long a2, volatile long a3) { uint64_t speed = a0; uint64_t dev_len = a1; const char* dev = (const char*)a2; const struct vusb_connect_descriptors* descs = (const struct vusb_connect_descriptors*)a3; return syz_usb_connect_impl(speed, dev_len, dev, descs, &lookup_connect_response_out_generic); } static volatile long syz_usb_control_io(volatile long a0, volatile long a1, volatile long a2) { int fd = a0; const struct vusb_descriptors* descs = (const struct vusb_descriptors*)a1; const struct vusb_responses* resps = (const struct vusb_responses*)a2; struct usb_raw_control_event event; event.inner.type = 0; event.inner.length = USB_MAX_PACKET_SIZE; int rv = usb_raw_event_fetch(fd, (struct usb_raw_event*)&event); if (rv < 0) { return rv; } if (event.inner.type != USB_RAW_EVENT_CONTROL) { return -1; } char* response_data = NULL; uint32_t response_length = 0; if ((event.ctrl.bRequestType & USB_DIR_IN) && event.ctrl.wLength) { if (!lookup_control_response(descs, resps, &event.ctrl, &response_data, &response_length)) { usb_raw_ep0_stall(fd); return -1; } } else { if ((event.ctrl.bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD || event.ctrl.bRequest == USB_REQ_SET_INTERFACE) { int iface_num = event.ctrl.wIndex; int alt_set = event.ctrl.wValue; int iface_index = lookup_interface(fd, iface_num, alt_set); if (iface_index < 0) { } else { set_interface(fd, iface_index); } } response_length = event.ctrl.wLength; } struct usb_raw_ep_io_data response; response.inner.ep = 0; response.inner.flags = 0; if (response_length > sizeof(response.data)) response_length = 0; if (event.ctrl.wLength < response_length) response_length = event.ctrl.wLength; if ((event.ctrl.bRequestType & USB_DIR_IN) && !event.ctrl.wLength) { response_length = USB_MAX_PACKET_SIZE; } response.inner.length = response_length; if (response_data) memcpy(&response.data[0], response_data, response_length); else memset(&response.data[0], 0, response_length); if ((event.ctrl.bRequestType & USB_DIR_IN) && event.ctrl.wLength) { rv = usb_raw_ep0_write(fd, (struct usb_raw_ep_io*)&response); } else { rv = usb_raw_ep0_read(fd, (struct usb_raw_ep_io*)&response); } if (rv < 0) { return rv; } sleep_ms(200); return 0; } 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_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); write_file("/proc/self/oom_score_adj", "1000"); } #define KMEMLEAK_FILE "/sys/kernel/debug/kmemleak" static void setup_leak() { if (!write_file(KMEMLEAK_FILE, "scan")) exit(1); sleep(5); if (!write_file(KMEMLEAK_FILE, "scan")) exit(1); if (!write_file(KMEMLEAK_FILE, "clear")) exit(1); } static void check_leaks(void) { int fd = open(KMEMLEAK_FILE, O_RDWR); if (fd == -1) exit(1); uint64_t start = current_time_ms(); if (write(fd, "scan", 4) != 4) exit(1); sleep(1); while (current_time_ms() - start < 4 * 1000) sleep(1); if (write(fd, "scan", 4) != 4) exit(1); static char buf[128 << 10]; ssize_t n = read(fd, buf, sizeof(buf) - 1); if (n < 0) exit(1); int nleaks = 0; if (n != 0) { sleep(1); if (write(fd, "scan", 4) != 4) exit(1); if (lseek(fd, 0, SEEK_SET) < 0) exit(1); n = read(fd, buf, sizeof(buf) - 1); if (n < 0) exit(1); buf[n] = 0; char* pos = buf; char* end = buf + n; while (pos < end) { char* next = strstr(pos + 1, "unreferenced object"); if (!next) next = end; char prev = *next; *next = 0; fprintf(stderr, "BUG: memory leak\n%s\n", pos); *next = prev; pos = next; nleaks++; } } if (write(fd, "clear", 5) != 5) exit(1); close(fd); if (nleaks) exit(1); } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { int iter = 0; for (;; iter++) { int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { 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 < 5000) { continue; } kill_and_wait(pid, &status); break; } check_leaks(); } } uint64_t r[1] = {0xffffffffffffffff}; void execute_one(void) { intptr_t res = 0; memcpy((void*)0x20000000, "\x12\x01\x00\x00\x53\xac\x69\x10\x08\x16\x04\x00\x85\x40\x00\x00\x00" "\x01\x09\x02\x2d\x00\x01\x00\x00\x00\x00\x09\x04\x3c\x00\x03\x83\x6f" "\xbd\x00\x09\x05\x8d\x1f\x00\x70\xd3\x00\x00\x09\x05\x05\x02\x00\x00" "\x00\x00\x00\x09\x05\x8f\x1e", 58); res = -1; res = syz_usb_connect(0, 0x3f, 0x20000000, 0); if (res != -1) r[0] = res; *(uint32_t*)0x20000300 = 0x2c; *(uint64_t*)0x20000304 = 0x20000040; *(uint8_t*)0x20000040 = 0; *(uint8_t*)0x20000041 = 0; *(uint32_t*)0x20000042 = 0x18; memcpy((void*)0x20000046, "\x8b\x09\x63\x50\xe4\xbe\x70\xe4\x47\xdd\x0f\xa8\x58\x9f\x59\xb5\x46" "\x49\x62\xae\xae\x9b\x81\x1c", 24); *(uint64_t*)0x2000030c = 0; *(uint64_t*)0x20000314 = 0; *(uint64_t*)0x2000031c = 0; *(uint64_t*)0x20000324 = 0; syz_usb_control_io(r[0], 0, 0x20000300); } 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_leak(); loop(); return 0; }
the_stack_data/111077946.c
/**/ #include <stdio.h> #include <stdlib.h> int main () { int n; int x, y; int temp; printf("\nEnter an integer > "); scanf("%d", &y); n = 0; while (n <= 10) { if (y == 0) { printf("\n%d", y); printf("\nThat's all, have a nice day!\n"); return 0; } x = y % 10; // printf("\n%d", abs(x)); x = y / 10; if (x > -10 && x < 0){ printf("\n%d", x); printf("\nThat's all, have a nice day!\n"); return 0; } // // // // temp = x; x = y; y = temp; n = n + 1; } // return 0; }
the_stack_data/87809.c
#include <stdio.h> int main(void) { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("*"); } printf("\n"); } return 0; }
the_stack_data/76699044.c
#include <stdio.h> int main () { for( unsigned int a = 100; a > 0; a -=4 ){ printf("value of a: %d\n", a); } return 0; }
the_stack_data/117327406.c
/* ** SQLCipher ** http://sqlcipher.net ** ** Copyright (c) 2008 - 2013, ZETETIC LLC ** 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 ZETETIC LLC 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 ZETETIC LLC ''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 ZETETIC LLC 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. ** */ /* BEGIN SQLCIPHER */ #ifdef SQLITE_HAS_CODEC #include "sqlcipher.h" #include "crypto.h" #include <time.h> #if defined(_WIN32) || defined(SQLITE_OS_WINRT) #include <windows.h> /* amalgamator: dontcache */ #else #include <sys/time.h> /* amalgamator: dontcache */ #endif #ifndef OMIT_MEMLOCK #if defined(__unix__) || defined(__APPLE__) || defined(_AIX) #include <errno.h> /* amalgamator: dontcache */ #include <unistd.h> /* amalgamator: dontcache */ #include <sys/resource.h> /* amalgamator: dontcache */ #include <sys/mman.h> /* amalgamator: dontcache */ #endif #endif #ifdef SQLCIPHER_TEST static volatile unsigned int cipher_test_flags = 0; unsigned int sqlcipher_get_test_flags() { return cipher_test_flags; } void sqlcipher_set_test_flags(unsigned int flags) { cipher_test_flags = flags; } static volatile int cipher_test_rand = 0; int sqlcipher_get_test_rand() { return cipher_test_rand; } void sqlcipher_set_test_rand(int rand) { cipher_test_rand = rand; } int sqlcipher_get_test_fail() { int x; /* if cipher_test_rand is not set to a non-zero value always fail (return true) */ if (cipher_test_rand == 0) return 1; sqlite3_randomness(sizeof(x), &x); return ((x % cipher_test_rand) == 0); } #endif /* Generate code to return a string value */ static volatile unsigned int default_flags = DEFAULT_CIPHER_FLAGS; static volatile unsigned char hmac_salt_mask = HMAC_SALT_MASK; static volatile int default_kdf_iter = PBKDF2_ITER; static volatile int default_page_size = 4096; static volatile int default_plaintext_header_sz = 0; static volatile int default_hmac_algorithm = SQLCIPHER_HMAC_SHA512; static volatile int default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA512; static volatile int mem_security_on = 0; static volatile int mem_security_initialized = 0; static volatile int mem_security_activated = 0; static volatile unsigned int sqlcipher_activate_count = 0; static volatile sqlite3_mem_methods default_mem_methods; static sqlcipher_provider *default_provider = NULL; static sqlite3_mutex* sqlcipher_static_mutex[SQLCIPHER_MUTEX_COUNT]; static volatile FILE* sqlcipher_log_file = NULL; static volatile int sqlcipher_log_logcat = 0; static volatile unsigned int sqlcipher_log_level = SQLCIPHER_LOG_NONE; sqlite3_mutex* sqlcipher_mutex(int mutex) { if(mutex < 0 || mutex >= SQLCIPHER_MUTEX_COUNT) return NULL; return sqlcipher_static_mutex[mutex]; } static int sqlcipher_mem_init(void *pAppData) { return default_mem_methods.xInit(pAppData); } static void sqlcipher_mem_shutdown(void *pAppData) { default_mem_methods.xShutdown(pAppData); } static void *sqlcipher_mem_malloc(int n) { void *ptr = default_mem_methods.xMalloc(n); if(mem_security_on) { sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_mem_malloc: calling sqlcipher_mlock(%p,%d)", ptr, n); sqlcipher_mlock(ptr, n); if(!mem_security_activated) mem_security_activated = 1; } return ptr; } static int sqlcipher_mem_size(void *p) { return default_mem_methods.xSize(p); } static void sqlcipher_mem_free(void *p) { int sz; if(mem_security_on) { sz = sqlcipher_mem_size(p); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_mem_free: calling sqlcipher_memset(%p,0,%d) and sqlcipher_munlock(%p, %d)", p, sz, p, sz); sqlcipher_memset(p, 0, sz); sqlcipher_munlock(p, sz); if(!mem_security_activated) mem_security_activated = 1; } default_mem_methods.xFree(p); } static void *sqlcipher_mem_realloc(void *p, int n) { void *new = NULL; int orig_sz = 0; if(mem_security_on) { orig_sz = sqlcipher_mem_size(p); if (n==0) { sqlcipher_mem_free(p); return NULL; } else if (!p) { return sqlcipher_mem_malloc(n); } else if(n <= orig_sz) { return p; } else { new = sqlcipher_mem_malloc(n); if(new) { memcpy(new, p, orig_sz); sqlcipher_mem_free(p); } return new; } } else { return default_mem_methods.xRealloc(p, n); } } static int sqlcipher_mem_roundup(int n) { return default_mem_methods.xRoundup(n); } static sqlite3_mem_methods sqlcipher_mem_methods = { sqlcipher_mem_malloc, sqlcipher_mem_free, sqlcipher_mem_realloc, sqlcipher_mem_size, sqlcipher_mem_roundup, sqlcipher_mem_init, sqlcipher_mem_shutdown, 0 }; void sqlcipher_init_memmethods() { if(mem_security_initialized) return; if(sqlite3_config(SQLITE_CONFIG_GETMALLOC, &default_mem_methods) != SQLITE_OK || sqlite3_config(SQLITE_CONFIG_MALLOC, &sqlcipher_mem_methods) != SQLITE_OK) { mem_security_on = mem_security_activated = 0; } mem_security_initialized = 1; } int sqlcipher_register_provider(sqlcipher_provider *p) { sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_register_provider: entering SQLCIPHER_MUTEX_PROVIDER"); sqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_register_provider: entered SQLCIPHER_MUTEX_PROVIDER"); if(default_provider != NULL && default_provider != p) { /* only free the current registerd provider if it has been initialized and it isn't a pointer to the same provider passed to the function (i.e. protect against a caller calling register twice for the same provider) */ sqlcipher_free(default_provider, sizeof(sqlcipher_provider)); } default_provider = p; sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_register_provider: leaving SQLCIPHER_MUTEX_PROVIDER"); sqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_register_provider: left SQLCIPHER_MUTEX_PROVIDER"); return SQLITE_OK; } /* return a pointer to the currently registered provider. This will allow an application to fetch the current registered provider and make minor changes to it */ sqlcipher_provider* sqlcipher_get_provider() { return default_provider; } void sqlcipher_activate() { sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_activate: entering static master mutex"); sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_activate: entered static master mutex"); /* allocate new mutexes */ if(sqlcipher_activate_count == 0) { int i; for(i = 0; i < SQLCIPHER_MUTEX_COUNT; i++) { sqlcipher_static_mutex[i] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); } } /* check to see if there is a provider registered at this point if there no provider registered at this point, register the default provider */ if(sqlcipher_get_provider() == NULL) { sqlcipher_provider *p = sqlcipher_malloc(sizeof(sqlcipher_provider)); #if defined (SQLCIPHER_CRYPTO_CC) extern int sqlcipher_cc_setup(sqlcipher_provider *p); sqlcipher_cc_setup(p); #elif defined (SQLCIPHER_CRYPTO_LIBTOMCRYPT) extern int sqlcipher_ltc_setup(sqlcipher_provider *p); sqlcipher_ltc_setup(p); #elif defined (SQLCIPHER_CRYPTO_NSS) extern int sqlcipher_nss_setup(sqlcipher_provider *p); sqlcipher_nss_setup(p); #elif defined (SQLCIPHER_CRYPTO_OPENSSL) extern int sqlcipher_openssl_setup(sqlcipher_provider *p); sqlcipher_openssl_setup(p); #else #error "NO DEFAULT SQLCIPHER CRYPTO PROVIDER DEFINED" #endif sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_activate: calling sqlcipher_register_provider(%p)", p); #ifdef SQLCIPHER_EXT sqlcipher_ext_provider_setup(p); #endif sqlcipher_register_provider(p); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_activate: called sqlcipher_register_provider(%p)",p); } sqlcipher_activate_count++; /* increment activation count */ sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_activate: leaving static master mutex"); sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_activate: left static master mutex"); } void sqlcipher_deactivate() { sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_deactivate: entering static master mutex"); sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_deactivate: entered static master mutex"); sqlcipher_activate_count--; /* if no connections are using sqlcipher, cleanup globals */ if(sqlcipher_activate_count < 1) { sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_deactivate: entering SQLCIPHER_MUTEX_PROVIDER"); sqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_deactivate: entered SQLCIPHER_MUTEX_PROVIDER"); if(default_provider != NULL) { sqlcipher_free(default_provider, sizeof(sqlcipher_provider)); default_provider = NULL; } sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_deactivate: leaving SQLCIPHER_MUTEX_PROVIDER"); sqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_deactivate: left SQLCIPHER_MUTEX_PROVIDER"); #ifdef SQLCIPHER_EXT sqlcipher_ext_provider_destroy(); #endif /* last connection closed, free mutexes */ if(sqlcipher_activate_count == 0) { int i; for(i = 0; i < SQLCIPHER_MUTEX_COUNT; i++) { sqlite3_mutex_free(sqlcipher_static_mutex[i]); } } sqlcipher_activate_count = 0; /* reset activation count */ } sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_deactivate: leaving static master mutex"); sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_deactivate: left static master mutex"); } /* constant time memset using volitile to avoid having the memset optimized out by the compiler. Note: As suggested by Joachim Schipper ([email protected]) */ void* sqlcipher_memset(void *v, unsigned char value, u64 len) { u64 i = 0; volatile unsigned char *a = v; if (v == NULL) return v; sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_memset: setting %p[0-%llu]=%d)", a, len, value); for(i = 0; i < len; i++) { a[i] = value; } return v; } /* constant time memory check tests every position of a memory segement matches a single value (i.e. the memory is all zeros) returns 0 if match, 1 of no match */ int sqlcipher_ismemset(const void *v, unsigned char value, u64 len) { const unsigned char *a = v; u64 i = 0, result = 0; for(i = 0; i < len; i++) { result |= a[i] ^ value; } return (result != 0); } /* constant time memory comparison routine. returns 0 if match, 1 if no match */ int sqlcipher_memcmp(const void *v0, const void *v1, int len) { const unsigned char *a0 = v0, *a1 = v1; int i = 0, result = 0; for(i = 0; i < len; i++) { result |= a0[i] ^ a1[i]; } return (result != 0); } void sqlcipher_mlock(void *ptr, u64 sz) { #ifndef OMIT_MEMLOCK #if defined(__unix__) || defined(__APPLE__) int rc; unsigned long pagesize = sysconf(_SC_PAGESIZE); unsigned long offset = (unsigned long) ptr % pagesize; if(ptr == NULL || sz == 0) return; sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_mem_lock: calling mlock(%p,%lu); _SC_PAGESIZE=%lu", ptr - offset, sz + offset, pagesize); rc = mlock(ptr - offset, sz + offset); if(rc!=0) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_mem_lock: mlock(%p,%lu) returned %d errno=%d", ptr - offset, sz + offset, rc, errno); } #elif defined(_WIN32) #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP)) int rc; sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_mem_lock: calling VirtualLock(%p,%d)", ptr, sz); rc = VirtualLock(ptr, sz); if(rc==0) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_mem_lock: VirtualLock(%p,%d) returned %d LastError=%d", ptr, sz, rc, GetLastError()); } #endif #endif #endif } void sqlcipher_munlock(void *ptr, u64 sz) { #ifndef OMIT_MEMLOCK #if defined(__unix__) || defined(__APPLE__) int rc; unsigned long pagesize = sysconf(_SC_PAGESIZE); unsigned long offset = (unsigned long) ptr % pagesize; if(ptr == NULL || sz == 0) return; sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_mem_unlock: calling munlock(%p,%lu)", ptr - offset, sz + offset); rc = munlock(ptr - offset, sz + offset); if(rc!=0) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_mem_unlock: munlock(%p,%lu) returned %d errno=%d", ptr - offset, sz + offset, rc, errno); } #elif defined(_WIN32) #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP)) int rc; sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_mem_lock: calling VirtualUnlock(%p,%d)", ptr, sz); rc = VirtualUnlock(ptr, sz); if(!rc) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_mem_unlock: VirtualUnlock(%p,%d) returned %d LastError=%d", ptr, sz, rc, GetLastError()); } #endif #endif #endif } /** * Free and wipe memory. Uses SQLites internal sqlite3_free so that memory * can be countend and memory leak detection works in the test suite. * If ptr is not null memory will be freed. * If sz is greater than zero, the memory will be overwritten with zero before it is freed * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the * memory segment so it can be paged */ void sqlcipher_free(void *ptr, u64 sz) { sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_free: calling sqlcipher_memset(%p,0,%llu)", ptr, sz); sqlcipher_memset(ptr, 0, sz); sqlcipher_munlock(ptr, sz); sqlite3_free(ptr); } /** * allocate memory. Uses sqlite's internall malloc wrapper so memory can be * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK * attempts to lock the memory pages so sensitive information won't be swapped */ void* sqlcipher_malloc(u64 sz) { void *ptr; sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_malloc: calling sqlite3Malloc(%llu)", sz); ptr = sqlite3Malloc(sz); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_malloc: calling sqlcipher_memset(%p,0,%llu)", ptr, sz); sqlcipher_memset(ptr, 0, sz); sqlcipher_mlock(ptr, sz); return ptr; } char* sqlcipher_version() { #ifdef CIPHER_VERSION_QUALIFIER char *version = sqlite3_mprintf("%s %s %s", CIPHER_XSTR(CIPHER_VERSION_NUMBER), CIPHER_XSTR(CIPHER_VERSION_QUALIFIER), CIPHER_XSTR(CIPHER_VERSION_BUILD)); #else char *version = sqlite3_mprintf("%s %s", CIPHER_XSTR(CIPHER_VERSION_NUMBER), CIPHER_XSTR(CIPHER_VERSION_BUILD)); #endif return version; } /** * Initialize new cipher_ctx struct. This function will allocate memory * for the cipher context and for the key * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ static int sqlcipher_cipher_ctx_init(codec_ctx *ctx, cipher_ctx **iCtx) { cipher_ctx *c_ctx; sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_cipher_ctx_init: allocating context"); *iCtx = (cipher_ctx *) sqlcipher_malloc(sizeof(cipher_ctx)); c_ctx = *iCtx; if(c_ctx == NULL) return SQLITE_NOMEM; sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_cipher_ctx_init: allocating key"); c_ctx->key = (unsigned char *) sqlcipher_malloc(ctx->key_sz); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_cipher_ctx_init: allocating hmac_key"); c_ctx->hmac_key = (unsigned char *) sqlcipher_malloc(ctx->key_sz); if(c_ctx->key == NULL) return SQLITE_NOMEM; if(c_ctx->hmac_key == NULL) return SQLITE_NOMEM; return SQLITE_OK; } /** * Free and wipe memory associated with a cipher_ctx */ static void sqlcipher_cipher_ctx_free(codec_ctx* ctx, cipher_ctx **iCtx) { cipher_ctx *c_ctx = *iCtx; sqlcipher_log(SQLCIPHER_LOG_DEBUG, "cipher_ctx_free: iCtx=%p", iCtx); sqlcipher_free(c_ctx->key, ctx->key_sz); sqlcipher_free(c_ctx->hmac_key, ctx->key_sz); sqlcipher_free(c_ctx->pass, c_ctx->pass_sz); sqlcipher_free(c_ctx->keyspec, ctx->keyspec_sz); sqlcipher_free(c_ctx, sizeof(cipher_ctx)); } static int sqlcipher_codec_ctx_reserve_setup(codec_ctx *ctx) { int base_reserve = ctx->iv_sz; /* base reserve size will be IV only */ int reserve = base_reserve; ctx->hmac_sz = ctx->provider->get_hmac_sz(ctx->provider_ctx, ctx->hmac_algorithm); if(sqlcipher_codec_ctx_get_use_hmac(ctx)) reserve += ctx->hmac_sz; /* if reserve will include hmac, update that size */ /* calculate the amount of reserve needed in even increments of the cipher block size */ reserve = ((reserve % ctx->block_sz) == 0) ? reserve : ((reserve / ctx->block_sz) + 1) * ctx->block_sz; sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_codec_ctx_reserve_setup: base_reserve=%d block_sz=%d md_size=%d reserve=%d", base_reserve, ctx->block_sz, ctx->hmac_sz, reserve); ctx->reserve_sz = reserve; return SQLITE_OK; } /** * Compare one cipher_ctx to another. * * returns 0 if all the parameters (except the derived key data) are the same * returns 1 otherwise */ static int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) { int are_equal = ( c1->pass_sz == c2->pass_sz && ( c1->pass == c2->pass || !sqlcipher_memcmp((const unsigned char*)c1->pass, (const unsigned char*)c2->pass, c1->pass_sz) )); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_cipher_ctx_cmp: c1=%p c2=%p sqlcipher_memcmp(c1->pass, c2_pass)=%d are_equal=%d", c1, c2, (c1->pass == NULL || c2->pass == NULL) ? -1 : sqlcipher_memcmp( (const unsigned char*)c1->pass, (const unsigned char*)c2->pass, c1->pass_sz ), are_equal ); return !are_equal; /* return 0 if they are the same, 1 otherwise */ } /** * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a * fully initialized context, you could copy it to write_ctx and all yet data * and pass information across * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ static int sqlcipher_cipher_ctx_copy(codec_ctx *ctx, cipher_ctx *target, cipher_ctx *source) { void *key = target->key; void *hmac_key = target->hmac_key; sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_cipher_ctx_copy: target=%p, source=%p", target, source); sqlcipher_free(target->pass, target->pass_sz); sqlcipher_free(target->keyspec, ctx->keyspec_sz); memcpy(target, source, sizeof(cipher_ctx)); target->key = key; /* restore pointer to previously allocated key data */ memcpy(target->key, source->key, ctx->key_sz); target->hmac_key = hmac_key; /* restore pointer to previously allocated hmac key data */ memcpy(target->hmac_key, source->hmac_key, ctx->key_sz); if(source->pass && source->pass_sz) { target->pass = sqlcipher_malloc(source->pass_sz); if(target->pass == NULL) return SQLITE_NOMEM; memcpy(target->pass, source->pass, source->pass_sz); } if(source->keyspec) { target->keyspec = sqlcipher_malloc(ctx->keyspec_sz); if(target->keyspec == NULL) return SQLITE_NOMEM; memcpy(target->keyspec, source->keyspec, ctx->keyspec_sz); } return SQLITE_OK; } /** * Set the keyspec for the cipher_ctx * * returns SQLITE_OK if assignment was successfull * returns SQLITE_NOMEM if an error occured allocating memory */ static int sqlcipher_cipher_ctx_set_keyspec(codec_ctx *ctx, cipher_ctx *c_ctx, const unsigned char *key) { /* free, zero existing pointers and size */ sqlcipher_free(c_ctx->keyspec, ctx->keyspec_sz); c_ctx->keyspec = NULL; c_ctx->keyspec = sqlcipher_malloc(ctx->keyspec_sz); if(c_ctx->keyspec == NULL) return SQLITE_NOMEM; c_ctx->keyspec[0] = 'x'; c_ctx->keyspec[1] = '\''; cipher_bin2hex(key, ctx->key_sz, c_ctx->keyspec + 2); cipher_bin2hex(ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->keyspec + (ctx->key_sz * 2) + 2); c_ctx->keyspec[ctx->keyspec_sz - 1] = '\''; return SQLITE_OK; } int sqlcipher_codec_get_store_pass(codec_ctx *ctx) { return ctx->store_pass; } void sqlcipher_codec_set_store_pass(codec_ctx *ctx, int value) { ctx->store_pass = value; } void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey) { *zKey = ctx->read_ctx->pass; *nKey = ctx->read_ctx->pass_sz; } static void sqlcipher_set_derive_key(codec_ctx *ctx, int derive) { if(ctx->read_ctx != NULL) ctx->read_ctx->derive_key = 1; if(ctx->write_ctx != NULL) ctx->write_ctx->derive_key = 1; } /** * Set the passphrase for the cipher_ctx * * returns SQLITE_OK if assignment was successfull * returns SQLITE_NOMEM if an error occured allocating memory */ static int sqlcipher_cipher_ctx_set_pass(cipher_ctx *ctx, const void *zKey, int nKey) { /* free, zero existing pointers and size */ sqlcipher_free(ctx->pass, ctx->pass_sz); ctx->pass = NULL; ctx->pass_sz = 0; if(zKey && nKey) { /* if new password is provided, copy it */ ctx->pass_sz = nKey; ctx->pass = sqlcipher_malloc(nKey); if(ctx->pass == NULL) return SQLITE_NOMEM; memcpy(ctx->pass, zKey, nKey); } return SQLITE_OK; } int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int for_ctx) { cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; int rc; if((rc = sqlcipher_cipher_ctx_set_pass(c_ctx, zKey, nKey)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_set_pass: error %d from sqlcipher_cipher_ctx_set_pass", rc); return rc; } c_ctx->derive_key = 1; if(for_ctx == 2) { if((rc = sqlcipher_cipher_ctx_copy(ctx, for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_set_pass: error %d from sqlcipher_cipher_ctx_copy", rc); return rc; } } return SQLITE_OK; } const char* sqlcipher_codec_ctx_get_cipher(codec_ctx *ctx) { return ctx->provider->get_cipher(ctx->provider_ctx); } /* set the global default KDF iteration */ void sqlcipher_set_default_kdf_iter(int iter) { default_kdf_iter = iter; } int sqlcipher_get_default_kdf_iter() { return default_kdf_iter; } int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter) { ctx->kdf_iter = kdf_iter; sqlcipher_set_derive_key(ctx, 1); return SQLITE_OK; } int sqlcipher_codec_ctx_get_kdf_iter(codec_ctx *ctx) { return ctx->kdf_iter; } int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter) { ctx->fast_kdf_iter = fast_kdf_iter; sqlcipher_set_derive_key(ctx, 1); return SQLITE_OK; } int sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx *ctx) { return ctx->fast_kdf_iter; } /* set the global default flag for HMAC */ void sqlcipher_set_default_use_hmac(int use) { if(use) default_flags |= CIPHER_FLAG_HMAC; else default_flags &= ~CIPHER_FLAG_HMAC; } int sqlcipher_get_default_use_hmac() { return (default_flags & CIPHER_FLAG_HMAC) != 0; } void sqlcipher_set_hmac_salt_mask(unsigned char mask) { hmac_salt_mask = mask; } unsigned char sqlcipher_get_hmac_salt_mask() { return hmac_salt_mask; } /* set the codec flag for whether this individual database should be using hmac */ int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use) { if(use) { sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_HMAC); } else { sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_HMAC); } return sqlcipher_codec_ctx_reserve_setup(ctx); } int sqlcipher_codec_ctx_get_use_hmac(codec_ctx *ctx) { return (ctx->flags & CIPHER_FLAG_HMAC) != 0; } /* the length of plaintext header size must be: * 1. greater than or equal to zero * 2. a multiple of the cipher block size * 3. less than the usable size of the first database page */ int sqlcipher_set_default_plaintext_header_size(int size) { default_plaintext_header_sz = size; return SQLITE_OK; } int sqlcipher_codec_ctx_set_plaintext_header_size(codec_ctx *ctx, int size) { if(size >= 0 && (size % ctx->block_sz) == 0 && size < (ctx->page_sz - ctx->reserve_sz)) { ctx->plaintext_header_sz = size; return SQLITE_OK; } ctx->plaintext_header_sz = -1; sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_set_plaintext_header_size: attempt to set invalid plantext_header_size %d", size); return SQLITE_ERROR; } int sqlcipher_get_default_plaintext_header_size() { return default_plaintext_header_sz; } int sqlcipher_codec_ctx_get_plaintext_header_size(codec_ctx *ctx) { return ctx->plaintext_header_sz; } /* manipulate HMAC algorithm */ int sqlcipher_set_default_hmac_algorithm(int algorithm) { default_hmac_algorithm = algorithm; return SQLITE_OK; } int sqlcipher_codec_ctx_set_hmac_algorithm(codec_ctx *ctx, int algorithm) { ctx->hmac_algorithm = algorithm; return sqlcipher_codec_ctx_reserve_setup(ctx); } int sqlcipher_get_default_hmac_algorithm() { return default_hmac_algorithm; } int sqlcipher_codec_ctx_get_hmac_algorithm(codec_ctx *ctx) { return ctx->hmac_algorithm; } /* manipulate KDF algorithm */ int sqlcipher_set_default_kdf_algorithm(int algorithm) { default_kdf_algorithm = algorithm; return SQLITE_OK; } int sqlcipher_codec_ctx_set_kdf_algorithm(codec_ctx *ctx, int algorithm) { ctx->kdf_algorithm = algorithm; return SQLITE_OK; } int sqlcipher_get_default_kdf_algorithm() { return default_kdf_algorithm; } int sqlcipher_codec_ctx_get_kdf_algorithm(codec_ctx *ctx) { return ctx->kdf_algorithm; } int sqlcipher_codec_ctx_set_flag(codec_ctx *ctx, unsigned int flag) { ctx->flags |= flag; return SQLITE_OK; } int sqlcipher_codec_ctx_unset_flag(codec_ctx *ctx, unsigned int flag) { ctx->flags &= ~flag; return SQLITE_OK; } int sqlcipher_codec_ctx_get_flag(codec_ctx *ctx, unsigned int flag) { return (ctx->flags & flag) != 0; } void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_set_error: ctx=%p, error=%d", ctx, error); sqlite3pager_error(ctx->pBt->pBt->pPager, error); ctx->pBt->pBt->db->errCode = error; } int sqlcipher_codec_ctx_get_reservesize(codec_ctx *ctx) { return ctx->reserve_sz; } void* sqlcipher_codec_ctx_get_data(codec_ctx *ctx) { return ctx->buffer; } static int sqlcipher_codec_ctx_init_kdf_salt(codec_ctx *ctx) { sqlite3_file *fd = sqlite3PagerFile(ctx->pBt->pBt->pPager); if(!ctx->need_kdf_salt) { return SQLITE_OK; /* don't reload salt when not needed */ } /* read salt from header, if present, otherwise generate a new random salt */ sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_codec_ctx_init_kdf_salt: obtaining salt"); if(fd == NULL || fd->pMethods == 0 || sqlite3OsRead(fd, ctx->kdf_salt, ctx->kdf_salt_sz, 0) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_codec_ctx_init_kdf_salt: unable to read salt from file header, generating random"); if(ctx->provider->random(ctx->provider_ctx, ctx->kdf_salt, ctx->kdf_salt_sz) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init_kdf_salt: error retrieving random bytes from provider"); return SQLITE_ERROR; } } ctx->need_kdf_salt = 0; return SQLITE_OK; } int sqlcipher_codec_ctx_set_kdf_salt(codec_ctx *ctx, unsigned char *salt, int size) { if(size >= ctx->kdf_salt_sz) { memcpy(ctx->kdf_salt, salt, ctx->kdf_salt_sz); ctx->need_kdf_salt = 0; return SQLITE_OK; } sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_set_kdf_salt: attempt to set salt of incorrect size %d", size); return SQLITE_ERROR; } int sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx, void** salt) { int rc = SQLITE_OK; if(ctx->need_kdf_salt) { if((rc = sqlcipher_codec_ctx_init_kdf_salt(ctx)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_get_kdf_salt: error %d from sqlcipher_codec_ctx_init_kdf_salt", rc); } } *salt = ctx->kdf_salt; return rc; } void sqlcipher_codec_get_keyspec(codec_ctx *ctx, void **zKey, int *nKey) { *zKey = ctx->read_ctx->keyspec; *nKey = ctx->keyspec_sz; } int sqlcipher_codec_ctx_set_pagesize(codec_ctx *ctx, int size) { if(!((size != 0) && ((size & (size - 1)) == 0)) || size < 512 || size > 65536) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "cipher_page_size not a power of 2 and between 512 and 65536 inclusive"); return SQLITE_ERROR; } /* attempt to free the existing page buffer */ sqlcipher_free(ctx->buffer,ctx->page_sz); ctx->page_sz = size; /* pre-allocate a page buffer of PageSize bytes. This will be used as a persistent buffer for encryption and decryption operations to avoid overhead of multiple memory allocations*/ ctx->buffer = sqlcipher_malloc(size); if(ctx->buffer == NULL) return SQLITE_NOMEM; return SQLITE_OK; } int sqlcipher_codec_ctx_get_pagesize(codec_ctx *ctx) { return ctx->page_sz; } void sqlcipher_set_default_pagesize(int page_size) { default_page_size = page_size; } int sqlcipher_get_default_pagesize() { return default_page_size; } void sqlcipher_set_mem_security(int on) { /* memory security can only be enabled, not disabled */ if(on) { mem_security_on = on; mem_security_activated = 0; } } int sqlcipher_get_mem_security() { return mem_security_on && mem_security_activated; } int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, const void *zKey, int nKey) { int rc; codec_ctx *ctx; sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_codec_ctx_init: allocating context"); *iCtx = sqlcipher_malloc(sizeof(codec_ctx)); ctx = *iCtx; if(ctx == NULL) return SQLITE_NOMEM; ctx->pBt = pDb->pBt; /* assign pointer to database btree structure */ /* allocate space for salt data. Then read the first 16 bytes directly off the database file. This is the salt for the key derivation function. If we get a short read allocate a new random salt value */ sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_codec_ctx_init: allocating kdf_salt"); ctx->kdf_salt_sz = FILE_HEADER_SZ; ctx->kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz); if(ctx->kdf_salt == NULL) return SQLITE_NOMEM; /* allocate space for separate hmac salt data. We want the HMAC derivation salt to be different than the encryption key derivation salt */ sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_codec_ctx_init: allocating hmac_kdf_salt"); ctx->hmac_kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz); if(ctx->hmac_kdf_salt == NULL) return SQLITE_NOMEM; /* setup default flags */ ctx->flags = default_flags; /* defer attempt to read KDF salt until first use */ ctx->need_kdf_salt = 1; /* setup the crypto provider */ sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_codec_ctx_init: allocating provider"); ctx->provider = (sqlcipher_provider *) sqlcipher_malloc(sizeof(sqlcipher_provider)); if(ctx->provider == NULL) return SQLITE_NOMEM; /* make a copy of the provider to be used for the duration of the context */ sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_codec_ctx_init: entering SQLCIPHER_MUTEX_PROVIDER"); sqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_codec_ctx_init: entered SQLCIPHER_MUTEX_PROVIDER"); memcpy(ctx->provider, default_provider, sizeof(sqlcipher_provider)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_codec_ctx_init: leaving SQLCIPHER_MUTEX_PROVIDER"); sqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); sqlcipher_log(SQLCIPHER_LOG_TRACE, "sqlcipher_codec_ctx_init: left SQLCIPHER_MUTEX_PROVIDER"); if((rc = ctx->provider->ctx_init(&ctx->provider_ctx)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d returned from ctx_init", rc); return rc; } ctx->key_sz = ctx->provider->get_key_sz(ctx->provider_ctx); ctx->iv_sz = ctx->provider->get_iv_sz(ctx->provider_ctx); ctx->block_sz = ctx->provider->get_block_sz(ctx->provider_ctx); /* establic the size for a hex-formated key specification, containing the raw encryption key and the salt used to generate it format. will be x'hexkey...hexsalt' so oversize by 3 bytes */ ctx->keyspec_sz = ((ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3; /* Always overwrite page size and set to the default because the first page of the database in encrypted and thus sqlite can't effectively determine the pagesize. this causes an issue in cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman */ if((rc = sqlcipher_codec_ctx_set_pagesize(ctx, default_page_size)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d returned from sqlcipher_codec_ctx_set_pagesize with %d", rc, default_page_size); return rc; } /* establish settings for the KDF iterations and fast (HMAC) KDF iterations */ if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, default_kdf_iter)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d setting default_kdf_iter %d", rc, default_kdf_iter); return rc; } if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d setting fast_kdf_iter to %d", rc, FAST_PBKDF2_ITER); return rc; } /* set the default HMAC and KDF algorithms which will determine the reserve size */ if((rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, default_hmac_algorithm)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d setting sqlcipher_codec_ctx_set_hmac_algorithm with %d", rc, default_hmac_algorithm); return rc; } /* Note that use_hmac is a special case that requires recalculation of page size so we call set_use_hmac to perform setup */ if((rc = sqlcipher_codec_ctx_set_use_hmac(ctx, default_flags & CIPHER_FLAG_HMAC)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d setting use_hmac %d", rc, default_flags & CIPHER_FLAG_HMAC); return rc; } if((rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, default_kdf_algorithm)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d setting sqlcipher_codec_ctx_set_kdf_algorithm with %d", rc, default_kdf_algorithm); return rc; } /* setup the default plaintext header size */ if((rc = sqlcipher_codec_ctx_set_plaintext_header_size(ctx, default_plaintext_header_sz)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d setting sqlcipher_codec_ctx_set_plaintext_header_size with %d", rc, default_plaintext_header_sz); return rc; } /* initialize the read and write sub-contexts. this must happen after key_sz is established */ if((rc = sqlcipher_cipher_ctx_init(ctx, &ctx->read_ctx)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d initializing read_ctx", rc); return rc; } if((rc = sqlcipher_cipher_ctx_init(ctx, &ctx->write_ctx)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d initializing write_ctx", rc); return rc; } /* set the key material on one of the sub cipher contexts and sync them up */ if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d setting pass key", rc); return rc; } if((rc = sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_ctx_init: error %d copying write_ctx to read_ctx", rc); return rc; } return SQLITE_OK; } /** * Free and wipe memory associated with a cipher_ctx, including the allocated * read_ctx and write_ctx. */ void sqlcipher_codec_ctx_free(codec_ctx **iCtx) { codec_ctx *ctx = *iCtx; sqlcipher_log(SQLCIPHER_LOG_DEBUG, "codec_ctx_free: iCtx=%p", iCtx); sqlcipher_free(ctx->kdf_salt, ctx->kdf_salt_sz); sqlcipher_free(ctx->hmac_kdf_salt, ctx->kdf_salt_sz); sqlcipher_free(ctx->buffer, ctx->page_sz); ctx->provider->ctx_free(&ctx->provider_ctx); sqlcipher_free(ctx->provider, sizeof(sqlcipher_provider)); sqlcipher_cipher_ctx_free(ctx, &ctx->read_ctx); sqlcipher_cipher_ctx_free(ctx, &ctx->write_ctx); sqlcipher_free(ctx, sizeof(codec_ctx)); } /** convert a 32bit unsigned integer to little endian byte ordering */ static void sqlcipher_put4byte_le(unsigned char *p, u32 v) { p[0] = (u8)v; p[1] = (u8)(v>>8); p[2] = (u8)(v>>16); p[3] = (u8)(v>>24); } static int sqlcipher_page_hmac(codec_ctx *ctx, cipher_ctx *c_ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) { unsigned char pgno_raw[sizeof(pgno)]; /* we may convert page number to consistent representation before calculating MAC for compatibility across big-endian and little-endian platforms. Note: The public release of sqlcipher 2.0.0 to 2.0.6 had a bug where the bytes of pgno were used directly in the MAC. SQLCipher convert's to little endian by default to preserve backwards compatibility on the most popular platforms, but can optionally be configured to use either big endian or native byte ordering via pragma. */ if(ctx->flags & CIPHER_FLAG_LE_PGNO) { /* compute hmac using little endian pgno*/ sqlcipher_put4byte_le(pgno_raw, pgno); } else if(ctx->flags & CIPHER_FLAG_BE_PGNO) { /* compute hmac using big endian pgno */ sqlite3Put4byte(pgno_raw, pgno); /* sqlite3Put4byte converts 32bit uint to big endian */ } else { /* use native byte ordering */ memcpy(pgno_raw, &pgno, sizeof(pgno)); } /* include the encrypted page data, initialization vector, and page number in HMAC. This will prevent both tampering with the ciphertext, manipulation of the IV, or resequencing otherwise valid pages out of order in a database */ return ctx->provider->hmac( ctx->provider_ctx, ctx->hmac_algorithm, c_ctx->hmac_key, ctx->key_sz, in, in_sz, (unsigned char*) &pgno_raw, sizeof(pgno), out); } /* * ctx - codec context * pgno - page number in database * size - size in bytes of input and output buffers * mode - 1 to encrypt, 0 to decrypt * in - pointer to input bytes * out - pouter to output bytes */ int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) { cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start; int size; /* calculate some required positions into various buffers */ size = page_sz - ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */ iv_out = out + size; iv_in = in + size; /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain random bytes. note, these pointers are only valid when using hmac */ hmac_in = in + size + ctx->iv_sz; hmac_out = out + size + ctx->iv_sz; out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */ sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_page_cipher: pgno=%d, mode=%d, size=%d", pgno, mode, size); CODEC_HEXDUMP("sqlcipher_page_cipher: input page data", in, page_sz); /* the key size should never be zero. If it is, error out. */ if(ctx->key_sz == 0) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_page_cipher: error possible context corruption, key_sz is zero for pgno=%d", pgno); goto error; } if(mode == CIPHER_ENCRYPT) { /* start at front of the reserve block, write random data to the end */ if(ctx->provider->random(ctx->provider_ctx, iv_out, ctx->reserve_sz) != SQLITE_OK) goto error; } else { /* CIPHER_DECRYPT */ memcpy(iv_out, iv_in, ctx->iv_sz); /* copy the iv from the input to output buffer */ } if((ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_DECRYPT) && !ctx->skip_read_hmac) { if(sqlcipher_page_hmac(ctx, c_ctx, pgno, in, size + ctx->iv_sz, hmac_out) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_page_cipher: hmac operation on decrypt failed for pgno=%d", pgno); goto error; } sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_page_cipher: comparing hmac on in=%p out=%p hmac_sz=%d", hmac_in, hmac_out, ctx->hmac_sz); if(sqlcipher_memcmp(hmac_in, hmac_out, ctx->hmac_sz) != 0) { /* the hmac check failed */ if(sqlite3BtreeGetAutoVacuum(ctx->pBt) != BTREE_AUTOVACUUM_NONE && sqlcipher_ismemset(in, 0, page_sz) == 0) { /* first check if the entire contents of the page is zeros. If so, this page resulted from a short read (i.e. sqlite attempted to pull a page after the end of the file. these short read failures must be ignored for autovaccum mode to work so wipe the output buffer and return SQLITE_OK to skip the decryption step. */ sqlcipher_log(SQLCIPHER_LOG_WARN, "sqlcipher_page_cipher: zeroed page (short read) for pgno %d, encryption but returning SQLITE_OK", pgno); sqlcipher_memset(out, 0, page_sz); return SQLITE_OK; } else { /* if the page memory is not all zeros, it means the there was data and a hmac on the page. since the check failed, the page was either tampered with or corrupted. wipe the output buffer, and return SQLITE_ERROR to the caller */ sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_page_cipher: hmac check failed for pgno=%d returning SQLITE_ERROR", pgno); goto error; } } } if(ctx->provider->cipher(ctx->provider_ctx, mode, c_ctx->key, ctx->key_sz, iv_out, in, size, out) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_page_cipher: cipher operation mode=%d failed for pgno=%d returning SQLITE_ERROR", mode, pgno); goto error; }; if((ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_ENCRYPT)) { if(sqlcipher_page_hmac(ctx, c_ctx, pgno, out_start, size + ctx->iv_sz, hmac_out) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_page_cipher: hmac operation on encrypt failed for pgno=%d", pgno); goto error; }; } CODEC_HEXDUMP("sqlcipher_page_cipher: output page data", out_start, page_sz); return SQLITE_OK; error: sqlcipher_memset(out, 0, page_sz); return SQLITE_ERROR; } /** * Derive an encryption key for a cipher contex key based on the raw password. * * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill * the key (i.e 64 hex chars for a 256 bit key) then the key data will be used directly. * Else, if the raw key data is formated as x'hex' and there are exactly enough hex chars to fill * the key and the salt (i.e 92 hex chars for a 256 bit key and 16 byte salt) then it will be unpacked * as the key followed by the salt. * * Otherwise, a key data will be derived using PBKDF2 * * returns SQLITE_OK if initialization was successful * returns SQLITE_ERROR if the key could't be derived (for instance if pass is NULL or pass_sz is 0) */ static int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) { int rc; sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_cipher_ctx_key_derive: ctx->kdf_salt_sz=%d ctx->kdf_iter=%d ctx->fast_kdf_iter=%d ctx->key_sz=%d", ctx->kdf_salt_sz, ctx->kdf_iter, ctx->fast_kdf_iter, ctx->key_sz); if(c_ctx->pass && c_ctx->pass_sz) { /* if key material is present on the context for derivation */ /* if necessary, initialize the salt from the header or random source */ if(ctx->need_kdf_salt) { if((rc = sqlcipher_codec_ctx_init_kdf_salt(ctx)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_cipher_ctx_key_derive: error %d from sqlcipher_codec_ctx_init_kdf_salt", rc); return rc; } } if (c_ctx->pass_sz == ((ctx->key_sz * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, ctx->key_sz * 2)) { int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */ const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */ sqlcipher_log(SQLCIPHER_LOG_DEBUG, "cipher_ctx_key_derive: using raw key from hex"); cipher_hex2bin(z, n, c_ctx->key); } else if (c_ctx->pass_sz == (((ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, (ctx->key_sz + ctx->kdf_salt_sz) * 2)) { const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */ sqlcipher_log(SQLCIPHER_LOG_DEBUG, "cipher_ctx_key_derive: using raw key from hex"); cipher_hex2bin(z, (ctx->key_sz * 2), c_ctx->key); cipher_hex2bin(z + (ctx->key_sz * 2), (ctx->kdf_salt_sz * 2), ctx->kdf_salt); } else { sqlcipher_log(SQLCIPHER_LOG_DEBUG, "cipher_ctx_key_derive: deriving key using full PBKDF2 with %d iterations", ctx->kdf_iter); if(ctx->provider->kdf(ctx->provider_ctx, ctx->kdf_algorithm, c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, ctx->kdf_iter, ctx->key_sz, c_ctx->key) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "cipher_ctx_key_derive: error occurred from provider kdf generating encryption key"); return SQLITE_ERROR; } } /* set the context "keyspec" containing the hex-formatted key and salt to be used when attaching databases */ if((rc = sqlcipher_cipher_ctx_set_keyspec(ctx, c_ctx, c_ctx->key)) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_cipher_ctx_key_derive: error %d from sqlcipher_cipher_ctx_set_keyspec", rc); return rc; } /* if this context is setup to use hmac checks, generate a seperate and different key for HMAC. In this case, we use the output of the previous KDF as the input to this KDF run. This ensures a distinct but predictable HMAC key. */ if(ctx->flags & CIPHER_FLAG_HMAC) { int i; /* start by copying the kdf key into the hmac salt slot then XOR it with the fixed hmac salt defined at compile time this ensures that the salt passed in to derive the hmac key, while easy to derive and publically known, is not the same as the salt used to generate the encryption key */ memcpy(ctx->hmac_kdf_salt, ctx->kdf_salt, ctx->kdf_salt_sz); for(i = 0; i < ctx->kdf_salt_sz; i++) { ctx->hmac_kdf_salt[i] ^= hmac_salt_mask; } sqlcipher_log(SQLCIPHER_LOG_DEBUG, "cipher_ctx_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations", ctx->fast_kdf_iter); if(ctx->provider->kdf(ctx->provider_ctx, ctx->kdf_algorithm, c_ctx->key, ctx->key_sz, ctx->hmac_kdf_salt, ctx->kdf_salt_sz, ctx->fast_kdf_iter, ctx->key_sz, c_ctx->hmac_key) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "cipher_ctx_key_derive: error occurred from provider kdf generating HMAC key"); return SQLITE_ERROR; } } c_ctx->derive_key = 0; return SQLITE_OK; } sqlcipher_log(SQLCIPHER_LOG_ERROR, "cipher_ctx_key_derive: key material is not present on the context for key derivation"); return SQLITE_ERROR; } int sqlcipher_codec_key_derive(codec_ctx *ctx) { /* derive key on first use if necessary */ if(ctx->read_ctx->derive_key) { if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->read_ctx) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_key_derive: error occurred deriving read_ctx key"); return SQLITE_ERROR; } } if(ctx->write_ctx->derive_key) { if(sqlcipher_cipher_ctx_cmp(ctx->write_ctx, ctx->read_ctx) == 0) { /* the relevant parameters are the same, just copy read key */ if(sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_key_derive: error occurred copying read_ctx to write_ctx"); return SQLITE_ERROR; } } else { if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->write_ctx) != SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_key_derive: error occurred deriving write_ctx key"); return SQLITE_ERROR; } } } /* TODO: wipe and free passphrase after key derivation */ if(ctx->store_pass != 1) { sqlcipher_cipher_ctx_set_pass(ctx->read_ctx, NULL, 0); sqlcipher_cipher_ctx_set_pass(ctx->write_ctx, NULL, 0); } return SQLITE_OK; } int sqlcipher_codec_key_copy(codec_ctx *ctx, int source) { if(source == CIPHER_READ_CTX) { return sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx); } else { return sqlcipher_cipher_ctx_copy(ctx, ctx->read_ctx, ctx->write_ctx); } } const char* sqlcipher_codec_get_cipher_provider(codec_ctx *ctx) { return ctx->provider->get_provider_name(ctx->provider_ctx); } static int sqlcipher_check_connection(const char *filename, char *key, int key_sz, char *sql, int *user_version, char** journal_mode) { int rc; sqlite3 *db = NULL; sqlite3_stmt *statement = NULL; char *query_journal_mode = "PRAGMA journal_mode;"; char *query_user_version = "PRAGMA user_version;"; rc = sqlite3_open(filename, &db); if(rc != SQLITE_OK) goto cleanup; rc = sqlite3_key(db, key, key_sz); if(rc != SQLITE_OK) goto cleanup; rc = sqlite3_exec(db, sql, NULL, NULL, NULL); if(rc != SQLITE_OK) goto cleanup; /* start by querying the user version. this will fail if the key is incorrect */ rc = sqlite3_prepare(db, query_user_version, -1, &statement, NULL); if(rc != SQLITE_OK) goto cleanup; rc = sqlite3_step(statement); if(rc == SQLITE_ROW) { *user_version = sqlite3_column_int(statement, 0); } else { goto cleanup; } sqlite3_finalize(statement); rc = sqlite3_prepare(db, query_journal_mode, -1, &statement, NULL); if(rc != SQLITE_OK) goto cleanup; rc = sqlite3_step(statement); if(rc == SQLITE_ROW) { *journal_mode = sqlite3_mprintf("%s", sqlite3_column_text(statement, 0)); } else { goto cleanup; } rc = SQLITE_OK; /* cleanup will finalize open statement */ cleanup: if(statement) sqlite3_finalize(statement); if(db) sqlite3_close(db); return rc; } int sqlcipher_codec_ctx_integrity_check(codec_ctx *ctx, Parse *pParse, char *column) { Pgno page = 1; int rc = 0; char *result; unsigned char *hmac_out = NULL; sqlite3_file *fd = sqlite3PagerFile(ctx->pBt->pBt->pPager); i64 file_sz; Vdbe *v = sqlite3GetVdbe(pParse); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, column, SQLITE_STATIC); if(fd == NULL || fd->pMethods == 0) { sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "database file is undefined", P4_TRANSIENT); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); goto cleanup; } if(!(ctx->flags & CIPHER_FLAG_HMAC)) { sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "HMAC is not enabled, unable to integrity check", P4_TRANSIENT); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); goto cleanup; } if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) { sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "unable to derive keys", P4_TRANSIENT); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); goto cleanup; } sqlite3OsFileSize(fd, &file_sz); hmac_out = sqlcipher_malloc(ctx->hmac_sz); for(page = 1; page <= file_sz / ctx->page_sz; page++) { i64 offset = (page - 1) * ctx->page_sz; int payload_sz = ctx->page_sz - ctx->reserve_sz + ctx->iv_sz; int read_sz = ctx->page_sz; /* skip integrity check on PAGER_MJ_PGNO since it will have no valid content */ if(sqlite3pager_is_mj_pgno(ctx->pBt->pBt->pPager, page)) continue; if(page==1) { int page1_offset = ctx->plaintext_header_sz ? ctx->plaintext_header_sz : FILE_HEADER_SZ; read_sz = read_sz - page1_offset; payload_sz = payload_sz - page1_offset; offset += page1_offset; } sqlcipher_memset(ctx->buffer, 0, ctx->page_sz); sqlcipher_memset(hmac_out, 0, ctx->hmac_sz); if(sqlite3OsRead(fd, ctx->buffer, read_sz, offset) != SQLITE_OK) { result = sqlite3_mprintf("error reading %d bytes from file page %d at offset %d", read_sz, page, offset); sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } else if(sqlcipher_page_hmac(ctx, ctx->read_ctx, page, ctx->buffer, payload_sz, hmac_out) != SQLITE_OK) { result = sqlite3_mprintf("HMAC operation failed for page %d", page); sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } else if(sqlcipher_memcmp(ctx->buffer + payload_sz, hmac_out, ctx->hmac_sz) != 0) { result = sqlite3_mprintf("HMAC verification failed for page %d", page); sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } } if(file_sz % ctx->page_sz != 0) { result = sqlite3_mprintf("page %d has an invalid size of %lld bytes", page, file_sz - ((file_sz / ctx->page_sz) * ctx->page_sz)); sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } cleanup: if(hmac_out != NULL) sqlcipher_free(hmac_out, ctx->hmac_sz); return SQLITE_OK; } int sqlcipher_codec_ctx_migrate(codec_ctx *ctx) { int i, pass_sz, keyspec_sz, nRes, user_version, rc, oflags; Db *pDb = 0; sqlite3 *db = ctx->pBt->db; const char *db_filename = sqlite3_db_filename(db, "main"); char *set_user_version = NULL, *pass = NULL, *attach_command = NULL, *migrated_db_filename = NULL, *keyspec = NULL, *temp = NULL, *journal_mode = NULL, *set_journal_mode = NULL, *pragma_compat = NULL; Btree *pDest = NULL, *pSrc = NULL; sqlite3_file *srcfile, *destfile; #if defined(_WIN32) || defined(SQLITE_OS_WINRT) LPWSTR w_db_filename = NULL, w_migrated_db_filename = NULL; int w_db_filename_sz = 0, w_migrated_db_filename_sz = 0; #endif pass_sz = keyspec_sz = rc = user_version = 0; if(!db_filename || sqlite3Strlen30(db_filename) < 1) goto cleanup; /* exit immediately if this is an in memory database */ /* pull the provided password / key material off the current codec context */ pass_sz = ctx->read_ctx->pass_sz; pass = sqlcipher_malloc(pass_sz+1); memset(pass, 0, pass_sz+1); memcpy(pass, ctx->read_ctx->pass, pass_sz); /* Version 4 - current, no upgrade required, so exit immediately */ rc = sqlcipher_check_connection(db_filename, pass, pass_sz, "", &user_version, &journal_mode); if(rc == SQLITE_OK){ sqlcipher_log(SQLCIPHER_LOG_DEBUG, "No upgrade required - exiting"); goto cleanup; } for(i = 3; i > 0; i--) { pragma_compat = sqlite3_mprintf("PRAGMA cipher_compatibility = %d;", i); rc = sqlcipher_check_connection(db_filename, pass, pass_sz, pragma_compat, &user_version, &journal_mode); if(rc == SQLITE_OK) { sqlcipher_log(SQLCIPHER_LOG_DEBUG, "Version %d format found", i); goto migrate; } if(pragma_compat) sqlcipher_free(pragma_compat, sqlite3Strlen30(pragma_compat)); pragma_compat = NULL; } /* if we exit the loop normally we failed to determine the version, this is an error */ sqlcipher_log(SQLCIPHER_LOG_ERROR, "Upgrade format not determined"); goto handle_error; migrate: temp = sqlite3_mprintf("%s-migrated", db_filename); /* overallocate migrated_db_filename, because sqlite3OsOpen will read past the null terminator * to determine whether the filename was URI formatted */ migrated_db_filename = sqlcipher_malloc(sqlite3Strlen30(temp)+2); memcpy(migrated_db_filename, temp, sqlite3Strlen30(temp)); sqlcipher_free(temp, sqlite3Strlen30(temp)); attach_command = sqlite3_mprintf("ATTACH DATABASE '%s' as migrate;", migrated_db_filename, pass); set_user_version = sqlite3_mprintf("PRAGMA migrate.user_version = %d;", user_version); rc = sqlite3_exec(db, pragma_compat, NULL, NULL, NULL); if(rc != SQLITE_OK){ sqlcipher_log(SQLCIPHER_LOG_ERROR, "set compatibility mode failed, error code %d", rc); goto handle_error; } /* force journal mode to DELETE, we will set it back later if different */ rc = sqlite3_exec(db, "PRAGMA journal_mode = delete;", NULL, NULL, NULL); if(rc != SQLITE_OK){ sqlcipher_log(SQLCIPHER_LOG_ERROR, "force journal mode DELETE failed, error code %d", rc); goto handle_error; } rc = sqlite3_exec(db, attach_command, NULL, NULL, NULL); if(rc != SQLITE_OK){ sqlcipher_log(SQLCIPHER_LOG_ERROR, "attach failed, error code %d", rc); goto handle_error; } rc = sqlite3_key_v2(db, "migrate", pass, pass_sz); if(rc != SQLITE_OK){ sqlcipher_log(SQLCIPHER_LOG_ERROR, "keying attached database failed, error code %d", rc); goto handle_error; } rc = sqlite3_exec(db, "SELECT sqlcipher_export('migrate');", NULL, NULL, NULL); if(rc != SQLITE_OK){ sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_export failed, error code %d", rc); goto handle_error; } #ifdef SQLCIPHER_TEST if((sqlcipher_get_test_flags() & TEST_FAIL_MIGRATE) > 0) { rc = SQLITE_ERROR; sqlcipher_log(SQLCIPHER_LOG_ERROR, "simulated migrate failure, error code %d", rc); goto handle_error; } #endif rc = sqlite3_exec(db, set_user_version, NULL, NULL, NULL); if(rc != SQLITE_OK){ sqlcipher_log(SQLCIPHER_LOG_ERROR, "set user version failed, error code %d", rc); goto handle_error; } if( !db->autoCommit ){ sqlcipher_log(SQLCIPHER_LOG_ERROR, "cannot migrate from within a transaction"); goto handle_error; } if( db->nVdbeActive>1 ){ sqlcipher_log(SQLCIPHER_LOG_ERROR, "cannot migrate - SQL statements in progress"); goto handle_error; } pDest = db->aDb[0].pBt; pDb = &(db->aDb[db->nDb-1]); pSrc = pDb->pBt; nRes = sqlite3BtreeGetRequestedReserve(pSrc); /* unset the BTS_PAGESIZE_FIXED flag to avoid SQLITE_READONLY */ pDest->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; rc = sqlite3BtreeSetPageSize(pDest, default_page_size, nRes, 0); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "set btree page size to %d res %d rc %d", default_page_size, nRes, rc); if( rc!=SQLITE_OK ) goto handle_error; sqlite3CodecGetKey(db, db->nDb - 1, (void**)&keyspec, &keyspec_sz); sqlite3CodecAttach(db, 0, keyspec, keyspec_sz); srcfile = sqlite3PagerFile(pSrc->pBt->pPager); destfile = sqlite3PagerFile(pDest->pBt->pPager); sqlite3OsClose(srcfile); sqlite3OsClose(destfile); #if defined(_WIN32) || defined(SQLITE_OS_WINRT) sqlcipher_log(SQLCIPHER_LOG_DEBUG, "performing windows MoveFileExA"); w_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) db_filename, -1, NULL, 0); w_db_filename = sqlcipher_malloc(w_db_filename_sz * sizeof(wchar_t)); w_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) db_filename, -1, (const LPWSTR) w_db_filename, w_db_filename_sz); w_migrated_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) migrated_db_filename, -1, NULL, 0); w_migrated_db_filename = sqlcipher_malloc(w_migrated_db_filename_sz * sizeof(wchar_t)); w_migrated_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) migrated_db_filename, -1, (const LPWSTR) w_migrated_db_filename, w_migrated_db_filename_sz); if(!MoveFileExW(w_migrated_db_filename, w_db_filename, MOVEFILE_REPLACE_EXISTING)) { rc = SQLITE_ERROR; sqlcipher_log(SQLCIPHER_LOG_ERROR, "error occurred while renaming %d", rc); goto handle_error; } #else sqlcipher_log(SQLCIPHER_LOG_DEBUG, "performing POSIX rename"); if ((rc = rename(migrated_db_filename, db_filename)) != 0) { sqlcipher_log(SQLCIPHER_LOG_ERROR, "error occurred while renaming %d", rc); goto handle_error; } #endif sqlcipher_log(SQLCIPHER_LOG_DEBUG, "renamed migration database %s to main database %s: %d", migrated_db_filename, db_filename, rc); rc = sqlite3OsOpen(db->pVfs, migrated_db_filename, srcfile, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_DB, &oflags); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "reopened migration database: %d", rc); if( rc!=SQLITE_OK ) goto handle_error; rc = sqlite3OsOpen(db->pVfs, db_filename, destfile, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_DB, &oflags); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "reopened main database: %d", rc); if( rc!=SQLITE_OK ) goto handle_error; sqlite3pager_reset(pDest->pBt->pPager); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "reset pager"); rc = sqlite3_exec(db, "DETACH DATABASE migrate;", NULL, NULL, NULL); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "DETACH DATABASE called %d", rc); if(rc != SQLITE_OK) goto cleanup; sqlite3ResetAllSchemasOfConnection(db); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "reset all schemas"); set_journal_mode = sqlite3_mprintf("PRAGMA journal_mode = %s;", journal_mode); rc = sqlite3_exec(db, set_journal_mode, NULL, NULL, NULL); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "%s: %d", set_journal_mode, rc); if( rc!=SQLITE_OK ) goto handle_error; goto cleanup; handle_error: sqlcipher_log(SQLCIPHER_LOG_ERROR, "An error occurred attempting to migrate the database - last error %d", rc); cleanup: if(migrated_db_filename) { int del_rc = sqlite3OsDelete(db->pVfs, migrated_db_filename, 0); sqlcipher_log(SQLCIPHER_LOG_DEBUG, "deleted migration database: %d", del_rc); } if(pass) sqlcipher_free(pass, pass_sz); if(attach_command) sqlcipher_free(attach_command, sqlite3Strlen30(attach_command)); if(migrated_db_filename) sqlcipher_free(migrated_db_filename, sqlite3Strlen30(migrated_db_filename)); if(set_user_version) sqlcipher_free(set_user_version, sqlite3Strlen30(set_user_version)); if(set_journal_mode) sqlcipher_free(set_journal_mode, sqlite3Strlen30(set_journal_mode)); if(journal_mode) sqlcipher_free(journal_mode, sqlite3Strlen30(journal_mode)); if(pragma_compat) sqlcipher_free(pragma_compat, sqlite3Strlen30(pragma_compat)); #if defined(_WIN32) || defined(SQLITE_OS_WINRT) if(w_db_filename) sqlcipher_free(w_db_filename, w_db_filename_sz); if(w_migrated_db_filename) sqlcipher_free(w_migrated_db_filename, w_migrated_db_filename_sz); #endif return rc; } int sqlcipher_codec_add_random(codec_ctx *ctx, const char *zRight, int random_sz){ const char *suffix = &zRight[random_sz-1]; int n = random_sz - 3; /* adjust for leading x' and tailing ' */ if (n > 0 && sqlite3StrNICmp((const char *)zRight ,"x'", 2) == 0 && sqlite3StrNICmp(suffix, "'", 1) == 0 && n % 2 == 0) { int rc = 0; int buffer_sz = n / 2; unsigned char *random; const unsigned char *z = (const unsigned char *)zRight + 2; /* adjust lead offset of x' */ sqlcipher_log(SQLCIPHER_LOG_DEBUG, "sqlcipher_codec_add_random: using raw random blob from hex"); random = sqlcipher_malloc(buffer_sz); memset(random, 0, buffer_sz); cipher_hex2bin(z, n, random); rc = ctx->provider->add_random(ctx->provider_ctx, random, buffer_sz); sqlcipher_free(random, buffer_sz); return rc; } sqlcipher_log(SQLCIPHER_LOG_ERROR, "sqlcipher_codec_add_random: attemt to add random with invalid format"); return SQLITE_ERROR; } #if !defined(SQLITE_OMIT_TRACE) static int sqlcipher_profile_callback(unsigned int trace, void *file, void *stmt, void *run_time){ FILE *f = (FILE*) file; char *fmt = "Elapsed time:%.3f ms - %s\n"; double elapsed = (*((sqlite3_uint64*)run_time))/1000000.0; #ifdef __ANDROID__ if(f == NULL) { __android_log_print(ANDROID_LOG_DEBUG, "sqlcipher", fmt, elapsed, sqlite3_sql((sqlite3_stmt*)stmt)); } #endif if(f) fprintf(f, fmt, elapsed, sqlite3_sql((sqlite3_stmt*)stmt)); return SQLITE_OK; } #endif int sqlcipher_cipher_profile(sqlite3 *db, const char *destination){ #if defined(SQLITE_OMIT_TRACE) return SQLITE_ERROR; #else FILE *f = NULL; if(sqlite3_stricmp(destination, "off") == 0){ sqlite3_trace_v2(db, 0, NULL, NULL); /* disable tracing */ } else { if(sqlite3_stricmp(destination, "stdout") == 0){ f = stdout; }else if(sqlite3_stricmp(destination, "stderr") == 0){ f = stderr; }else if(sqlite3_stricmp(destination, "logcat") == 0){ f = NULL; /* file pointer will be NULL indicating logcat on android */ }else{ #if !defined(SQLCIPHER_PROFILE_USE_FOPEN) && (defined(_WIN32) && (__STDC_VERSION__ > 199901L) || defined(SQLITE_OS_WINRT)) if(fopen_s(&f, destination, "a") != 0) return SQLITE_ERROR; #else if((f = fopen(destination, "a")) == 0) return SQLITE_ERROR; #endif } sqlite3_trace_v2(db, SQLITE_TRACE_PROFILE, sqlcipher_profile_callback, f); } return SQLITE_OK; #endif } int sqlcipher_codec_fips_status(codec_ctx *ctx) { return ctx->provider->fips_status(ctx->provider_ctx); } const char* sqlcipher_codec_get_provider_version(codec_ctx *ctx) { return ctx->provider->get_provider_version(ctx->provider_ctx); } #ifndef SQLCIPHER_OMIT_LOG /* constants from https://github.com/Alexpux/mingw-w64/blob/master/mingw-w64-crt/misc/gettimeofday.c */ #define FILETIME_1970 116444736000000000ull /* seconds between 1/1/1601 and 1/1/1970 */ #define HECTONANOSEC_PER_SEC 10000000ull void sqlcipher_log(unsigned int level, const char *message, ...) { va_list params; va_start(params, message); #ifdef CODEC_DEBUG #ifdef __ANDROID__ __android_log_vprint(ANDROID_LOG_DEBUG, "sqlcipher", message, params); #else vfprintf(stderr, message, params); fprintf(stderr, "\n"); #endif #endif if(level > sqlcipher_log_level || (sqlcipher_log_logcat == 0 && sqlcipher_log_file == NULL)) { /* no log target or tag not in included filters */ goto end; } if(sqlcipher_log_file != NULL){ char buffer[24]; struct tm tt; int ms; time_t sec; #ifdef _WIN32 SYSTEMTIME st; FILETIME ft; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); sec = (time_t) ((*((sqlite_int64*)&ft) - FILETIME_1970) / HECTONANOSEC_PER_SEC); ms = st.wMilliseconds; localtime_s(&tt, &sec); #else struct timeval tv; gettimeofday(&tv, NULL); sec = tv.tv_sec; ms = tv.tv_usec/1000.0; localtime_r(&sec, &tt); #endif if(strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tt)) { fprintf((FILE*)sqlcipher_log_file, "%s.%03d: ", buffer, ms); vfprintf((FILE*)sqlcipher_log_file, message, params); fprintf((FILE*)sqlcipher_log_file, "\n"); } } #ifdef __ANDROID__ if(sqlcipher_log_logcat) { __android_log_vprint(ANDROID_LOG_DEBUG, "sqlcipher", message, params); } #endif end: va_end(params); } #endif void sqlcipher_set_log_level(unsigned int level) { sqlcipher_log_level = level; } int sqlcipher_set_log(const char *destination){ #ifdef SQLCIPHER_OMIT_LOG return SQLITE_ERROR; #else /* close open trace file if it is not stdout or stderr, then reset trace settings */ if(sqlcipher_log_file != NULL && sqlcipher_log_file != stdout && sqlcipher_log_file != stderr) { fclose((FILE*)sqlcipher_log_file); } sqlcipher_log_file = NULL; sqlcipher_log_logcat = 0; if(sqlite3_stricmp(destination, "logcat") == 0){ sqlcipher_log_logcat = 1; } else if(sqlite3_stricmp(destination, "stdout") == 0){ sqlcipher_log_file = stdout; }else if(sqlite3_stricmp(destination, "stderr") == 0){ sqlcipher_log_file = stderr; }else if(sqlite3_stricmp(destination, "off") != 0){ #if !defined(SQLCIPHER_PROFILE_USE_FOPEN) && (defined(_WIN32) && (__STDC_VERSION__ > 199901L) || defined(SQLITE_OS_WINRT)) if(fopen_s(&sqlcipher_log_file, destination, "a") != 0) return SQLITE_ERROR; #else if((sqlcipher_log_file = fopen(destination, "a")) == 0) return SQLITE_ERROR; #endif } sqlcipher_log(SQLCIPHER_LOG_INFO, "sqlcipher_set_log: set log to %s", destination); return SQLITE_OK; #endif } #endif /* END SQLCIPHER */
the_stack_data/165767131.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'hadd_long2long2.cl' */ source_code = read_buffer("hadd_long2long2.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "hadd_long2long2", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_long2 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_long2)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_long2){{2, 2}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_long2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_long2), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_long2 *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_long2)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_long2){{2, 2}}; /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_long2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_long2), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_long2 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_long2)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_long2)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_long2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_long2), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_long2)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
the_stack_data/64394.c
#include <stdio.h> unsigned int mystery(unsigned int a, unsigned int b); // function prototype int main(void) { printf("%s", "Enter two positive integers: "); unsigned int x; // first integer unsigned int y; // second integer scanf("%u%u", &x, &y); printf("The result is %u\n", mystery(x, y)); } // Parameter b must be a positive integer // to prevent infinite recursion unsigned int mystery(unsigned int a, unsigned int b) { // base case if (1 == b) { return a; } else { // recursive step return a + mystery(a, b - 1); } } /************************************************************************** * (C) Copyright 1992-2015 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
the_stack_data/73573989.c
/* ============================================================================ Name : Euler.c Author : Jonathan Rivas Version : Copyright : Description : Problem #28 ============================================================================ */ #include <stdio.h> #include <stdlib.h> int main(void) { struct timeval stop, start; gettimeofday(&start, NULL); int sum = 0, n = 1, i, j; int size = 1001; sum = n; for(i = 2; i < size; i+=2){ for(j = 0; j< 4; j++){ n += i; sum += n; } } printf("diagonal sum = %d", sum); gettimeofday(&stop, NULL); printf("\ntook %lu usec\n", stop.tv_usec - start.tv_usec); return 0; }
the_stack_data/150139270.c
/* ** EPITECH PROJECT, 2021 ** my_isblank.c ** File description: ** Checks whether a character is blank or not. */ int my_isblank(char c) { return ((c == '\t' || c == ' ')); }
the_stack_data/202344.c
#include <stdio.h> int main() { int n; char letters_underlined[] = "LIFE IS NOT A PROBLEM TO BE SOLVED"; scanf("%d", &n); letters_underlined[n] = '\0'; printf("%s\n", letters_underlined); return 0; }
the_stack_data/454872.c
extern int __VERIFIER_nondet_int(); extern void abort(void); void reach_error(){} int id(int x) { if (x==0) return 0; return id(x-1) + 1; } int main(void) { int input = 25; int result = id(input); if (result != 25) { ERROR: {reach_error();abort();} } }
the_stack_data/87638831.c
/* * * Copyright (C) 2019, Broadband Forum * Copyright (C) 2017-2019 CommScope, Inc * * 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. * */ /** * \file coap_client.c * * Implements the client portion of Constrained Application Protocol transport for USP * */ #ifdef ENABLE_COAP // NOTE: This isn't strictly necessary as this file is not included in the build if CoAP is disabled #include <stdlib.h> #include <stdio.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <string.h> #include <net/if.h> #include <openssl/ssl.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/opensslv.h> #include "common_defs.h" #include "usp_coap.h" #include "usp_api.h" #include "usp-msg.pb-c.h" #include "msg_handler.h" #include "os_utils.h" #include "dllist.h" #include "dm_exec.h" #include "retry_wait.h" #include "usp_coap.h" #include "text_utils.h" #include "nu_ipaddr.h" #include "iso8601.h" //------------------------------------------------------------------------------------ // Mutex used to protect access to this component static pthread_mutex_t coap_access_mutex; //------------------------------------------------------------------------------ // Structure used to walk the CoAP option list. // It is used to maintain state between each CoAP option, and also return the current parsed option typedef struct { unsigned char *buf; // On input : pointer to option to parse // On output: pointer to next option to parse int len; // On input : length of buffer left for this option and following options // On output: length of buffer left for next options int cur_option; // On input : Last option parsed // On output: Option just parsed unsigned char *option_value; // On input : don't care // On output: pointer to buffer containing the values for the option just parsed int option_len; // On input : don't care // On output: length of the buffer containing the values for the option just parsed } option_walker_t; //------------------------------------------------------------------------------ // Buffer containing the textual cause of the error - to copy into the payload of an ACK or RST message static char coap_err_message[256]; //------------------------------------------------------------------------------ // Forward declarations. Note these are not static, because we need them in the symbol table for USP_LOG_Callstack() to show them int WalkCoapOption(option_walker_t *ow, parsed_pdu_t *pp); int ParseCoapOption(int option, unsigned char *buf, int len, parsed_pdu_t *pp); void AppendUriPath(char *path, int path_len, char *segment, int seg_len); void ParseBlock1Option(unsigned char *buf, int len, parsed_pdu_t *pp); bool ParseCoapUriQuery(char *uri_query, mtp_reply_to_t *mrt); unsigned ReadUnsignedOptionValue(unsigned char *buf, int len); pdu_block_size_t CalcBlockSize_Int2Pdu(int block_size); int CalcBlockSize_Pdu2Int(pdu_block_size_t pdu_block_size); int ReceiveDtlsHandshakePacket(SSL *ssl, BIO *rbio, int socket_fd, int timeout_in_sec); int SendDtlsRecordFragments(int socket_fd, unsigned char *buf, int len); /*********************************************************************//** ** ** COAP_Init ** ** Initialises this component ** ** \param None ** ** \return USP_ERR_OK if successful ** **************************************************************************/ int COAP_Init(void) { int err; // Exit if unable to initialise CoAP servers err = COAP_SERVER_Init(); if (err != USP_ERR_OK) { return err; } // Exit if unable to initialise CoAP clients err = COAP_CLIENT_Init(); if (err != USP_ERR_OK) { return err; } // Exit if unable to create mutex protecting access to this subsystem err = OS_UTILS_InitMutex(&coap_access_mutex); if (err != USP_ERR_OK) { return err; } return USP_ERR_OK; } /*********************************************************************//** ** ** COAP_Start ** ** Creates the SSL contexts used by this module ** ** \param None ** ** \return USP_ERR_OK if successful ** **************************************************************************/ int COAP_Start(void) { int err = USP_ERR_OK; COAP_LockMutex(); // Exit if unable to start CoAP servers err = COAP_SERVER_InitStart(); if (err != USP_ERR_OK) { goto exit; } // Exit if unable to start CoAP clients err = COAP_CLIENT_InitStart(); if (err != USP_ERR_OK) { goto exit; } // Code was successful err = USP_ERR_OK; exit: COAP_UnlockMutex(); return err; } /*********************************************************************//** ** ** COAP_Destroy ** ** Frees all memory used by this component ** ** \param None ** ** \return None ** **************************************************************************/ void COAP_Destroy(void) { COAP_LockMutex(); COAP_SERVER_Destroy(); COAP_CLIENT_Destroy(); COAP_UnlockMutex(); } /*********************************************************************//** ** ** COAP_UpdateAllSockSet ** ** Updates the set of all COAP socket fds to read/write from ** ** \param set - pointer to socket set structure to update with sockets to wait for activity on ** ** \return None ** **************************************************************************/ void COAP_UpdateAllSockSet(socket_set_t *set) { COAP_LockMutex(); COAP_SERVER_UpdateAllSockSet(set); COAP_CLIENT_UpdateAllSockSet(set); COAP_UnlockMutex(); } /*********************************************************************//** ** ** COAP_ProcessAllSocketActivity ** ** Processes the socket for the specified controller ** ** \param set - pointer to socket set structure containing the sockets which need processing ** ** \return Nothing ** **************************************************************************/ void COAP_ProcessAllSocketActivity(socket_set_t *set) { COAP_LockMutex(); // Exit if MTP thread has exited // NOTE: This check should be unnecessary, as this function is only called from the MTP thread if (is_coap_mtp_thread_exited) { COAP_UnlockMutex(); return; } COAP_CLIENT_ProcessAllSocketActivity(set); COAP_SERVER_ProcessAllSocketActivity(set); COAP_UnlockMutex(); } /*********************************************************************//** ** ** COAP_AreAllResponsesSent ** ** Determines whether all responses have been sent, and that there are no outstanding incoming messages ** ** \param None ** ** \return true if all responses have been sent ** **************************************************************************/ bool COAP_AreAllResponsesSent(void) { bool all_responses_sent; COAP_LockMutex(); // Exit if MTP thread has exited // NOTE: This check is not strictly necessary, as only the MTP thread should be calling this function if (is_coap_mtp_thread_exited) { COAP_UnlockMutex(); return true; } all_responses_sent = COAP_CLIENT_AreAllResponsesSent() && COAP_SERVER_AreNoOutstandingIncomingMessages(); COAP_UnlockMutex(); return all_responses_sent; } /*********************************************************************//** ** ** COAP_ReceivePdu ** ** Reads a CoAP PDU addressed to our CoAP client ** NOTE: This function is called by both CoAP client and server ** ** \param ssl - pointer to SSL object associated with the socket, or NULL if encryption is not enabled ** \param rbio - pointer to BIO object for reading ** \param socket_fd - socket on which to receive the PDU ** \param buf - pointer to buffer in which to read CoAP PDU ** \param buflen - length of buffer in which to read CoAP PDU ** ** \return Number of bytes read, or -1 if the remote server disconnected ** **************************************************************************/ int COAP_ReceivePdu(SSL *ssl, BIO *rbio, int socket_fd, unsigned char *buf, int buflen) { int err; int ssl_flags; int retry_count; int bytes_read; (void)rbio; // unused in this implementation if (ssl == NULL) { // Exit if unable to read the CoAP PDU into the buffer bytes_read = recv(socket_fd, buf, buflen, 0); if (bytes_read == -1) { USP_ERR_ERRNO("recv", errno); } return bytes_read; } // Code below is complex because a renegotiation could occur, and open SSL requires that we retry the EXACT same SSL call // We cope with this by retrying the SSL call until the retry has completed (or failed) // This code blocks until the retry has completed, or the retry has timed out #define ONE_SECOND_IN_MICROSECONDS (1000000) #define SSL_RETRY_SLEEP (ONE_SECOND_IN_MICROSECONDS/20) // Retry 20 times a second #define SSL_RETRY_TIMEOUT (5*ONE_SECOND_IN_MICROSECONDS) // Retry for upto 5 seconds #define MAX_SSL_RETRY_COUNT (SSL_RETRY_TIMEOUT/SSL_RETRY_SLEEP) retry_count = 0; while (retry_count < MAX_SSL_RETRY_COUNT) { // Exit if read some bytes successfully bytes_read = SSL_read(ssl, buf, buflen); if (bytes_read > 0) { return bytes_read; } // Determine whether to retry this call until the read has occurred - this is needed if a renegotiation occurs err = SSL_get_error(ssl, bytes_read); // Exit if CoAP peer has gracefully disconnected ssl_flags = SSL_get_shutdown(ssl); if ((bytes_read==0) || (ssl_flags & SSL_RECEIVED_SHUTDOWN)) { return -1; } // Log exceptional failure causes USP_LOG_ErrorSSL(__FUNCTION__, "SSL_read() failed", bytes_read, err); switch(err) { case SSL_ERROR_NONE: // NOTE: I don't think this case will ever get executed because bytes_read would be >= 0 // If there was no SSL error or no bytes to read, then assume the CoAP peer has gracefully disconnected if (bytes_read <= 0) { return -1; } return bytes_read; break; case SSL_ERROR_ZERO_RETURN: // Exit if CoAP server has disconnected // NOTE: I don't think this case will ever get executed because it would have been caught earlier at the (bytes_read==0) test return -1; break; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_X509_LOOKUP: usleep(SSL_RETRY_SLEEP); retry_count++; break; default: case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: // Exit if any other error occurred. Handle these the same as a disconnect return -1; break; } } // If the code gets here, then the retry timed out, so perform a disconnect USP_LOG_Error("%s: SSL Renegotiation timed out", __FUNCTION__); return -1; } /*********************************************************************//** ** ** COAP_SendPdu ** ** Sends a CoAP PDU ** NOTE: This function is called by both CoAP client and server ** ** \param ssl - pointer to SSL object associated with the socket, or NULL if encryption is not enabled ** \param wbio - pointer to BIO object for writing ** \param socket_fd - socket on which to send the PDU ** \param buf - pointer to buffer of data to send ** \param len - length of buffer of data to send ** ** \return USP_ERR_OK if successful ** **************************************************************************/ int COAP_SendPdu(SSL *ssl, BIO *wbio, int socket_fd, unsigned char *buf, int len) { int err; int retry_count; int ssl_flags; int bytes_sent = 0; (void)wbio; // unused in this implementation // Perform a simple send() if connection is not encrypted if (ssl == NULL) { bytes_sent = send(socket_fd, buf, len, 0); if (bytes_sent != len) { // NOTE: We have failed to send the new block. It will be retried by the retry mechanism if this is a client, or the remote client will retry USP_ERR_ERRNO("send", errno); return USP_ERR_OK; } return USP_ERR_OK; } // Code below is complex because a renegotiation could occur, and open SSL requires that we retry the EXACT same SSL call // We cope with this by retrying the SSL call until the retry has completed (or failed) // This code blocks until the retry has completed, or the retry has timed out retry_count = 0; while (retry_count < MAX_SSL_RETRY_COUNT) { // Try sending bytes_sent = SSL_write(ssl, buf, len); if (bytes_sent > 0) { return USP_ERR_OK;; } // Determine whether to retry this call until the write has occurred - this is needed if a renegotiation occurs err = SSL_get_error(ssl, bytes_sent); // Exit if peer has disconnected ssl_flags = SSL_get_shutdown(ssl); if ((bytes_sent==0) || (ssl_flags & SSL_RECEIVED_SHUTDOWN)) { USP_PROTOCOL("%s: Peer has disconnected", __FUNCTION__); return USP_ERR_INTERNAL_ERROR; } // Log exceptional failure causes USP_LOG_ErrorSSL(__FUNCTION__, "SSL_write() failed", bytes_sent, err); switch(err) { case SSL_ERROR_NONE: case SSL_ERROR_WANT_READ: // NOTE: I don't think these can occur. If they do and nothing was sent out, then the CoAP retry mechanism will fix it anyway. return USP_ERR_OK; break; case SSL_ERROR_WANT_WRITE: // Wait a while, then perform the renegotiation usleep(SSL_RETRY_SLEEP); retry_count++; break; default: case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: return USP_ERR_INTERNAL_ERROR; break; } } // If the code gets here, then SSL renegotiation failed USP_LOG_Error("%s: SSL Renegotiation timed out", __FUNCTION__); return USP_ERR_INTERNAL_ERROR; } /*********************************************************************//** ** ** COAP_WriteRst ** ** Writes a CoAP PDU containing a RST of the message to send ** RST is empty message with Code 0 ** ** \param message_id - message_id which this RST is a response to, or a message_id allocated by us, if one could not be parsed from the input PDU ** \param token - pointer to buffer containing token of received PDU that caused this RST ** \param token_len - length of buffer containing token of received PDU that caused this RST ** NOTE: if no token could be parsed from the input PDU, then the token will be empty ** \param buf - pointer to buffer in which to write the CoAP PDU ** \param len - length of buffer in which to write the CoAP PDU ** ** \return Number of bytes written to the CoAP PDU buffer ** **************************************************************************/ int COAP_WriteRst(int message_id, unsigned char *token, int token_len, unsigned char *buf, int len) { unsigned header = 0; unsigned char *p; // Calculate the header bytes MODIFY_BITS(31, 30, header, COAP_VERSION); MODIFY_BITS(29, 28, header, kPduType_Reset); MODIFY_BITS(27, 24, header, token_len); MODIFY_BITS(23, 16, header, kPduClientErrRespCode_BadRequest); MODIFY_BITS(15, 0, header, message_id); // Write the CoAP header bytes and token into the output buffer p = buf; WRITE_4_BYTES(p, header); memcpy(p, token, token_len); p += token_len; // Log what is going to be sent USP_PROTOCOL("%s: Sending CoAP RST (MID=%d)", __FUNCTION__, message_id); // Return the number of bytes written to the output buffer return p - buf; } /*********************************************************************//** ** ** COAP_CalcBlockOption ** ** Calculates the value of the Block1 option for this tx ** ** \param buf - pointer to buffer in which to write the block option's value. ** It is the callers responsibility to ensure that this is at least 3 bytes long. ** \param cur_block - Current block number to transmit ** \param is_more_blocks - Set to 1 if there are more blocks containing the USP record, 0 if this is the last block ** \param block_size - Size of the blocks containing the USP record ** ** \return Number of bytes written into the block option's value buffer ** **************************************************************************/ int COAP_CalcBlockOption(unsigned char *buf, int cur_block, int is_more_blocks, int block_size) { pdu_block_size_t pdu_block_size; int block_option_len; unsigned option = 0; // Convert the block size to the PDU enumeration pdu_block_size = CalcBlockSize_Int2Pdu(block_size); // Determine how many bytes to store in the block if (cur_block < 16) { block_option_len = 1; } else if (cur_block < 4096) { block_option_len = 2; } else { block_option_len = 3; } // Write the block option switch(block_option_len) { case 1: MODIFY_BITS(7, 4, option, cur_block); MODIFY_BITS(3, 3, option, is_more_blocks); MODIFY_BITS(2, 0, option, pdu_block_size); STORE_BYTE(buf, option); break; case 2: MODIFY_BITS(15, 4, option, cur_block); MODIFY_BITS(3, 3, option, is_more_blocks); MODIFY_BITS(2, 0, option, pdu_block_size); STORE_2_BYTES(buf, option); break; case 3: MODIFY_BITS(23, 4, option, cur_block); MODIFY_BITS(3, 3, option, is_more_blocks); MODIFY_BITS(2, 0, option, pdu_block_size); STORE_3_BYTES(buf, option); break; } return block_option_len; } /*********************************************************************//** ** ** COAP_WriteOption ** ** Writes the specified CoAP option to the specified buffer ** ** \param pdu_option - CoAP option to write ** \param option_data - pointer to buffer containing the data for the option to write ** \param len - number of bytes of option_data ** \param buf - pointer to output buffer in which to write option ** \param last_pdu_option - pointer to variable in which to return the CoAP option written by this function ** NOTE: This is necessary as CoAP uses a delta encoding for option numbers ** ** \return pointer to next byte in the output buffer after writing this option ** **************************************************************************/ unsigned char *COAP_WriteOption(pdu_option_t pdu_option, unsigned char *option_data, int len, unsigned char *buf, pdu_option_t *last_pdu_option) { int option_delta; int option_delta_ext = 0; int option_len; int option_len_ext = 0; unsigned option_header = 0; unsigned char *p; // Calculate option_delta, determining whether option_delta_ext is present option_delta = pdu_option - (*last_pdu_option); USP_ASSERT(option_delta >= 0); // Ensure that the caller attempts to write options in numeric order if (option_delta > 12) { USP_ASSERT(option_delta < 268); // This code does not cope with 16 bit option deltas option_delta_ext = option_delta - 13; option_delta = 13; } // Calculate option_len, determining whether option_len_ext is present option_len = len; if (option_len > 12) { USP_ASSERT(option_len < 268); // This code does not cope with 16 bit option lengths option_len_ext = option_len - 13; option_len = 13; } // Calculate the option header MODIFY_BITS(7, 4, option_header, option_delta); MODIFY_BITS(3, 0, option_header, option_len); // Write the option header p = buf; WRITE_BYTE(p, option_header); // Write the option_delta_ext if necessary if (option_delta == 13) { WRITE_BYTE(p, option_delta_ext); } // Write the option_len_ext if necessary if (option_len == 13) { WRITE_BYTE(p, option_len_ext); } // Write the option data memcpy(p, option_data, len); p += len; // Update the last pdu option, so that the next call to this function can update the delta from the last option written *last_pdu_option = pdu_option; return p; } /*********************************************************************//** ** ** COAP_ParsePdu ** ** Parses the specified PDU into a structure ** ** \param buf - pointer to buffer containing CoAP PDU to parse ** \param len - length of buffer containing CoAP PDU to parse ** \param pp - pointer to structure in which to store the parsed CoAP PDU ** ** \return action flags determining what actions to take ** **************************************************************************/ unsigned COAP_ParsePdu(unsigned char *buf, int len, parsed_pdu_t *pp) { option_walker_t walker; unsigned header; unsigned action_flags = COAP_NO_ERROR; // Exit if size of packet is not large enough for a CoAP packet if (len < COAP_HEADER_SIZE) { COAP_SetErrMessage("%s: Received CoAP PDU (MID=?) was too small (len=%d). Ignoring.", __FUNCTION__, len); return IGNORE_PDU; } // Parse the header header = READ_4_BYTES(buf, len); pp->coap_version = BITS(31, 30, header); pp->pdu_type = BITS(29, 28, header); pp->token_size = BITS(27, 24, header); pp->pdu_class = BITS(23, 21, header); pp->request_response_code = BITS(20, 16, header); pp->message_id = BITS(15, 0, header); // Exit if PDU has incorrect CoAP version if (pp->coap_version != COAP_VERSION) { COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has incorrect CoAP version (version=%d)", __FUNCTION__, pp->message_id, pp->coap_version); return SEND_RST; } // Exit if PDU is using a class reserved for future expansion if ((pp->pdu_class == 1) || (pp->pdu_class == 6) || (pp->pdu_class == 7)) { COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) is using a reserved class (class=%d)", __FUNCTION__, pp->message_id, pp->pdu_class); return SEND_RST; } // Exit if token size is too large or message not large enough to contain the specified token if ((pp->token_size > sizeof(pp->token)) || (len < pp->token_size)) { COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has incorrect token size (token_size=%d, size_left=%d)", __FUNCTION__, pp->message_id, pp->token_size, len); return SEND_RST; } // Copy the token READ_N_BYTES(pp->token, buf, pp->token_size, len); // Parse all options memset(&walker, 0, sizeof(walker)); walker.buf = buf; walker.len = len; walker.cur_option = kPduOption_Zero; while ((walker.len > 0) && (walker.buf[0] != PDU_OPTION_END_MARKER)) { // Exit if unable to parse the TLV metadata of the option action_flags = WalkCoapOption(&walker, pp); if (action_flags != COAP_NO_ERROR) { return action_flags; } // Exit if an error occurred in parsing the option itself action_flags = ParseCoapOption(walker.cur_option, walker.option_value, walker.option_len, pp); if (action_flags != COAP_NO_ERROR) { return action_flags; } } // Skip the PDU_OPTION_END_MARKER // NOTE: This may not be present after the options if there is no payload if ((walker.len > 0) && (walker.buf[0] == PDU_OPTION_END_MARKER)) { buf = walker.buf + 1; len = walker.len - 1; } // Store pointer to the payload and it's size. This is whatever is left in the PDU. pp->payload = buf; pp->payload_len = len; return COAP_NO_ERROR; } /*********************************************************************//** ** ** COAP_LockMutex ** ** Take the mutex protecting the CoAP sub-system ** ** \param None ** ** \return None ** **************************************************************************/ void COAP_LockMutex(void) { OS_UTILS_LockMutex(&coap_access_mutex); } /*********************************************************************//** ** ** COAP_UnlockMutex ** ** Release the mutex protecting the CoAP sub-system ** ** \param None ** ** \return None ** **************************************************************************/ void COAP_UnlockMutex(void) { OS_UTILS_UnlockMutex(&coap_access_mutex); } /*********************************************************************//** ** ** COAP_SetErrMessage ** ** Stores the textual cause of the error, so that it may be copied later into the payload of the ACK or RST message ** ** \param fmt - printf style format ** ** \return None ** **************************************************************************/ void COAP_SetErrMessage(char *fmt, ...) { va_list ap; // Write the error message into the buffer, ensuring it is always zero terminated va_start(ap, fmt); vsnprintf(coap_err_message, sizeof(coap_err_message), fmt, ap); coap_err_message[sizeof(coap_err_message)-1] = '\0'; va_end(ap); USP_PROTOCOL("%s", coap_err_message); } /*********************************************************************//** ** ** COAP_GetErrMessage ** ** Returns a pointer to the stored CoAP error message ** ** \param None ** ** \return pointer to stored error message ** **************************************************************************/ char *COAP_GetErrMessage(void) { return coap_err_message; } /*********************************************************************//** ** ** WalkCoapOption ** ** Called to walk through each CoAP option ** ** \param ow - pointer to parameters which are used to walk the option list ** On input: The parameters in this structure point to the option to parse ** On output: The parameters in this structure point to the next option to parse, and return the current option and it's values ** \param pp - pointer to parsed CoAP PDU ** ** \return action flags determining what actions to take ** **************************************************************************/ int WalkCoapOption(option_walker_t *ow, parsed_pdu_t *pp) { unsigned char *buf; int len; unsigned option_header; int option_delta; int option_delta_ext; int option_len; int option_len_ext; int buffer_required; // Exit if buffer length left is not enough to include the option header buf = ow->buf; len = ow->len; if (len < 1) { COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has not enough packet left for option header", __FUNCTION__, pp->message_id); return SEND_RST; } // Read and parse the option header option_header = READ_BYTE(buf, len); option_delta = BITS(7, 4, option_header); option_len = BITS(3, 0, option_header); // Exit if Option Delta or option len are encoded incorrectly // NOTE: It is an error to call this code for the PDU_OPTION_END_MARKER USP_ASSERT(option_header != PDU_OPTION_END_MARKER) if ((option_delta == 15) || (option_len==15)) { COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has invalid option_delta or option_len (=15)", __FUNCTION__, pp->message_id); return SEND_RST; } // Calculate the amount of buffer left needed to parse option_delta_ext and option_len_ext buffer_required = 0; if (option_delta > 12) { buffer_required += option_delta - 12; } if (option_len > 12) { buffer_required += option_len - 12; } // Exit if there is not enough buffer left to parse option_delta_ext and option_len_ext if (len < buffer_required) { COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has not enough packet left for option_delta_ext and option_len_ext", __FUNCTION__, pp->message_id); return SEND_RST; } // Parse option_delta_ext, and update option_delta with it if (option_delta == 13) { option_delta_ext = READ_BYTE(buf, len); option_delta = option_delta_ext + 13; } else if (option_delta == 14) { option_delta_ext = READ_2_BYTES(buf, len); option_delta = option_delta_ext + 269; } // Parse option_len_ext, and update option_len with it if (option_len == 13) { option_len_ext = READ_BYTE(buf, len); option_len = option_len_ext + 13; } else if (option_len == 14) { option_len_ext = READ_2_BYTES(buf, len); option_len = option_len_ext + 269; } // Exit if there is not enough buffer left for the option's value if (len < option_len) { COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has not enough packet left to contain the option's value (option=%d)", __FUNCTION__, pp->message_id, ow->cur_option + option_delta); return SEND_RST; } // Update the option walker to point to the next option, and return this option ow->buf = buf + option_len; ow->len = len - option_len; ow->cur_option = ow->cur_option + option_delta; ow->option_value = buf; ow->option_len = option_len; return COAP_NO_ERROR; } /*********************************************************************//** ** ** ParseCoapOption ** ** Parses the specified coap option ** ** \param cs - coap server that sent the PDU containing the specified option ** \param option - coap option ** \param buf - pointer to buffer containing the value of the coap option ** \param len - length of the buffer containing the value of the coap option ** \param pp - pointer to structure in which to store the parsed CoAP PDU ** ** \return action flags determining what actions to take ** **************************************************************************/ int ParseCoapOption(int option, unsigned char *buf, int len, parsed_pdu_t *pp) { bool is_wrong_length = false; // assume that option is correct length bool result; // Determine if the option's value is the wrong length switch(option) { case kPduOption_UriHost: case kPduOption_UriPath: case kPduOption_UriQuery: if (len == 0) { is_wrong_length = true; } break; case kPduOption_ContentFormat: if (len > 2) { is_wrong_length = true; } break; case kPduOption_UriPort: if (len != 2) { is_wrong_length = true; } break; case kPduOption_Size1: if (len > 4) // Size1 option is 0 to 4 bytes { is_wrong_length = true; } break; case kPduOption_Block1: if (len > 3) // Block1 option is 0 to 3 bytes { is_wrong_length = true; } break; default: break; } // Exit if the option is the wrong length if (is_wrong_length) { COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) has incorrect length for an option (option=%d, len=%d)", __FUNCTION__, pp->message_id, option, len); return SEND_RST; } // Copy the option's parsed value into the parsed_pdu structure switch(option) { case kPduOption_UriHost: case kPduOption_UriPort: // NOTE: Ignore these options, as we do not host multiple virtual servers break; case kPduOption_UriPath: pp->options_present |= URI_PATH_PRESENT; AppendUriPath(pp->uri_path, sizeof(pp->uri_path), (char *)buf, len); break; case kPduOption_UriQuery: pp->options_present |= URI_QUERY_PRESENT; TEXT_UTILS_StrncpyLen(pp->uri_query, sizeof(pp->uri_query), (char *)buf, len); USP_PROTOCOL("%s: Received CoAP UriQueryOption='%s'", __FUNCTION__, pp->uri_query); result = ParseCoapUriQuery(pp->uri_query, &pp->mtp_reply_to); if (result == false) { COAP_SetErrMessage("%s: Received CoAP URI query option (%s) is incorrectly formed", __FUNCTION__, pp->uri_query); return SEND_ACK | INDICATE_BAD_OPTION; } break; case kPduOption_ContentFormat: pp->options_present |= CONTENT_FORMAT_PRESENT; pp->content_format = ReadUnsignedOptionValue(buf, len); break; case kPduOption_Block1: ParseBlock1Option(buf, len, pp); break; case kPduOption_Block2: // Ignore the Block2 option. It is used in requests to suggest a block size for the response. But USP uses POST, without piggybacked responses. break; case kPduOption_Size1: pp->options_present |= SIZE1_PRESENT; pp->total_size = ReadUnsignedOptionValue(buf, len); break; default: if ((option & 1) == 1) { // Odd numbered options are 'critical' and must cause the return of a 4.02 (Bad Option) if not handled COAP_SetErrMessage("%s: Received CoAP PDU (MID=%d) contains an unhandled critical option (option=%d)", __FUNCTION__, pp->message_id, option); if (pp->pdu_type == kPduType_Confirmable) { return SEND_ACK | INDICATE_BAD_OPTION; } else { return SEND_RST; } } else { // Even numbered options are 'elective' and can be ignored if we don't parse them } break; } return COAP_NO_ERROR; } /*********************************************************************//** ** ** AppendUriPath ** ** Appends the specified path segment to the URI path buffer ** ** \param path - pointer to buffer containing the current URI path that we wish to append to ** \param path_len - maximum length of the buffer containing the URI path ** \param segment - pointer to buffer (not NULL terminated) containing the path segment to append ** \param seg_len - length of the path segment to append ** ** \return None ** **************************************************************************/ void AppendUriPath(char *path, int path_len, char *segment, int seg_len) { char buf[MAX_COAP_URI_PATH]; int len; // Exit if this is the first segment, copying it into the buffer without a leading '/' separator if (path[0] == '\0') { TEXT_UTILS_StrncpyLen(path, path_len, segment, seg_len); return; } // Form the path segment as a NULL terminated string, with leading '/' separator in local buffer buf[0] = '/'; TEXT_UTILS_StrncpyLen(&buf[1], sizeof(buf)-1, segment, seg_len); // Minus 1 because of '/' separator at the beginning // Append path segment in local buffer to URI path len = strlen(path); USP_STRNCPY(&path[len], buf, path_len-len); } /*********************************************************************//** ** ** ParseBlock1Option ** ** Parses the Block1 option's value ** ** \param buf - pointer to buffer containing the value of the Block1 option ** \param len - length of the buffer containing the value of the Block1 option ** \param pp - pointer to structure in which to store the parsed CoAP PDU ** ** \return None ** **************************************************************************/ void ParseBlock1Option(unsigned char *buf, int len, parsed_pdu_t *pp) { unsigned value; pdu_block_size_t pdu_block_size; pp->options_present |= BLOCK1_PRESENT; switch(len) { default: case 0: pp->rxed_block = 0; pp->is_more_blocks = 0; pdu_block_size = kPduBlockSize_16; break; case 1: value = READ_BYTE(buf, len); pp->rxed_block = BITS(7, 4, value); pp->is_more_blocks = BITS(3, 3, value); pdu_block_size = BITS(2, 0, value); break; case 2: value = READ_2_BYTES(buf, len); pp->rxed_block = BITS(15, 4, value); pp->is_more_blocks = BITS(3, 3, value); pdu_block_size = BITS(2, 0, value); break; case 3: value = READ_3_BYTES(buf, len); pp->rxed_block = BITS(23, 4, value); pp->is_more_blocks = BITS(3, 3, value); pdu_block_size = BITS(2, 0, value); break; } // Convert the enumerated block size back into an integer pp->block_size = CalcBlockSize_Pdu2Int(pdu_block_size); } /*********************************************************************//** ** ** ParseCoapUriQuery ** ** Parses the URI Query option into an mtp_reply_to structure ** The format of the URI Query option is: ** reply_to=coap[s]:// hostname [':' port] '/' resource ** ** NOTE: On exit, the strings in the mtp_reply_to structure will point to within the uri_query (input) buffer ** ** \param uri_query - pointer to buffer containing the URI query option to parse ** NOTE: This buffer will be altered by this function ** \param mrt - pointer to structure containing the parsed 'reply-to' ** ** \return true if parsed successfully ** **************************************************************************/ bool ParseCoapUriQuery(char *uri_query, mtp_reply_to_t *mrt) { char *p; char *p_slash; char *p_colon; char *hostname_end; char *endptr; // Determine if the reply is to an encrypted port or not (and set the default port based on encryption status) #define URI_QUERY_COAP "reply-to=coap://" #define URI_QUERY_COAPS "reply-to=coaps://" p = uri_query; if (strncmp(p, URI_QUERY_COAP, sizeof(URI_QUERY_COAP)-1) == 0) { mrt->coap_encryption = false; mrt->coap_port = 5683; p += sizeof(URI_QUERY_COAP)-1; } else if (strncmp(p, URI_QUERY_COAPS, sizeof(URI_QUERY_COAPS)-1) == 0) { mrt->coap_encryption = true; mrt->coap_port = 5684; p += sizeof(URI_QUERY_COAPS)-1; } else { return false; } // Exit if the rest of the string does not contain a slash character separating the hostname (and possibly port) from the resource p_slash = strchr(p, '/'); if (p_slash == NULL) { return false; } hostname_end = p_slash; // Determine whether an optional port number is present, before the slash p_colon = strchr(p, ':'); if ((p_colon != NULL) && (p_colon < p_slash)) { // Exit if not all of the characters from the colon to the slash are part of the port value mrt->coap_port = strtol(&p_colon[1], &endptr, 10); if (endptr != p_slash) { return false; } hostname_end = p_colon; } *hostname_end = '\0'; // Terminate the hostname in the input buffer mrt->coap_host = p; mrt->coap_resource = &p_slash[1]; mrt->protocol = kMtpProtocol_CoAP; mrt->is_reply_to_specified = true; return true; } /*********************************************************************//** ** ** ReadUnsignedOptionValue ** ** Reads the value of an option contained in a variable number of bytes in network byte order ** ** \param buf - pointer to buffer containing the value of the option ** \param len - length of the buffer containing the value of the option ** ** \return value of the option ** **************************************************************************/ unsigned ReadUnsignedOptionValue(unsigned char *buf, int len) { unsigned value = 0; switch(len) { case 0: value = 0; break; case 1: value = READ_BYTE(buf, len); break; case 2: value = READ_2_BYTES(buf, len); break; case 3: value = READ_3_BYTES(buf, len); break; case 4: value = READ_4_BYTES(buf, len); break; default: TERMINATE_BAD_CASE(len); break; } return value; } /*********************************************************************//** ** ** CalcBlockSize_Int2Pdu ** ** Converts the block size integer into an enumeration suitable to be used in Block option ** ** \param block_size - size of block in bytes ** ** \return Enumerated value representing block size ** **************************************************************************/ pdu_block_size_t CalcBlockSize_Int2Pdu(int block_size) { pdu_block_size_t pdu_block_size = kPduBlockSize_16; switch(block_size) { case 1024: pdu_block_size = kPduBlockSize_1024; break; case 512: pdu_block_size = kPduBlockSize_512; break; case 256: pdu_block_size = kPduBlockSize_256; break; case 128: pdu_block_size = kPduBlockSize_128; break; case 64: pdu_block_size = kPduBlockSize_64; break; case 32: pdu_block_size = kPduBlockSize_32; break; case 16: pdu_block_size = kPduBlockSize_16; break; default: TERMINATE_BAD_CASE(block_size); break; } return pdu_block_size; } /*********************************************************************//** ** ** CalcBlockSize_Pdu2Int ** ** Converts the pdu block size enumeration into an integer ** ** \param pdu_block_size - size of block in enumeration ** ** \return Number of bytes in block ** **************************************************************************/ int CalcBlockSize_Pdu2Int(pdu_block_size_t pdu_block_size) { int block_size; block_size = 1 << (4 + pdu_block_size); return block_size; } #endif // ENABLE_COAP
the_stack_data/5711.c
#include <unistd.h> #include <sys/time.h> unsigned int alarm(unsigned int secs) { struct itimerval old, new; unsigned int retval; new.it_value.tv_usec = 0; new.it_interval.tv_sec = 0; new.it_interval.tv_usec = 0; new.it_value.tv_sec = (long int)secs; if (setitimer(ITIMER_REAL, &new, &old) < 0) return 0; retval = old.it_value.tv_sec; if (old.it_value.tv_usec) ++retval; return retval; }
the_stack_data/193894392.c
// This is derived from the loop in musl's __fwritex that looks for newlines. int puts(const char *s); int main(int argc, const char **argv) { const char *p = (const char *)argv; char *s = "Hello\nWorld"; unsigned i = 0; // Depend on argc to avoid having this whole thing get dead-code-eliminated. for (i = 14 - argc; i && p[i - 1] != '\n'; i--) ; puts(s); return i; }
the_stack_data/4499.c
// Replace this file with the Solution for Project Euler Problem #046 // Project Euler Problem: #046 // Repository Maintainer: https://www.github.com/theSwapnilSaste // File Creation Date : 14th March 2020 // Solution Author : **** Insert Your Name/Github Handle Here *** // Solution added on : **** Insert Date here **** // Problem Status : Complete/Incomplete/Need Improvement etc. // Space for Notes // . // .
the_stack_data/72012645.c
#include <stdio.h> int main () { int a; scanf("%d", &a); if(a%400==0) printf("1"); else if(a%4==0 && a%100!=0) printf("1"); else printf("0"); }
the_stack_data/1262251.c
#define DIGIT_DEC (256) #define DIGIT_HEX (8) // ใ‚ทใƒชใ‚ขใƒซๅ‡บๅŠ›ใฎใ‚ฆใ‚งใ‚คใƒˆ #define UART_WAIT 10 // ใ‚ทใƒชใ‚ขใƒซๅ‡บๅŠ›ใฎ memory-mapped address #define SERIAL_ADDRESS 0x40002000 #include <sys/types.h> void* __attribute((weak)) memcpy(void* dest_, const void* src_, size_t n) { char* dest = dest_; const char* src = src_; for (size_t i = 0; i < n; i++) dest[i] = src[i]; return dest; } void serial_wait() { #ifdef FPGA volatile int sum = 0; int i; for(i=0; i<UART_WAIT; i++) sum += i; #endif } void serial_out_dec(int val) { volatile int *e_txd = (int*)SERIAL_ADDRESS; // memory mapped I/O int i; int c[DIGIT_DEC]; int cnt = 0; int minus_flag = 0; if (val < 0) { /* ----- setting + or - ----- */ minus_flag = 1; /* ----- calclate absolute value ----- */ val *= -1; } do { c[cnt] = (val % 10) + '0'; cnt++; val = val / 10; } while (val != 0); if (minus_flag) { c[cnt] = '-'; cnt++; } for (i = cnt - 1; i >= 0; i--) { serial_wait(); *e_txd = c[i]; } } void serial_out_hex(int val) { volatile int *e_txd = (int*)SERIAL_ADDRESS; // memory mapped I/O int i; int c[DIGIT_HEX]; int cnt = 0; while (cnt < DIGIT_HEX) { c[cnt] = ((val & 0x0000000f) == 0) ? '0' : ((val & 0x0000000f) == 1) ? '1' : ((val & 0x0000000f) == 2) ? '2' : ((val & 0x0000000f) == 3) ? '3' : ((val & 0x0000000f) == 4) ? '4' : ((val & 0x0000000f) == 5) ? '5' : ((val & 0x0000000f) == 6) ? '6' : ((val & 0x0000000f) == 7) ? '7' : ((val & 0x0000000f) == 8) ? '8' : ((val & 0x0000000f) == 9) ? '9' : ((val & 0x0000000f) == 10) ? 'a' : ((val & 0x0000000f) == 11) ? 'b' : ((val & 0x0000000f) == 12) ? 'c' : ((val & 0x0000000f) == 13) ? 'd' : ((val & 0x0000000f) == 14) ? 'e' : 'f'; cnt++; val = val >> 4; } for (i = cnt - 1; i >= 0; i--) { serial_wait(); *e_txd = c[i]; } } void serial_out_char(char val) { volatile char *e_txd = (char*)SERIAL_ADDRESS; // memory mapped I/O serial_wait(); *e_txd = val; }
the_stack_data/1245517.c
struct { int a } * b; c; d() { int e, f, g; switch (b->a) { case 6: f = g = 2; break; case 135: case 134: g = 5; break; case 132: f = 0; } if (b->a || b) e = c; h(f); i(g); j(e); }
the_stack_data/51699220.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned short input[1] , unsigned short output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } int main(int argc , char *argv[] ) { unsigned short input[1] ; unsigned short output[1] ; int randomFuns_i5 ; unsigned short randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned short )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == (unsigned short)31026) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void RandomFunc(unsigned short input[1] , unsigned short output[1] ) { unsigned short state[1] ; unsigned short local1 ; char copy11 ; { state[0UL] = (input[0UL] - 51238316UL) - (unsigned short)47038; local1 = 0UL; while (local1 < 1UL) { if (state[0UL] > local1) { state[0UL] = (state[local1] >> ((state[local1] & (unsigned short)15) | 1UL)) | (state[local1] << (16 - ((state[local1] & (unsigned short)15) | 1UL))); state[0UL] = (state[local1] << (((state[local1] >> (unsigned short)2) & (unsigned short)15) | 1UL)) | (state[local1] >> (16 - (((state[local1] >> (unsigned short)2) & (unsigned short)15) | 1UL))); } else { copy11 = *((char *)(& state[local1]) + 0); *((char *)(& state[local1]) + 0) = *((char *)(& state[local1]) + 1); *((char *)(& state[local1]) + 1) = copy11; state[local1] |= (((state[local1] << (((state[0UL] >> (unsigned short)2) & (unsigned short)15) | 1UL)) | (state[local1] >> (16 - (((state[0UL] >> (unsigned short)2) & (unsigned short)15) | 1UL)))) & (unsigned short)63) << 4UL; } if (state[0UL] == local1) { state[local1] |= ((state[local1] + state[local1]) & (unsigned short)15) << 2UL; } else { state[local1] |= (state[local1] * state[local1] & (unsigned short)63) << 4UL; } local1 ++; } output[0UL] = state[0UL] * 1062470260UL; } }
the_stack_data/68887112.c
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <termios.h> #include <unistd.h> struct termios orig_termios; void disableRawMode() { tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios); } void enableRawMode() { tcgetattr(STDIN_FILENO, &orig_termios); atexit(disableRawMode); struct termios raw = orig_termios; raw.c_iflag &= ~(IXON); raw.c_lflag &= ~(ECHO | ICANON | ISIG); tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); } int main() { enableRawMode(); char c; while (read(STDIN_FILENO, &c, 1) == 1 && c != 'q') { if (iscntrl(c)) { printf("%d\n", c); } else { printf("%d ('%c')\n", c, c); } } return 0; }
the_stack_data/53588.c
#include <stdio.h> void extra() { printf("PASS\n"); }
the_stack_data/161080042.c
int main () { int a = 6; int b = 7; int c = 20; if( a&b ||c) { return a||c&b; } }
the_stack_data/220455221.c
#include <stdbool.h> #include <stdint.h> #include <stdlib.h> // Table of CRCs of all 8-bit messages. static uint32_t crc_table[256]; // Has the table been computed? static bool crc_table_computed = false; // Make the table for a fast CRC static void make_crc_table() { for (uint32_t n = 0; n < 256; n++) { uint32_t c = n; for (int k = 0; k < 8; k++) { if (c & 1) { c = 0xedb88320L ^ (c >> 1); } else { c = c >> 1; } } crc_table[n] = c; } crc_table_computed = true; } /* Update a running CRC with the bytes buf[0..len-1]--the CRC should be * initialized to all 1s, and the transmitted value is the 1s complement of the * final running CRC (see the crc() routine below)). */ uint32_t update_crc(uint32_t crc, const unsigned char *buf, size_t len) { if (!crc_table_computed) { make_crc_table(); } uint32_t c = crc; for (size_t n = 0; n < len; n++) { c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8); } return c; } // Return the CRC of the bytes buf[0..len-1] uint32_t crc(unsigned char *buf, size_t len) { return update_crc(0xffffffffL, buf, len) ^ 0xffffffffL; }
the_stack_data/95400.c
/* ** Copyright (c) 2018 Arm Limited (or its affiliates). All rights reserved. ** Use, modification and redistribution of this file is subject to your possession of a ** valid End User License Agreement for the Arm Product of which these examples are part of ** and your compliance with all applicable terms and conditions of such licence agreement. */ /* Simple polled UART driver for Cortex-M MPS2 FVP model */ // Ensure uart_init() is called before any other functions in this file. typedef struct { volatile unsigned int DATA; volatile unsigned int STATE; volatile unsigned int CTRL; volatile unsigned int INTERRUPT; volatile unsigned int BAUDDIV; } UART_struct; // UART at 0x50200000 in SSE-200 (see MPS2+ documentation) #define UART ((UART_struct *) 0x49303000UL ) void uart_init(void) { UART->BAUDDIV = 16; UART->CTRL = 0x41; // High speed test mode, TX only } void uart_putc_polled(char c) { while ((UART->STATE & 1)); // Wait if Transmit Holding register is full UART->DATA = c; } char uart_getchar_polled(void) { while ((UART->STATE & 2)==0); // Wait if Receive Holding register is empty return (UART->DATA); }
the_stack_data/68888104.c
/* * Copyright (c) 2021-2021 Huawei Device Co., Ltd. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 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. */ extern int undef_func(int a, int b); int caller(int a, int b) { return a + undef_func(a, b); }
the_stack_data/94788.c
/* * factorial.c * * recursively compute a factorial * * compiled by mcc */ int factorial (int x) { if (x > 1) return (x * factorial(x - 1)); else return 1; }
the_stack_data/87637827.c
#include<stdio.h> void displaythematrix(float * , char , char ); float * cofactormatrix(float *, float *, char, char , char ); float determinantof(float *, unsigned char, unsigned char); float * actualcofactormatrix(float *, float * , char); // worked previously so yeah, it works. float determinantof(float *inmat, unsigned char size, unsigned char depth) { float * nothing; // Since we are using functions that return memory address if(size==0) return 1; if(size==1) return * inmat; float submat[size-1][size-1]; float det=0; for(int i = 0; i<size; i++) { _Bool sign = (i%2==0); // True if even nothing = cofactormatrix(&submat[0][0],inmat,size,1,i+1); // Count starting from 0 for matrix position float cofactor = (sign?1:-1)*determinantof(&submat[0][0],size-1,depth+1); det += (*(inmat+i))*cofactor; } return det; } //works float * cofactormatrix(float *outmat, float *inmat, char size, char row, char column) { float *output=outmat; row--; column--; // During implementation, however, we use programmer's convention for(int i=0; i<size; i++) // i is the row of matrix { if(i==row) // We move to another row {inmat+=size;continue;} // plus we skip assigning for this iteration for(int j = 0; j<size; j++) // j is the column of matrix { if(j==column) // We move to another column {inmat++;continue;} // plus we skip assigning for this iteration *(outmat++) = *(inmat++); // First assign then increment } } return output; } // Works perfectly now float * actualcofactormatrix(float * outmat, float * inmat, char size) { float * output = outmat; float * nothing; // since we are using function that return memory address float submatrix[size-1][size-1]; for(int i = 0; i<size; i++) for(int j = 0; j<size; j++) { _Bool sign = ((i+j)%2==0); nothing = cofactormatrix(&submatrix[0][0],inmat,size ,i+1,j+1); // mathematically consistent counting there //printf("\n%c",sign?'+':'-'); //displaythematrix(&submatrix[0][0],size-1,size-1); *(outmat++) = determinantof(&submatrix[0][0],size-1,1) * (sign?1:-1); } return output; } // works void displaythematrix(float * inmat, char rows, char cols) { for(char i=0; i<rows; i++) { printf("\n"); for(char j = 0; j<cols; j++) printf("%.2f\t",*(inmat++)); } } int main() { float matrix1[3][3]= { {1,2,3}, {3,4,5}, {5,6,7} }; float matrix2[2][3]= { {1,2,3}, {4,5,6} }; float matrixofcofactor[3][3]; float matrixsub[2][2]; actualcofactormatrix(&matrixofcofactor[0][0],&matrix1[0][0],3); displaythematrix(&matrixofcofactor[0][0],3,3); }
the_stack_data/43887129.c
/* * Copyright 2021 Kontain Inc * * 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. */ #define _GNU_SOURCE #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/utsname.h> #include <sys/wait.h> #define errExit(msg) \ do { \ perror(msg); \ exit(EXIT_FAILURE); \ } while (0) static int childFunc(void* arg) { fprintf(stderr, "Hello from clone\n"); return 0; /* Child terminates now */ } #define STACK_SIZE (1024 * 1024) /* Stack size for cloned child */ int main(int argc, char* argv[]) { unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED; char* stack; /* Start of stack buffer */ pid_t pid, tid; stack = malloc(STACK_SIZE); if (stack == NULL) { errExit("malloc"); } printf("clone()\n"); pid = clone(childFunc, stack + STACK_SIZE, flags, NULL, &pid, NULL, &tid); if (pid == -1) { errExit("clone"); } printf("clone() returned %ld\n", (long)pid); usleep(100000); exit(EXIT_SUCCESS); }
the_stack_data/373829.c
#ifdef _WIN32 #include <Winsock2.h> #include <Ws2tcpip.h> #include <Windows.h> #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #endif #include <string.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc != 3) { printf("Command line args should be multicast group and port\n"); printf("(e.g. for SSDP, `sender 239.255.255.250 1900`)\n"); return 1; } char* group = argv[1]; int port = atoi(argv[2]); const int delay_secs = 1; const char *message = "Hello, World!"; #ifdef _WIN32 WSADATA wsaData; if (WSAStartup(0x0101, &wsaData)) { perror("WSAStartup"); return 1; } #endif int fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("socket"); return 1; } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(group); addr.sin_port = htons(port); while (1) { char ch = 0; int nbytes = sendto( fd, message, strlen(message), 0, (struct sockaddr*) &addr, sizeof(addr) ); if (nbytes < 0) { perror("sendto"); return 1; } printf("sent\n"); #ifdef _WIN32 Sleep(delay_secs * 1000); #else sleep(delay_secs); #endif } #ifdef _WIN32 WSACleanup(); #endif return 0; }
the_stack_data/52600.c
/* * Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #if defined(LIBC_SCCS) && !defined(lint) static const char orig_rcsid[] = "From Id: inet_net_ntop.c,v 8.2 1996/08/08 06:54:44 vixie Exp"; static const char rcsid[] = "$Id: inet_net_ntop.c $"; #endif #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #ifdef SPRINTF_CHAR # define SPRINTF(x) strlen(sprintf/**/x) #else # define SPRINTF(x) ((size_t)sprintf x) #endif static char * inet_net_ntop_ipv4 (const u_char *src, int bits, char *dst, size_t size); /* * char * * inet_net_ntop(af, src, bits, dst, size) * convert network number from network to presentation format. * generates CIDR style result always. * return: * pointer to dst, or NULL if an error occurred (check errno). * author: * Paul Vixie (ISC), July 1996 */ char * inet_net_ntop( int af, const void *src, int bits, char *dst, size_t size ) { switch (af) { case AF_INET: return (inet_net_ntop_ipv4(src, bits, dst, size)); default: errno = EAFNOSUPPORT; return (NULL); } } /* * static char * * inet_net_ntop_ipv4(src, bits, dst, size) * convert IPv4 network number from network to presentation format. * generates CIDR style result always. * return: * pointer to dst, or NULL if an error occurred (check errno). * note: * network byte order assumed. this means 192.5.5.240/28 has * 0x11110000 in its fourth octet. * author: * Paul Vixie (ISC), July 1996 */ static char * inet_net_ntop_ipv4( const u_char *src, int bits, char *dst, size_t size ) { char *odst = dst; char *t; u_int m; int b; if (bits < 0 || bits > 32) { errno = EINVAL; return (NULL); } if (bits == 0) { if (size < sizeof "0") goto emsgsize; *dst++ = '0'; *dst = '\0'; } /* Format whole octets. */ for (b = bits / 8; b > 0; b--) { if (size < sizeof "255.") goto emsgsize; t = dst; dst += SPRINTF((dst, "%u", *src++)); if (b > 1) { *dst++ = '.'; *dst = '\0'; } size -= (size_t)(dst - t); } /* Format partial octet. */ b = bits % 8; if (b > 0) { if (size < sizeof ".255") goto emsgsize; t = dst; if (dst != odst) *dst++ = '.'; m = ((1 << b) - 1) << (8 - b); dst += SPRINTF((dst, "%u", *src & m)); size -= (size_t)(dst - t); } /* Format CIDR /width. */ if (size < sizeof "/32") goto emsgsize; dst += SPRINTF((dst, "/%u", bits)); return (odst); emsgsize: errno = EMSGSIZE; return (NULL); }
the_stack_data/75146.c
#include <stdio.h> #include <stdlib.h> int main() { double val = strtod("-20.23 hello world", NULL); printf("val: %lf\n", val); val = strtod("+20.23 hello world", NULL); printf("val: %lf\n", val); return 0; }
the_stack_data/179831003.c
/* Copyright 1990 by Abacus Research and * Development, Inc. All rights reserved. */ #if !defined (OMIT_RCSID_STRINGS) char ROMlib_rcsid_mkseedtables[] = "$Id: mkseedtables.c 86 2005-05-25 00:47:12Z ctm $"; #endif #include <stdio.h> #include <stdlib.h> #define EIGHTHPOWEROF(x) ((x)*(x)*(x)*(x)*(x)*(x)*(x)*(x)) typedef int LONGINT; static void buildbinarytotrinary() { LONGINT i, retval; printf("PRIVATE INTEGER binarytotrinary[] = {\n"); for (i = 0; i < EIGHTHPOWEROF(2); i++) { retval = 0; if (i & (1 << 0)) retval += 1; if (i & (1 << 1)) retval += 3; if (i & (1 << 2)) retval += 3*3; if (i & (1 << 3)) retval += 3*3*3; if (i & (1 << 4)) retval += 3*3*3*3; if (i & (1 << 5)) retval += 3*3*3*3*3; if (i & (1 << 6)) retval += 3*3*3*3*3*3; if (i & (1 << 7)) retval += 3*3*3*3*3*3*3; if (!(i & 7)) printf(" "); printf("0x%04X,", retval); putchar((i & 7) == 7 ? '\n' : ' '); } printf("};\n"); } static void buildexpandtable() { register LONGINT i, n, bit; register LONGINT x, y; unsigned char toexpand, seed, retval; printf("PRIVATE unsigned char expandtable[] = {\n"); for (i = 0; i < EIGHTHPOWEROF(3); i++) { toexpand = seed = retval = 0; for (n = 1, bit = 1; n < 6561; n *= 3, bit <<= 1) { switch ((i / n) % 3) { case 0: toexpand |= bit; break; case 2: seed |= bit; break; } } x = ~toexpand & seed; for (bit = 1; bit < 256; bit <<= 1) { if (x & bit) { retval |= bit; for (y = bit << 1; y < 256 && !(y&toexpand); y <<= 1) retval |= y; for (y = bit >> 1; y && !(y&toexpand); y >>= 1) retval |= y; } } if (!(i & 7)) printf(" "); printf("0x%02X,", retval); putchar((i & 7) == 7 || i == EIGHTHPOWEROF(3)-1 ? '\n' : ' '); } printf("};\n"); } int main() { buildbinarytotrinary(); buildexpandtable(); exit(0); }
the_stack_data/218894352.c
/* Question : 1.Find the sum of the digits of given number. Eg: Input: 14->1+4->5. 165->1+6+5->1+2->3 author : s.shivasurya date : 8/3/2016 algo: 1) get a number split the number by mod 10 remainder 2) sum it up 3) check that sum is > 9 =>recursion call above function with sum as data 4) else return sum directly cscvenkat suggested : O(n^2) as time complexity */ #include<stdio.h> int sum(int data){ int sums = 0; while(data){ sums = sums + (data%10); data = data / 10; } while(sums > 9){ return sum(sums); } return sums; } int main(){ int temp=0; temp = sum(999); printf("\nans=>%d\n",temp); temp = sum(1128); printf("\nans=>%d\n",temp); }
the_stack_data/156393582.c
/* This file tests shifts in various integral modes. */ #include <limits.h> #define CAT(A, B) A ## B #define REPEAT_8 \ REPEAT_FN ( 0) \ REPEAT_FN ( 1) \ REPEAT_FN ( 2) \ REPEAT_FN ( 3) \ REPEAT_FN ( 4) \ REPEAT_FN ( 5) \ REPEAT_FN ( 6) \ REPEAT_FN ( 7) #define REPEAT_16 \ REPEAT_8 \ REPEAT_FN ( 8) \ REPEAT_FN ( 9) \ REPEAT_FN (10) \ REPEAT_FN (11) \ REPEAT_FN (12) \ REPEAT_FN (13) \ REPEAT_FN (14) \ REPEAT_FN (15) #define REPEAT_32 \ REPEAT_16 \ REPEAT_FN (16) \ REPEAT_FN (17) \ REPEAT_FN (18) \ REPEAT_FN (19) \ REPEAT_FN (20) \ REPEAT_FN (21) \ REPEAT_FN (22) \ REPEAT_FN (23) \ REPEAT_FN (24) \ REPEAT_FN (25) \ REPEAT_FN (26) \ REPEAT_FN (27) \ REPEAT_FN (28) \ REPEAT_FN (29) \ REPEAT_FN (30) \ REPEAT_FN (31) /* Define 8-bit shifts. */ #if CHAR_BIT == 8 typedef unsigned int u8 __attribute__((mode(QI))); typedef signed int s8 __attribute__((mode(QI))); #define REPEAT_FN(COUNT) \ u8 CAT (ashift_qi_, COUNT) (u8 n) { return n << COUNT; } REPEAT_8 #undef REPEAT_FN #define REPEAT_FN(COUNT) \ u8 CAT (lshiftrt_qi_, COUNT) (u8 n) { return n >> COUNT; } REPEAT_8 #undef REPEAT_FN #define REPEAT_FN(COUNT) \ s8 CAT (ashiftrt_qi_, COUNT) (s8 n) { return n >> COUNT; } REPEAT_8 #undef REPEAT_FN #endif /* CHAR_BIT == 8 */ /* Define 16-bit shifts. */ #if CHAR_BIT == 8 || CHAR_BIT == 16 #if CHAR_BIT == 8 typedef unsigned int u16 __attribute__((mode(HI))); typedef signed int s16 __attribute__((mode(HI))); #elif CHAR_BIT == 16 typedef unsigned int u16 __attribute__((mode(QI))); typedef signed int s16 __attribute__((mode(QI))); #endif #define REPEAT_FN(COUNT) \ u16 CAT (ashift_hi_, COUNT) (u16 n) { return n << COUNT; } REPEAT_16 #undef REPEAT_FN #define REPEAT_FN(COUNT) \ u16 CAT (lshiftrt_hi_, COUNT) (u16 n) { return n >> COUNT; } REPEAT_16 #undef REPEAT_FN #define REPEAT_FN(COUNT) \ s16 CAT (ashiftrt_hi_, COUNT) (s16 n) { return n >> COUNT; } REPEAT_16 #undef REPEAT_FN #endif /* CHAR_BIT == 8 || CHAR_BIT == 16 */ /* Define 32-bit shifts. */ #if CHAR_BIT == 8 || CHAR_BIT == 16 || CHAR_BIT == 32 #if CHAR_BIT == 8 typedef unsigned int u32 __attribute__((mode(SI))); typedef signed int s32 __attribute__((mode(SI))); #elif CHAR_BIT == 16 typedef unsigned int u32 __attribute__((mode(HI))); typedef signed int s32 __attribute__((mode(HI))); #elif CHAR_BIT == 32 typedef unsigned int u32 __attribute__((mode(QI))); typedef signed int s32 __attribute__((mode(QI))); #endif #define REPEAT_FN(COUNT) \ u32 CAT (ashift_si_, COUNT) (u32 n) { return n << COUNT; } REPEAT_32 #undef REPEAT_FN #define REPEAT_FN(COUNT) \ u32 CAT (lshiftrt_si_, COUNT) (u32 n) { return n >> COUNT; } REPEAT_32 #undef REPEAT_FN #define REPEAT_FN(COUNT) \ s32 CAT (ashiftrt_si_, COUNT) (s32 n) { return n >> COUNT; } REPEAT_32 #undef REPEAT_FN #endif /* CHAR_BIT == 8 || CHAR_BIT == 16 || CHAR_BIT == 32 */ extern void abort (void); extern void exit (int); int main () { /* Test 8-bit shifts. */ #if CHAR_BIT == 8 # define REPEAT_FN(COUNT) \ if (CAT (ashift_qi_, COUNT) (0xff) != (u8) ((u8)0xff << COUNT)) abort (); REPEAT_8; # undef REPEAT_FN # define REPEAT_FN(COUNT) \ if (CAT (lshiftrt_qi_, COUNT) (0xff) != (u8) ((u8)0xff >> COUNT)) abort (); REPEAT_8; # undef REPEAT_FN # define REPEAT_FN(COUNT) \ if (CAT (ashiftrt_qi_, COUNT) (-1) != -1) abort (); REPEAT_8; # undef REPEAT_FN # define REPEAT_FN(COUNT) \ if (CAT (ashiftrt_qi_, COUNT) (0) != 0) abort (); REPEAT_8; # undef REPEAT_FN #endif /* CHAR_BIT == 8 */ /* Test 16-bit shifts. */ #if CHAR_BIT == 8 || CHAR_BIT == 16 # define REPEAT_FN(COUNT) \ if (CAT (ashift_hi_, COUNT) (0xffff) \ != (u16) ((u16) 0xffff << COUNT)) abort (); REPEAT_16; # undef REPEAT_FN # define REPEAT_FN(COUNT) \ if (CAT (lshiftrt_hi_, COUNT) (0xffff) \ != (u16) ((u16) 0xffff >> COUNT)) abort (); REPEAT_16; # undef REPEAT_FN # define REPEAT_FN(COUNT) \ if (CAT (ashiftrt_hi_, COUNT) (-1) != -1) abort (); REPEAT_16; # undef REPEAT_FN # define REPEAT_FN(COUNT) \ if (CAT (ashiftrt_hi_, COUNT) (0) != 0) abort (); REPEAT_16; # undef REPEAT_FN #endif /* CHAR_BIT == 8 || CHAR_BIT == 16 */ /* Test 32-bit shifts. */ #if CHAR_BIT == 8 || CHAR_BIT == 16 || CHAR_BIT == 32 # define REPEAT_FN(COUNT) \ if (CAT (ashift_si_, COUNT) (0xffffffff) \ != (u32) ((u32) 0xffffffff << COUNT)) abort (); REPEAT_32; # undef REPEAT_FN # define REPEAT_FN(COUNT) \ if (CAT (lshiftrt_si_, COUNT) (0xffffffff) \ != (u32) ((u32) 0xffffffff >> COUNT)) abort (); REPEAT_32; # undef REPEAT_FN # define REPEAT_FN(COUNT) \ if (CAT (ashiftrt_si_, COUNT) (-1) != -1) abort (); REPEAT_32; # undef REPEAT_FN # define REPEAT_FN(COUNT) \ if (CAT (ashiftrt_si_, COUNT) (0) != 0) abort (); REPEAT_32; # undef REPEAT_FN #endif /* CHAR_BIT == 8 || CHAR_BIT == 16 || CHAR_BIT == 32 */ exit (0); }
the_stack_data/150141968.c
#include <stdio.h> int main () { int var = 20; /* ๅฎž้™…ๅ˜้‡็š„ๅฃฐๆ˜Ž */ int *ip; /* ๆŒ‡้’ˆๅ˜้‡็š„ๅฃฐๆ˜Ž */ ip = &var; /* ๅœจๆŒ‡้’ˆๅ˜้‡ไธญๅญ˜ๅ‚จ var ็š„ๅœฐๅ€ */ printf("Address of var variable: %x\n", &var ); /* ๅœจๆŒ‡้’ˆๅ˜้‡ไธญๅญ˜ๅ‚จ็š„ๅœฐๅ€ */ printf("Address stored in ip variable: %x\n", ip ); /* ไฝฟ็”จๆŒ‡้’ˆ่ฎฟ้—ฎๅ€ผ */ printf("Value of *ip variable: %d\n", *ip ); return 0; }
the_stack_data/144175.c
#include <stdio.h> #include <stddef.h> #include <stdint.h> #define offset_of(t, m) ((size_t) & (((t*)0)->m)) struct test { int a; char b; uint32_t c; }; struct test2 { int a; char b; uint32_t c; } __attribute__((packed)); int main(void) { printf("offset_of a: %zu / b: %zu / c: %zu\n", offset_of(struct test, a), offset_of(struct test, b), offset_of(struct test, c)); printf("Packed: offset_of a: %zu / b: %zu / c: %zu\n", offset_of(struct test2, a), offset_of(struct test2, b), offset_of(struct test2, c)); }
the_stack_data/897021.c
// // Created by adamzeng on 2019-06-21. // #include <stdio.h> #include <fcntl.h> int main() { FILE *fp; int fd = open("data.dat", O_WRONLY | O_CREAT | O_TRUNC); if (fd == -1) { fputs("file open error()",stdout); return -1; } printf("First file descriptor: %d \n", fd); fp = fdopen(fd, "w"); fputs("TCP/IP SOCKET PROGRAMMING \n", fp); printf("Second file descriptor: %d \n", fileno(fp)); fclose(fp); return 0; }
the_stack_data/67324691.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_isspace.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: yviavant <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/04 18:50:37 by yviavant #+# #+# */ /* Updated: 2020/02/14 14:33:58 by yviavant ### ########.fr */ /* */ /* ************************************************************************** */ int ft_isspace(char c) { if (c == '\f' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == ' ') return (1); return (0); }
the_stack_data/61076682.c
#include <stdio.h> void swap(int * a, int * b); void quick(int * A, int l, int r); int main () { int i, n; scanf("%d", &n); int A[n]; for (i=0; i<n; i++) { scanf("%d", &A[i]); } quick(A, 0, n-1); printf("\n\n"); for (i=0; i<n; i++) { printf("%d ", A[i]); } printf("\n"); return 0; } void swap(int * a, int * b) { int swap = *a; *a = *b; *b = swap; } void quick(int * A, int l, int r) { int i, b; if (r-l < 1) { return; } b = l + 1; for (i=l+1; i<=r; i++) { if (A[i] <= A[l]) { swap(&A[b], &A[i]); b++; } } swap(&A[l], &A[b-1]); quick(A, l, b-1); quick(A, b, r); }
the_stack_data/26701163.c
# include <stdio.h> # include <stdlib.h> int main() { char nilai; scanf("%c", &nilai); switch (nilai) { case 'A': printf("You did great!\n"); break; case 'B': printf("You did alright\n"); break; case 'C': printf("You did poorly\n"); break; case 'D': printf("You did very bad\n"); break; case 'F': printf("You failed\n"); break; default : /*ini sama kaya else*/ printf("Invalid Grade\n"); } return 0; } /* ini membuat switch statements sama kaya if statements ini lebih mudah bagi kita kalo mau menghitung 1 value */
the_stack_data/444928.c
/* $NetBSD: strlen.c,v 1.9 2003/08/07 16:32:11 agc Exp $ */ /*- * 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. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> #if defined(LIBC_SCCS) && !defined(lint) #if 0 static char sccsid[] = "@(#)strlen.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: strlen.c,v 1.9 2003/08/07 16:32:11 agc Exp $"); #endif #endif /* LIBC_SCCS and not lint */ #if !defined(_KERNEL) && !defined(_STANDALONE) #include <string.h> #else #include <lib/libkern/libkern.h> #endif size_t strlen(str) const char *str; { const char *s; for (s = str; *s; ++s); return(s - str); }
the_stack_data/67325519.c
/* Copyright (C) 1991, 1997 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #undef atol /* Convert a string to a long int. */ long int atol (const char *nptr) { return strtol (nptr, (char **) NULL, 10); }
the_stack_data/117328410.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_foreach.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpearson <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/07/10 20:34:39 by dpearson #+# #+# */ /* Updated: 2017/07/10 20:34:40 by dpearson ### ########.fr */ /* */ /* ************************************************************************** */ /* ** The function can take in a pointer to an array of ints. ** It also takes in an int, which could be the length of this array. ** It also takes in a pointer to the function it wants to apply to this ** array. ** _______________________________________________________________________ ** An example could be taking in ft_putnbr, and displaying all of the ints ** in the array. */ void ft_foreach(int *tab, int length, void (*f)(int)) { int i; i = 0; while (i < length) f(tab[i++]); }
the_stack_data/165768127.c
#include <string.h> #include <stdio.h> int main(int argc, char **argv) { char buf[80]; char *tstr; tstr = (argc < 2 ? "test string" : argv[1]); printf ("tstr @ %p = \"%s\"\n", tstr, tstr); printf ("strlen(tstr) = %d\n", strlen(tstr)); strcpy(buf, tstr); printf ("strcpy(buf, tstr) = \"%s\"\n", buf); strcat(buf, tstr); printf ("strcat(buf, tstr) = \"%s\"\n", buf); printf ("strcmp(tstr, \"abcde\") = %d\n", strcmp(tstr, "abcde")); printf ("strncmp(tstr, \"abcde\", 3) = %d\n", strncmp(tstr, "abcde", 3)); printf ("strchr(tstr, 's') = %p\n", strchr(tstr, 's')); printf ("strrchr(tstr, 's') = %p\n", strrchr(tstr, 's')); printf ("strstr(tstr, \"str\") = %p\n", strstr(tstr, "str")); return 0; }
the_stack_data/89199824.c
#include <stdio.h> /* Defines printf */ /*The Main function of a simple program*/ int main(void) { int num = 1; /*Defines a variable called num and initialize with the number 1*/ printf("I am a simple "); /*Use the printf function*/ printf("computer program.\n"); printf("My favorite numer is %d because it is true.\n", num); return 0; }
the_stack_data/248580722.c
/* XPM */ static const char *const xpm_icon_0[] = { /* columns rows colors chars-per-pixel */ "16 16 156 2", " c black", ". c #010101", "X c #020201", "o c #020202", "O c gray1", "+ c #040404", "@ c #060606", "# c #070707", "$ c gray3", "% c #090909", "& c #1A1919", "* c #1D1D1C", "= c #212020", "- c #232322", "; c #272625", ": c #272726", "> c #30302F", ", c #424140", "< c #444442", "1 c #484846", "2 c #494846", "3 c #4A4A48", "4 c #535250", "5 c #545452", "6 c #555452", "7 c #565553", "8 c #585755", "9 c #585855", "0 c #5C5B59", "q c #5E5D5B", "w c #61605E", "e c #62615E", "r c #62615F", "t c #646361", "y c #666563", "u c #666663", "i c #686765", "p c #6A6A67", "a c #6B6A67", "s c #6B6A68", "d c #6E6D6B", "f c #706F6D", "g c #71706D", "h c #72716E", "j c #767472", "k c #777673", "l c #787774", "z c #797875", "x c #83827E", "c c #858480", "v c #8A8986", "b c #8B8986", "n c #8B8A86", "m c #8B8A87", "M c #8C8C88", "N c #8E8D8A", "B c #8F8E8A", "V c #8F8F8B", "C c #908E8B", "Z c #908F8B", "A c #908F8C", "S c #92908D", "D c #92918D", "F c #93928E", "G c #949390", "H c #959491", "J c #969491", "K c #969591", "L c #979692", "P c #989793", "I c #999794", "U c #9A9895", "Y c #9A9995", "T c #9B9A96", "R c #9C9B97", "E c #9D9C98", "W c #9E9C99", "Q c #9E9D99", "! c #9F9D9A", "~ c #9F9E9A", "^ c #A09E9A", "/ c #A09E9B", "( c #A09F9B", ") c #A19F9B", "_ c #A1A09C", "` c #A2A09C", "' c #A2A19D", "] c #A3A19D", "[ c #A5A39F", "{ c #A5A4A0", "} c #A6A5A1", "| c #A7A5A1", " . c #A7A6A2", ".. c #A8A6A2", "X. c #A8A7A3", "o. c #A9A7A3", "O. c #A9A8A4", "+. c #AAA9A5", "@. c #ABA9A5", "#. c #ABAAA6", "$. c #ACAAA6", "%. c #ACABA7", "&. c #ADABA7", "*. c #ADACA8", "=. c #AEACA8", "-. c #AEADA8", ";. c #AEADA9", ":. c #AFADA9", ">. c #AFAEAA", ",. c #B0AEAA", "<. c #B0AFAA", "1. c #B0AFAB", "2. c #B1AFAB", "3. c #B3B1AD", "4. c #B3B2AD", "5. c #B4B2AE", "6. c #B4B3AF", "7. c #B5B3AF", "8. c #B5B4AF", "9. c #B5B4B0", "0. c #B6B4B0", "q. c #B6B5B1", "w. c #B8B6B2", "e. c #B9B7B2", "r. c #B9B7B3", "t. c #BAB9B4", "y. c #BCBAB6", "u. c #BDBCB7", "i. c #BEBCB8", "p. c #C0BEBA", "a. c #C1C0BB", "s. c #C3C1BC", "d. c #C4C2BD", "f. c #C5C4BF", "g. c #C6C4BF", "h. c #C7C5C0", "j. c #C8C6C1", "k. c #C9C7C2", "l. c #CAC8C3", "z. c #CBC9C4", "x. c #CCCAC6", "c. c #CECCC7", "v. c #CFCDC8", "b. c #D0CEC9", "n. c #D0CFCA", "m. c #D1CFCA", "M. c #D1CFCB", "N. c #D3D1CC", "B. c #D4D2CD", "V. c #D5D3CE", "C. c #D6D4CF", "Z. c #D7D5D0", "A. c #DAD8D3", "S. c #E3E0DB", "D. c #E5E3DE", "F. c #E8E6E1", /* pixels */ "@.0.T B 3.[ M S V B ;[email protected] E 0.@.", "0./ c K E h # % _ S S S _ >.", "K / ;.w x.< + h C.t s.G R ", "b ;.5.4 A., + # d F.9 6._ F ", "*.S } y.} 0 % b E [ E S *.", "5.t.a t T 8.s 5 4 l i.X.( E u.@.", "3.P *.P T o.[ T @.R l.C._ z.v.X.", "b *.b 1 C.6 N.x K t.E S.h j A.} ", "S _ E w h.0 k.b b 3.} C., } C.} ", "0._ 0.a.T 0.S } _ B h.v.f.c.l.X.", "R 1 = * > _ @.s i ;.l.z.N.N.a.o.", "V + O t ..x 3.S i.N.b *.N.} ", "A $ + 3 Z.z h i.E D.w z A.} ", "V + 8 r.$.T E 3.N.9 0.N.} ", "K : - : & m T G I K h.z.C.c.s.@.", "@.;.;.;.;.@.;.K P ;.O.X.} X.O.@." }; /* XPM */ static const char *const xpm_icon_1[] = { /* columns rows colors chars-per-pixel */ "32 32 77 1", " c #010101", ". c #0C0B0B", "X c #141413", "o c #1B1B1A", "O c #20201F", "+ c #252524", "@ c #282827", "# c #2C2C2B", "$ c #302F2E", "% c #353433", "& c #383837", "* c #3D3C3B", "= c #41413F", "- c #454443", "; c #4A4947", ": c #4D4C4A", "> c #504F4D", ", c #51514F", "< c #555452", "1 c #585755", "2 c #595856", "3 c #5D5C5A", "4 c #605F5D", "5 c #61615E", "6 c #656462", "7 c #686765", "8 c #6A6866", "9 c #6D6C69", "0 c #706F6C", "q c #72716E", "w c #757471", "e c #787774", "r c #7A7976", "t c #7E7D7A", "y c #807F7C", "u c #82817E", "i c #858481", "p c #888683", "a c #8A8986", "s c #8E8C89", "d c #908E8B", "f c #92918D", "g c #969592", "h c #989793", "j c #9B9A96", "k c #9E9D99", "l c #A19F9B", "z c #A3A19E", "x c #A6A5A2", "c c #A8A7A3", "v c #AAA9A5", "b c #AEADA9", "n c #B0AFAB", "m c #B3B2AD", "M c #B6B5B0", "N c #B9B7B2", "B c #BBBAB5", "V c #BEBDB8", "C c #C0BFBA", "Z c #C4C2BE", "A c #C7C5C0", "S c #C9C7C2", "D c #CCCAC6", "F c #CFCDC8", "G c #D1CFCA", "H c #D4D2CD", "J c #D7D5D0", "K c #D9D7D1", "L c #DBD9D4", "P c #DFDDD8", "I c #E1DED9", "U c #E4E2DC", "Y c #E8E6E1", "T c #ECE9E4", "R c #F1EFE9", "E c #F4F2EC", "W c #FEFBF5", /* pixels */ "vvxxxmMmxxcbmmmmmmmmvxxcmMmxxcvv", "vvmVbuqaBNmsuuiuuuuuxmVbtwsNNbcv", "xmUj<tp7<VK+ gTg<rp71ZFxc", "xVk<VbVYn:B# zl<FAVPv>Mvc", "cb<Hkr#<Ez5& f3GJ3 NTk3Mx", "miwIJb@9PH3+ 5uPKN.NKH<zv", "MwyILC%2IK8X .<sPLC.SLL3hv", "ms7Tgd%<UG2+ 8wUFr tJG>cv", "xN2MGujHTiq* k4MIssfYu9Mx", "xNZ:cUTGu4G# lZ:xYTIu5Dxv", "xbDb5121qZZ,$=-%&-&%jHv<>1;7AVcv", "xbDFi-&>jHNZIn713eSKMZDHNmZHDNcv", "xMH1rAIV4eDGf,nJDs:MAJHLUYUHKAxv", "xV8fRD=zE8in<UM-uEm,NHLm3:gKHZcv", "bg6PK6 rUS24vIS%;UUruPJmmi.HKZxv", "MwrRit%wUL3*GGT>;ULl7UFLE1oHKZxv", "MrwR8,X&GL2=SGI--ILj9UHH: lKHZcv", "vx2KHD-tTM3wgRj%%jR5dLLco-0DKAxv", "xCu8IUUTF<kA:NYIUYs6AHHJIKGHKZcv", "xmTu4jvs1cHDM:tvx63GVGHHHGHHHZxv", "bzus6&#-essMSA2+@tHVnBBBNNBBVMcv", "mu %KS3wjh4rLVHHJUIHHKZxv", "mi &H1jFvlF0wSGHGxzHHKZxv", "mu -itW4&sZY2jLPz6-=KJZxv", "mu =6NY8%wAUf9UGFEg GKZcv", "mu &3SJGLo8Rk8UFIm.6PKZxv", "mu =6MPatodRyrIKm osGKZxv", "mi -k3TMabYF:nJKVhkfGKZcv", "mi %Pe7FYIn<lAJJLUUUJKSxv", "bf&***=**&5AFt:1<>lFmAZZCZZZANcv", "vbMMMMMmMMbcxmvjkmbxvxxxxcxxxcvv", "vvxxxxcxcccvccvbvccvvvvvvvvvvvcv" }; /* XPM */ static const char *const xpm_icon_2[] = { /* columns rows colors chars-per-pixel */ "48 48 85 1", " c #010101", ". c #080707", "X c #0C0C0C", "o c #131313", "O c #181817", "+ c #1C1C1C", "@ c #20201F", "# c #242423", "$ c #282726", "% c #282827", "& c #2C2B2A", "* c #302F2E", "= c #31302F", "- c #343432", "; c #383736", ": c #393837", "> c #3C3C3A", ", c #403F3D", "< c #41403F", "1 c #444442", "2 c #484745", "3 c #494947", "4 c #4D4C4A", "5 c #504F4D", "6 c #51504F", "7 c #555452", "8 c #585756", "9 c #595856", "0 c #5D5C5A", "q c #605F5D", "w c #61615E", "e c #656462", "r c #686765", "t c #696866", "y c #6C6C69", "u c #706F6D", "i c #72716E", "p c #767572", "a c #787774", "s c #7A7976", "d c #7D7C79", "f c #807F7C", "g c #82817E", "h c #858481", "j c #888784", "k c #8A8985", "l c #8E8D8A", "z c #908F8C", "x c #92918E", "c c #959491", "v c #989793", "b c #9B9A96", "n c #9E9D99", "m c #A09F9B", "M c #A3A29E", "N c #A6A6A2", "B c #A8A7A3", "V c #AAA9A5", "C c #AEADA9", "Z c #B0AFAB", "A c #B3B2AE", "S c #B6B5B0", "D c #B8B7B3", "F c #BAB9B4", "G c #BFBDB9", "H c #C0BFBA", "J c #C4C2BD", "K c #C6C5C0", "L c #C9C7C2", "P c #CCCAC6", "I c #CFCDC8", "U c #D1CFCA", "Y c #D4D2CD", "T c #D7D5D0", "R c #D8D6D1", "E c #DCDAD5", "W c #DFDDD8", "Q c #E1DFD9", "! c #E4E2DD", "~ c #E7E5E0", "^ c #E9E6E1", "/ c #EDEBE5", "( c #F1EFE9", ") c #F5F3ED", "_ c #FEFCF6", /* pixels */ "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV", "VVBVVVVVVBBBVVVVVBBBVNNVVNBNBBVVVVVVNNBVVVVVBVVV", "VVVVNBNNVASZBBBBBZZAAZAAAZAAAAVNVNMVSSANNNNVVVVV", "VVVVAZSJNdpkAHZAZlhhhhhhhhhhhjCACFJMsakSHZACVVVV", "VVBAYQJ7=<1,*fQRJ% oSYQH6-11>-gWESNVVV", "VVBZQZ#yU//RC>2RL% . oA!B#iL^/EV:5WFNVVV", "VVBDL$b!MkmIQ!79U$ oFH#M/LbvJW!4eKMVVV", "VVMJ9u)z>5X#JRE;x- XJ7s^Rp# xWYY-xZBVV", "VBVN-KRPR_e ZRQg4: On-PTIQz v!I!s3SBVV", "VBAd1EYED& rQIEZ:& #p4QYI!k x!IEV=CVNV", "VBAa2!IEUZ>XHRRH-& #y4!II!k x!UEA&CVVV", "VNAk<YYJJ/0 CEEM>- +g2EYI!l b!IWn;ANVV", "VVBA:Z^x==otRU!t0> oZ-GTEuO OsE!q0SNVV", "VVMHg1!RJALEUQF&A& oJs3^TGDJSG!A=CVNVV", "VVNAW36E^QEE^D$zY% . .. . OAE<0E^QE!/C#bJMVVV", "VVBAEE8=fZGMw$z!J% oAWT5:jSGMw%v^DBVVV", "VVVCFFJk4;->qBJDSp90wyuttit00rCDGJf>&%=6VJDZBVVV", "VCMCJJYZr;*2gJPLALTWYj6><eV!EPAKJJYYPLUTPJLABVVV", "VVVAEWt$ymVx5%M!SJ!V&2kNnp&8EPAETTYYYTYYTTEDBVVV", "VVMAQ9<Y!!^!!B@MJPC#v^/!!!T53YSYYYY!EEQTYYRDBVVV", "VVMJz:QYRV@5R!V*ZL-b/J8#3YY!3iJYITU9:&tUYYRDBVVV", "VVMD:VQUY- *EP^qtk4!YJlO+EUEG%ATYEG9Sa s!ITFBVVV", "VBAl>YU!09@#EUWn<3lWYT^++EYYE<hQUYYW^G 9!IEFBVVV", "VVAp2QEM:!O%/URG-&CWYUY++RYY!8u!YYYTY- fQIRDMVVV", "VBAd2E!i+9X.gERA:-MWYR/#@/YY!6p!YYRU> rWYYTFNVVV", "VVVM-LEGllXoCY!j4wp!YLgXogLRY-vWURI% @gMTYTDNVVV", "VVMJ6f!Y!!yd!UQ,hV-RRJ8ww8G^x:GYYRJwrr4kWYTFNVVV", "VVMFG#A!YPQWY/e4HYq6!W!!!!!G$MGYYYR!!!^QUYTDVVVV", "VVBZ!n@gYWWEH4:YGJW31FTWEYz#xEARTTYYUYUYTTRFNVVV", "VVBSY!F2:0w6-yRQDGUYr#4eq:=mWJAPPPPPPPPPPPISNVVV", "VBVnddgje>;3pkfavAAAYA8$-sPJZACASSSSSSSSSSSCVVVV", "VBAh . qRREd-398:1A!PAEYRYYYYYTTTRFNVVV", "VBAh . wYE4:A!)(Rg@bRAYYYYE!!RUYYYFBVVV", "VBAh 0!w4!Yxgpb(A$VGYYYRAhkHEYYRDNVVV", "BBAh . tZ=YQA 69dY!z>JYYRH$8#.NEURFNVVV", "VBAh uri!RF xP!RYY=bEYTPF/G 0!URDNVVV", "VBAh t<MEEA-> 0EUQ6p!UYYRQg e!IRDNVVV", "VBAh t>VEYRR/4 GR!8u!YYU!k oZEYRDBVVV", "VBAh y5zQYDHY-.JYE2gQUYRd OCQIYRDNVVV", "VBAh . ug5!Ek-%+lRRH%ZRYRJo.#&iQYRDBVVV", "VNAh . eY=n^YLGURY^4tJYYYYLPJFLYYRDBVVV", "VNAh . . 0WN#M!!QE!E02YSYYYYTTTETYYRDBVVV", "VVAh 0T!N&6vSCf-6RUAETTTTTTTTRREDBVVV", "VVCbryyyytyytyyelFSJAe:%&1gJGACFDFFDDDDDDDDZBVVV", "VVVVSSSSSSSSSSSSCNNNVSACZSANNNVNNNNNBBNNBBBBBVVV", "VBVVBNNNNNNNNNBNNVVVVNNBVNBVVVVVVVVVVVBVBVVVBVVV", "VVVVVVVVVVVVVVVVVVVVVVBVVVVVVVVVVVVVVVVVVVVVVVVV", "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" }; const char *const *const xpm_icons[] = { xpm_icon_0, xpm_icon_1, xpm_icon_2, }; const int n_xpm_icons = 3;
the_stack_data/153269255.c
#define MATRIX_SIZE 700000 void initializeVectors(float a[MATRIX_SIZE], float b[MATRIX_SIZE]) { for (int i = 0; i < MATRIX_SIZE; i++) { a[i] = (float)i; b[i] = 0.0; } } float matrixElement(int row, int column) { if (row == column) { return 1.0; } return 0.0; } void printVector(float vec[MATRIX_SIZE]) { const int standardSize = 10; int size = MATRIX_SIZE < standardSize ? MATRIX_SIZE : standardSize; for (int i = 0; i < size; i++) { printf("%.2f ", vec[i]); } printf("\n"); } void compareVectors(float a[MATRIX_SIZE], float b[MATRIX_SIZE]) { for (int i = 0; i < MATRIX_SIZE; i++) { if (fabs(a[i] - b[i]) > 0.001) { printf("mismatch at index %d: %f != %f\n", i, a[i], b[i]); } } printf("\n"); }
the_stack_data/111078950.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jpucelle <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/07/12 14:47:32 by jpucelle #+# #+# */ /* Updated: 2014/07/13 14:18:16 by jdesmet ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> int jp_parse_sudoku_table(int pos[9][9], char **argv); int jp_print_sudoku(int pos[9][9]); void jp_set_pos(int *pos, int *orig, int i, int check); int jp_check_square(int pos[9][9], int x, int y, int nbr) { int xmin; int xmax; int ymin; int ymax; int i; xmin = (x / 3) * 3; xmax = xmin + 3; ymin = (y / 3) * 3; ymax = ymin + 3; while (xmin < xmax) { i = ymin; while (i < ymax) { if (i != y && xmin != x && pos[i][xmin] == nbr) return (0); i++; } xmin++; } return (1); } int jp_check_pos(int pos[9][9], int x, int y, int nbr) { int i; i = 0; while (i < 9) { if (i != x && pos[y][i] == nbr) return (0); i++; } i = 0; while (i < 9) { if (i != y && pos[i][x] == nbr) return (0); i++; } i = jp_check_square(pos, x, y, nbr); return (i); } void jp_put_last_nr(int pos[9][9], int nr, int *check) { if (jp_check_pos(pos, 8, 8, nr)) { if (pos[8][8] == 0) pos[8][8] = nr; *check = *check + 1; } } void jp_solve(int pos[9][9], int val, int orig[9][9], int *check) { int i; int x; int y; x = val % 9; y = val / 9; if (pos[y][x] != 0 && (x != 8 || y != 8) && *check < 2) jp_solve(pos, val + 1, orig, check); i = 1; while (i < 10 && *check < 2) { if (x != 8 || y != 8) { if (jp_check_pos(pos, x, y, i) && pos[y][x] == 0) { jp_set_pos(&pos[y][x], &orig[y][x], i, *check); jp_solve(pos, val + 1, orig, check); pos[y][x] = 0; } } else jp_put_last_nr(orig, i, check); i++; } } int main(int argc, char **argv) { int pos[9][9]; int orig[9][9]; int check; int *ptr_check; check = 0; ptr_check = &check; if (argc == 10) { jp_parse_sudoku_table(orig, &argv[1]); if (jp_parse_sudoku_table(pos, &argv[1])) { jp_solve(pos, 0, orig, ptr_check); if (check == 1) jp_print_sudoku(orig); else write(1, "Erreur\n", 7); } else write(1, "Erreur\n", 7); } return (0); }
the_stack_data/61075859.c
// Main reference: 1. http://pages.tacc.utexas.edu/~eijkhout/istc/istc.html void store(double *a, double *b, double *c) { *c = *a + *b; }
the_stack_data/173577606.c
extern float __VERIFIER_nondet_float(void); extern int __VERIFIER_nondet_int(void); typedef enum {false, true} bool; bool __VERIFIER_nondet_bool(void) { return __VERIFIER_nondet_int() != 0; } int main() { float x_8, _x_x_8; float x_1, _x_x_1; bool _J540, _x__J540; bool _J532, _x__J532; float x_9, _x_x_9; bool _EL_X_517, _x__EL_X_517; float x_0, _x_x_0; bool _EL_U_516, _x__EL_U_516; float x_11, _x_x_11; float x_6, _x_x_6; float x_5, _x_x_5; float x_10, _x_x_10; float x_3, _x_x_3; float x_2, _x_x_2; float x_7, _x_x_7; bool _EL_U_514, _x__EL_U_514; float x_4, _x_x_4; int __steps_to_fair = __VERIFIER_nondet_int(); x_8 = __VERIFIER_nondet_float(); x_1 = __VERIFIER_nondet_float(); _J540 = __VERIFIER_nondet_bool(); _J532 = __VERIFIER_nondet_bool(); x_9 = __VERIFIER_nondet_float(); _EL_X_517 = __VERIFIER_nondet_bool(); x_0 = __VERIFIER_nondet_float(); _EL_U_516 = __VERIFIER_nondet_bool(); x_11 = __VERIFIER_nondet_float(); x_6 = __VERIFIER_nondet_float(); x_5 = __VERIFIER_nondet_float(); x_10 = __VERIFIER_nondet_float(); x_3 = __VERIFIER_nondet_float(); x_2 = __VERIFIER_nondet_float(); x_7 = __VERIFIER_nondet_float(); _EL_U_514 = __VERIFIER_nondet_bool(); x_4 = __VERIFIER_nondet_float(); bool __ok = (1 && ((_EL_X_517 && ( !_J532)) && ( !_J540))); while (__steps_to_fair >= 0 && __ok) { if ((_J532 && _J540)) { __steps_to_fair = __VERIFIER_nondet_int(); } else { __steps_to_fair--; } _x_x_8 = __VERIFIER_nondet_float(); _x_x_1 = __VERIFIER_nondet_float(); _x__J540 = __VERIFIER_nondet_bool(); _x__J532 = __VERIFIER_nondet_bool(); _x_x_9 = __VERIFIER_nondet_float(); _x__EL_X_517 = __VERIFIER_nondet_bool(); _x_x_0 = __VERIFIER_nondet_float(); _x__EL_U_516 = __VERIFIER_nondet_bool(); _x_x_11 = __VERIFIER_nondet_float(); _x_x_6 = __VERIFIER_nondet_float(); _x_x_5 = __VERIFIER_nondet_float(); _x_x_10 = __VERIFIER_nondet_float(); _x_x_3 = __VERIFIER_nondet_float(); _x_x_2 = __VERIFIER_nondet_float(); _x_x_7 = __VERIFIER_nondet_float(); _x__EL_U_514 = __VERIFIER_nondet_bool(); _x_x_4 = __VERIFIER_nondet_float(); __ok = ((((((((((((((((x_10 + (-1.0 * _x_x_0)) <= -7.0) && (((x_9 + (-1.0 * _x_x_0)) <= -12.0) && (((x_5 + (-1.0 * _x_x_0)) <= -19.0) && (((x_4 + (-1.0 * _x_x_0)) <= -20.0) && (((x_0 + (-1.0 * _x_x_0)) <= -8.0) && ((x_3 + (-1.0 * _x_x_0)) <= -8.0)))))) && (((x_10 + (-1.0 * _x_x_0)) == -7.0) || (((x_9 + (-1.0 * _x_x_0)) == -12.0) || (((x_5 + (-1.0 * _x_x_0)) == -19.0) || (((x_4 + (-1.0 * _x_x_0)) == -20.0) || (((x_0 + (-1.0 * _x_x_0)) == -8.0) || ((x_3 + (-1.0 * _x_x_0)) == -8.0))))))) && ((((x_10 + (-1.0 * _x_x_1)) <= -14.0) && (((x_8 + (-1.0 * _x_x_1)) <= -2.0) && (((x_6 + (-1.0 * _x_x_1)) <= -8.0) && (((x_3 + (-1.0 * _x_x_1)) <= -3.0) && (((x_0 + (-1.0 * _x_x_1)) <= -9.0) && ((x_2 + (-1.0 * _x_x_1)) <= -1.0)))))) && (((x_10 + (-1.0 * _x_x_1)) == -14.0) || (((x_8 + (-1.0 * _x_x_1)) == -2.0) || (((x_6 + (-1.0 * _x_x_1)) == -8.0) || (((x_3 + (-1.0 * _x_x_1)) == -3.0) || (((x_0 + (-1.0 * _x_x_1)) == -9.0) || ((x_2 + (-1.0 * _x_x_1)) == -1.0)))))))) && ((((x_11 + (-1.0 * _x_x_2)) <= -12.0) && (((x_10 + (-1.0 * _x_x_2)) <= -17.0) && (((x_7 + (-1.0 * _x_x_2)) <= -13.0) && (((x_6 + (-1.0 * _x_x_2)) <= -7.0) && (((x_0 + (-1.0 * _x_x_2)) <= -7.0) && ((x_5 + (-1.0 * _x_x_2)) <= -3.0)))))) && (((x_11 + (-1.0 * _x_x_2)) == -12.0) || (((x_10 + (-1.0 * _x_x_2)) == -17.0) || (((x_7 + (-1.0 * _x_x_2)) == -13.0) || (((x_6 + (-1.0 * _x_x_2)) == -7.0) || (((x_0 + (-1.0 * _x_x_2)) == -7.0) || ((x_5 + (-1.0 * _x_x_2)) == -3.0)))))))) && ((((x_11 + (-1.0 * _x_x_3)) <= -8.0) && (((x_10 + (-1.0 * _x_x_3)) <= -19.0) && (((x_8 + (-1.0 * _x_x_3)) <= -9.0) && (((x_7 + (-1.0 * _x_x_3)) <= -19.0) && (((x_0 + (-1.0 * _x_x_3)) <= -8.0) && ((x_5 + (-1.0 * _x_x_3)) <= -14.0)))))) && (((x_11 + (-1.0 * _x_x_3)) == -8.0) || (((x_10 + (-1.0 * _x_x_3)) == -19.0) || (((x_8 + (-1.0 * _x_x_3)) == -9.0) || (((x_7 + (-1.0 * _x_x_3)) == -19.0) || (((x_0 + (-1.0 * _x_x_3)) == -8.0) || ((x_5 + (-1.0 * _x_x_3)) == -14.0)))))))) && ((((x_9 + (-1.0 * _x_x_4)) <= -16.0) && (((x_7 + (-1.0 * _x_x_4)) <= -20.0) && (((x_4 + (-1.0 * _x_x_4)) <= -1.0) && (((x_3 + (-1.0 * _x_x_4)) <= -13.0) && (((x_1 + (-1.0 * _x_x_4)) <= -14.0) && ((x_2 + (-1.0 * _x_x_4)) <= -2.0)))))) && (((x_9 + (-1.0 * _x_x_4)) == -16.0) || (((x_7 + (-1.0 * _x_x_4)) == -20.0) || (((x_4 + (-1.0 * _x_x_4)) == -1.0) || (((x_3 + (-1.0 * _x_x_4)) == -13.0) || (((x_1 + (-1.0 * _x_x_4)) == -14.0) || ((x_2 + (-1.0 * _x_x_4)) == -2.0)))))))) && ((((x_8 + (-1.0 * _x_x_5)) <= -6.0) && (((x_7 + (-1.0 * _x_x_5)) <= -1.0) && (((x_6 + (-1.0 * _x_x_5)) <= -16.0) && (((x_5 + (-1.0 * _x_x_5)) <= -2.0) && (((x_2 + (-1.0 * _x_x_5)) <= -18.0) && ((x_3 + (-1.0 * _x_x_5)) <= -9.0)))))) && (((x_8 + (-1.0 * _x_x_5)) == -6.0) || (((x_7 + (-1.0 * _x_x_5)) == -1.0) || (((x_6 + (-1.0 * _x_x_5)) == -16.0) || (((x_5 + (-1.0 * _x_x_5)) == -2.0) || (((x_2 + (-1.0 * _x_x_5)) == -18.0) || ((x_3 + (-1.0 * _x_x_5)) == -9.0)))))))) && ((((x_11 + (-1.0 * _x_x_6)) <= -14.0) && (((x_8 + (-1.0 * _x_x_6)) <= -18.0) && (((x_7 + (-1.0 * _x_x_6)) <= -10.0) && (((x_6 + (-1.0 * _x_x_6)) <= -9.0) && (((x_2 + (-1.0 * _x_x_6)) <= -4.0) && ((x_3 + (-1.0 * _x_x_6)) <= -6.0)))))) && (((x_11 + (-1.0 * _x_x_6)) == -14.0) || (((x_8 + (-1.0 * _x_x_6)) == -18.0) || (((x_7 + (-1.0 * _x_x_6)) == -10.0) || (((x_6 + (-1.0 * _x_x_6)) == -9.0) || (((x_2 + (-1.0 * _x_x_6)) == -4.0) || ((x_3 + (-1.0 * _x_x_6)) == -6.0)))))))) && ((((x_11 + (-1.0 * _x_x_7)) <= -13.0) && (((x_7 + (-1.0 * _x_x_7)) <= -20.0) && (((x_6 + (-1.0 * _x_x_7)) <= -2.0) && (((x_5 + (-1.0 * _x_x_7)) <= -19.0) && (((x_0 + (-1.0 * _x_x_7)) <= -15.0) && ((x_4 + (-1.0 * _x_x_7)) <= -10.0)))))) && (((x_11 + (-1.0 * _x_x_7)) == -13.0) || (((x_7 + (-1.0 * _x_x_7)) == -20.0) || (((x_6 + (-1.0 * _x_x_7)) == -2.0) || (((x_5 + (-1.0 * _x_x_7)) == -19.0) || (((x_0 + (-1.0 * _x_x_7)) == -15.0) || ((x_4 + (-1.0 * _x_x_7)) == -10.0)))))))) && ((((x_9 + (-1.0 * _x_x_8)) <= -12.0) && (((x_7 + (-1.0 * _x_x_8)) <= -13.0) && (((x_4 + (-1.0 * _x_x_8)) <= -12.0) && (((x_3 + (-1.0 * _x_x_8)) <= -10.0) && (((x_0 + (-1.0 * _x_x_8)) <= -7.0) && ((x_1 + (-1.0 * _x_x_8)) <= -19.0)))))) && (((x_9 + (-1.0 * _x_x_8)) == -12.0) || (((x_7 + (-1.0 * _x_x_8)) == -13.0) || (((x_4 + (-1.0 * _x_x_8)) == -12.0) || (((x_3 + (-1.0 * _x_x_8)) == -10.0) || (((x_0 + (-1.0 * _x_x_8)) == -7.0) || ((x_1 + (-1.0 * _x_x_8)) == -19.0)))))))) && ((((x_8 + (-1.0 * _x_x_9)) <= -13.0) && (((x_7 + (-1.0 * _x_x_9)) <= -3.0) && (((x_5 + (-1.0 * _x_x_9)) <= -19.0) && (((x_4 + (-1.0 * _x_x_9)) <= -11.0) && (((x_0 + (-1.0 * _x_x_9)) <= -4.0) && ((x_2 + (-1.0 * _x_x_9)) <= -8.0)))))) && (((x_8 + (-1.0 * _x_x_9)) == -13.0) || (((x_7 + (-1.0 * _x_x_9)) == -3.0) || (((x_5 + (-1.0 * _x_x_9)) == -19.0) || (((x_4 + (-1.0 * _x_x_9)) == -11.0) || (((x_0 + (-1.0 * _x_x_9)) == -4.0) || ((x_2 + (-1.0 * _x_x_9)) == -8.0)))))))) && ((((x_10 + (-1.0 * _x_x_10)) <= -2.0) && (((x_9 + (-1.0 * _x_x_10)) <= -6.0) && (((x_8 + (-1.0 * _x_x_10)) <= -2.0) && (((x_7 + (-1.0 * _x_x_10)) <= -15.0) && (((x_1 + (-1.0 * _x_x_10)) <= -1.0) && ((x_4 + (-1.0 * _x_x_10)) <= -19.0)))))) && (((x_10 + (-1.0 * _x_x_10)) == -2.0) || (((x_9 + (-1.0 * _x_x_10)) == -6.0) || (((x_8 + (-1.0 * _x_x_10)) == -2.0) || (((x_7 + (-1.0 * _x_x_10)) == -15.0) || (((x_1 + (-1.0 * _x_x_10)) == -1.0) || ((x_4 + (-1.0 * _x_x_10)) == -19.0)))))))) && ((((x_11 + (-1.0 * _x_x_11)) <= -13.0) && (((x_9 + (-1.0 * _x_x_11)) <= -8.0) && (((x_8 + (-1.0 * _x_x_11)) <= -15.0) && (((x_7 + (-1.0 * _x_x_11)) <= -8.0) && (((x_2 + (-1.0 * _x_x_11)) <= -19.0) && ((x_6 + (-1.0 * _x_x_11)) <= -14.0)))))) && (((x_11 + (-1.0 * _x_x_11)) == -13.0) || (((x_9 + (-1.0 * _x_x_11)) == -8.0) || (((x_8 + (-1.0 * _x_x_11)) == -15.0) || (((x_7 + (-1.0 * _x_x_11)) == -8.0) || (((x_2 + (-1.0 * _x_x_11)) == -19.0) || ((x_6 + (-1.0 * _x_x_11)) == -14.0)))))))) && ((((_EL_X_517 == (((_x_x_1 + (-1.0 * _x_x_3)) <= 15.0) || (_x__EL_U_516 && ( !(_x__EL_U_514 || ( !((_x_x_1 + (-1.0 * _x_x_3)) <= 15.0))))))) && ((_EL_U_514 == (_x__EL_U_514 || ( !((_x_x_1 + (-1.0 * _x_x_3)) <= 15.0)))) && (_EL_U_516 == (((_x_x_1 + (-1.0 * _x_x_3)) <= 15.0) || (_x__EL_U_516 && ( !(_x__EL_U_514 || ( !((_x_x_1 + (-1.0 * _x_x_3)) <= 15.0))))))))) && (_x__J532 == (( !(_J532 && _J540)) && ((_J532 && _J540) || ((( !((x_1 + (-1.0 * x_3)) <= 15.0)) || ( !(( !((x_1 + (-1.0 * x_3)) <= 15.0)) || _EL_U_514))) || _J532))))) && (_x__J540 == (( !(_J532 && _J540)) && ((_J532 && _J540) || ((((x_1 + (-1.0 * x_3)) <= 15.0) || ( !(((x_1 + (-1.0 * x_3)) <= 15.0) || (_EL_U_516 && ( !(( !((x_1 + (-1.0 * x_3)) <= 15.0)) || _EL_U_514)))))) || _J540)))))); x_8 = _x_x_8; x_1 = _x_x_1; _J540 = _x__J540; _J532 = _x__J532; x_9 = _x_x_9; _EL_X_517 = _x__EL_X_517; x_0 = _x_x_0; _EL_U_516 = _x__EL_U_516; x_11 = _x_x_11; x_6 = _x_x_6; x_5 = _x_x_5; x_10 = _x_x_10; x_3 = _x_x_3; x_2 = _x_x_2; x_7 = _x_x_7; _EL_U_514 = _x__EL_U_514; x_4 = _x_x_4; } }
the_stack_data/86074155.c
/* ************************************************ username : smmehrab fullname : s.m.mehrabul islam email : [email protected] institute : university of dhaka, bangladesh session : 2017-2018 ************************************************ */ #include<stdio.h> int main() { int n,c; scanf("%d",&n); if(n>36) printf("-1"); else { if(n%2==0) { c=0; while(c!=(n/2)) { printf("8"); c++; } } else { c=0; while(c!=(n-1)/2) { printf("8"); c++; } printf("9"); } } printf("\n"); return 0; }
the_stack_data/178266278.c
/* { dg-do compile } */ /* { dg-options "-O2 -w" } */ /* { dg-final { scan-assembler-times "cbd .3,0\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cbd .3,1\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cbd .3,2\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cbd .3,3\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cbd .3,4\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cbd .3,5\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cbd .3,6\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cbd .3,7\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cbd .3,15\\(.sp\\)" 15 } } */ /* { dg-final { scan-assembler-times "chd .3,0\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "chd .3,2\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "chd .3,4\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "chd .3,6\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cwd .3,0\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cwd .3,4\\(.sp\\)" 1 } } */ /* { dg-final { scan-assembler-times "cdd .3,0\\(.sp\\)" 1 } } */ #define MAKE_ULLONG(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,aA,aB,aC,aD,aE,aF) \ ((unsigned long long) \ (a0##ull << 56 \ | a1##ull << 48 \ | a2##ull << 40 \ | a3##ull << 32\ | a4##ull << 24\ | a5##ull << 16 \ | a6##ull << 8 \ | a7##ull )) unsigned long long cbd_0() { return MAKE_ULLONG( 0x03, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_1() { return MAKE_ULLONG( 0x10, 0x03, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_2() { return MAKE_ULLONG( 0x10, 0x11, 0x03, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_3() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x03, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_4() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x03, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_5() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x03, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_6() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x03, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_7() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x03, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_8() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x03, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_9() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_a() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x03, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_b() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x03, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_c() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x03, 0x1D, 0x1E, 0x1F); } unsigned long long cbd_d() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x03, 0x1E, 0x1F); } unsigned long long cbd_e() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x03, 0x1F); } unsigned long long cbd_f() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x03); } unsigned long long chd_0() { return MAKE_ULLONG( 0x02, 0x03, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long chd_2() { return MAKE_ULLONG( 0x10, 0x11, 0x02, 0x03, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long chd_4() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x02, 0x03, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long chd_6() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x02, 0x03, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long chd_8() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x02, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long chd_a() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x02, 0x03, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long chd_c() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x02, 0x03, 0x1E, 0x1F); } unsigned long long chd_e() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x02, 0x03); } unsigned long long cwd_0() { return MAKE_ULLONG( 0x00, 0x01, 0x02, 0x03, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cwd_4() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x00, 0x01, 0x02, 0x03, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cwd_8() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x00, 0x01, 0x02, 0x03, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cwd_c() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x00, 0x01, 0x02, 0x03); } unsigned long long cdd_0() { return MAKE_ULLONG( 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F); } unsigned long long cdd_8() { return MAKE_ULLONG( 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07); }
the_stack_data/109122.c
/* The program Tritype (implemented in function foo) takes as input three integers (the sides of a triangle) and returns 3 if the input correspond to an equilateral triangle, 2 if it correspond to an isosceles triangle, 1 if it correspond to another type of triangle, 4 if it does not correspond to a valid triangle. The error in this program is in the condition "(trityp == 2 && (i+j) > k)", the instruction should be "(trityp == 2 && (i+k) > j)". By taking as counterexample the input {i=1, j=2, k=1}, the program should return 2 (isosceles triangle). This program with the same input return a value that correspond to an invalid triangle. SPDX-FileCopyrightText: Mohammed Bekkouche <http://www.i3s.unice.fr> SPDX-License-Identifier: GPL-3.0-or-later */ extern int __VERIFIER_nondet_uint(); extern void __VERIFIER_error(); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } /* program for triangle classification * returns 1 if (i,j,k) are the sides of any triangle * returns 2 if (i,j,k) are the sides of an isosceles triangle * returns 3 if (i,j,k) are the sides of an equilateral triangle * returns 4 if (i,j,k) are not the sides of a triangle * * an error has been inserted in the condition line 53 * when (i,j,k) = (2,4,2) returns 2 while it would return * 4 since the triangular inequality 2+2>4 is not verified */ void foo (int i, int j, int k) {//__CPROVER_assume((i == 1) && (j == 2) && (k ==1)); int trityp; if (i == 0 || j == 0 || k == 0) { trityp = 4; } else { trityp = 0; if (i == j) { trityp = trityp + 1; } if (i == k) { trityp = trityp + 2; } if (j == k) { trityp = trityp + 3; } if (trityp == 0) { if ((i+j) <= k || (j+k) <= i || (i+k) <= j) { trityp = 4; } else { trityp = 1; } } else { if (trityp > 3) { trityp = 3; } else { if (trityp == 1 && (i+j) > k) { trityp = 2; } else { // error in the condition : (i+j) > k) instead of (i+k) > j if (trityp == 2 && (i+j) > k) { // BUG trityp = 2; } else { if (trityp == 3 && (j+k) > i) { trityp = 2; } else { trityp = 4; } } } } } } __VERIFIER_assert(trityp== ((i == 0 || j == 0 || k == 0)?4:( (i!=j && i!=k && j!=k)?( ((i+j)<=k || (j+k)<=i || (i+k)<=j)?4:1 ):( ((i==j && j==k) || (j==k && i==k))?3:( (i==j && i!=k && j!=k && (i+j)>k)?2:( (i!=j && j!=k && i==k && (i+k)>j)?2:( ( ((i!=j && j==k && i!=k) || (i==j && j!=k && i==k)) && (j+k)>i)?2:4 ) ) ) ) )) ); } int main() { foo( __VERIFIER_nondet_int(),__VERIFIER_nondet_int(),__VERIFIER_nondet_int()); }