file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/225143798.c
/* * Copyright 2010 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. */ /* * Egyptian Cotton: maximize the thread count. */ #include <errno.h> #include <pthread.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static char const *short_usage = ("Usage: egytian_cotton [-fhv] [-n num_threads] [-s bytes]\n"); static char const *flags_usage = (" -f expect thread creation to fail for given\n" " thread creation parameters\n" " -h longer help\n" " -v increase verbosity\n" " -m use manual allocation of stacks\n" " -n number of additional threads to create\n" " -s stack size for each new thread\n"); static char const *long_winded_explanation[] = { "This is a test to exercise the thread library when used", "in a high thread-count situation. The exit status (and", "SUCCESS/FAIL output) will indicate success when all requested", "threads were created without error and the -f flag is not", "specified. This is typicaly used to make sure that a large", "number of threads can be created -- as long as the stack size", "requested is moderate, so we don't run out of memory", "Conversely, the -f flag is used to ensure that the thread", "library returns the appropriate error rather than faulting,", "when a larger-than-supported number of threads is requested,", "or if the total amount of stack memory exceeds available", "memory / address space", NULL, }; #define DEFAULT_NUM_THREADS ((size_t) 0x1000) #define DEFAULT_STACK_SIZE ((size_t) 0x4000) #if defined(__native_client__) # define PRIdS "d" # define PRIxS "x" #else # define PRIdS "zd" # define PRIxS "zx" #endif int gVerbosity = 0; int gExpectThreadCreationFailure = 0; int gAllocateStacksUsingMalloc = 0; size_t kNewlineMask = 0x3f; size_t kCountMask = 0xff; pthread_mutex_t gBarrierMu = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t gBarrierCv = PTHREAD_COND_INITIALIZER; int gThreadWait = 1; void *thread_start(void *state) { int tid = (int) (uintptr_t) state; int rv = 0; if (0 != (rv = pthread_mutex_lock(&gBarrierMu))) { printf("Mutex lock failed at thread %d, error %d (%s)\n", tid, rv, strerror(rv)); exit(1); } while (gThreadWait) { if (gVerbosity > 1) { printf("Thread %d: waiting\n", tid); } if (0 != (rv = pthread_cond_wait(&gBarrierCv, &gBarrierMu))) { printf("Cond wait failed at thread %d, error %d (%s)\n", tid, rv, strerror(rv)); exit(1); } } if (0 != (rv = pthread_mutex_unlock(&gBarrierMu))) { printf("Mutex unlock failed at thread %d, error %d (%s)\n", tid, rv, strerror(rv)); exit(1); } return NULL; } int main(int ac, char **av) { int opt; size_t num_threads = DEFAULT_NUM_THREADS; size_t stack_size = DEFAULT_STACK_SIZE; char const **line; int rv = 0; pthread_t thr_state; pthread_attr_t attr; size_t tid; char *stacks = 0; while (EOF != (opt = getopt(ac, av, "mfhn:s:v"))) { switch (opt) { #ifdef __GLIBC__ case 'm': gAllocateStacksUsingMalloc = 1; break; #else case 'm': printf("Option -m can only be used with GLibC\n"); rv = 1; goto cleanup_exit; #endif case 'f': gExpectThreadCreationFailure = 1; break; case 'n': num_threads = strtoul(optarg, (char **) NULL, 0); break; case 's': stack_size = strtoul(optarg, (char **) NULL, 0); break; case 'v': ++gVerbosity; break; case 'h': fprintf(stderr, "%s%s\n", short_usage, flags_usage); for (line = long_winded_explanation; NULL != *line; ++line) { fprintf(stderr, " %s\n", *line); } return 0; default: fprintf(stderr, "%s\n", short_usage); return 1; } } if (gVerbosity > 1) { printf("Creating %"PRIdS" threads with 0x%"PRIxS" byte stacks\n", num_threads, stack_size); printf("According to the command line parameters," " this is%s expected to work.\n", gExpectThreadCreationFailure ? " not" : ""); } if (0 != (rv = pthread_attr_init(&attr))) { printf("Pthread attr initializetion failed, error %d (%s)\n", rv, strerror(rv)); goto cleanup_exit; } if (!gAllocateStacksUsingMalloc) { if (0 != (rv = pthread_attr_setstacksize(&attr, stack_size))) { printf("Pthread stack size selection failed, error %d (%s)\n", rv, strerror(rv)); goto cleanup_exit; } } if (0 != (rv = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))) { printf("Pthread detach state selection failed, error %d (%s)\n", rv, strerror(rv)); goto cleanup_exit; } if (gAllocateStacksUsingMalloc) { stacks = malloc(stack_size * num_threads); if (NULL == stacks) { printf("Can not allocate memory for stacks"); rv = ENOMEM; goto cleanup_exit; } } for (tid = 0; tid < num_threads; ++tid) { if (gVerbosity > 0) { printf("Creating thread %"PRIdS"\n", tid); fflush(stdout); } /* * thr_state is overwritten each time. */ #ifdef __GLIBC__ if (gAllocateStacksUsingMalloc) { if (0 != (rv = pthread_attr_setstack(&attr, stacks + stack_size * tid, stack_size))) { printf("Pthread stack size selection failed, error %d (%s)\n", rv, strerror(rv)); goto cleanup_exit; } } #endif if (0 != (rv = pthread_create(&thr_state, &attr, thread_start, (void *) tid))) { printf("Thread creation failed at thread %"PRIdS", error %d (%s)\n", tid, rv, strerror(rv)); if (gExpectThreadCreationFailure) { if (EAGAIN == rv) { printf("This is expected.\n"); rv = 0; goto cleanup_exit; } /* * Anything other than EAGAIN is bad. */ } break; } putchar('.'); if (kCountMask == (tid & kCountMask)) { printf("%"PRIdS, tid); } if (kNewlineMask == (tid & kNewlineMask)) { putchar('\n'); } } if (0 == rv && gExpectThreadCreationFailure) { printf("Expected thread creation failure.\n"); rv = 1; } cleanup_exit: if (0 != (rv = pthread_mutex_lock(&gBarrierMu))) { printf("Mutex lock failed at main thread, error %d (%s)\n", rv, strerror(rv)); exit(1); } gThreadWait = 0; if (0 != (rv = pthread_cond_broadcast(&gBarrierCv))) { printf("Cond wait failed at main thread, error %d (%s)\n", rv, strerror(rv)); exit(1); } if (0 != (rv = pthread_mutex_unlock(&gBarrierMu))) { printf("Mutex unlock failed at main thread, error %d (%s)\n", rv, strerror(rv)); exit(1); } if (0 == rv) { printf("PASSED\n"); } else { printf("FAILED\n"); } return rv != 0; }
the_stack_data/11075712.c
#include <stdio.h> struct SLL { int data,ind; struct SLL *next; }; struct SLL *front = NULL; void add(int data,int ind) { struct SLL *t = (struct SLL *)malloc(sizeof(struct SLL)); t->data = data; t->ind = ind; t->next = NULL; if(front == NULL) front = t; else { struct SLL *trav; trav=front; while(trav->next!=NULL) trav = trav->next; trav->next=t; } } void print() { struct SLL *trav = front; while(trav!=NULL) { printf("%d ",trav->ind); trav=trav->next; } printf("\n"); } void shuffle(int k) { if(k==1 || k==0) return; struct SLL *start=front,*end=NULL,*trav=front; struct SLL* temp = (struct SLL *)malloc(sizeof(struct SLL)); while(start!=end) { trav=start; temp->data = start->data; temp->ind= start->ind; while(trav->next!=end) { trav->data = trav->next->data; trav->ind = trav->next->ind; trav=trav->next; } trav->data = temp->data; trav->ind = temp->ind; end = trav; if(((start->ind)%k)==0) start = start->next; } } int main() { int k,x,i=1; scanf("%d",&k); while(1) { scanf("%d",&x); if(x==-1) break; else { add(x,i); i++; } } print(); shuffle(k); print(); return 0; } // 3 1 2 3 4 5 6 7 8 9 -1
the_stack_data/198580892.c
// RUN: %clang_cc1 -E -x c %s > /dev/tty // The original bug requires UNIX line endings to trigger. // The original bug triggers only when outputting directly to console. // REQUIRES: console // Make sure clang does not crash during preprocessing #define M0 extern int x; #define M2 M0 M0 M0 M0 #define M4 M2 M2 M2 M2 #define M6 M4 M4 M4 M4 #define M8 M6 M6 M6 M6 #define M10 M8 M8 M8 M8 #define M12 M10 M10 M10 M10 #define M14 M12 M12 M12 M12 M14
the_stack_data/225142410.c
int a = 11, b = 22, c = 0; void main() { int d = 1 < c ? a : c; assert(d == 0, "d must be 0"); b = (14 > a ? a + 4 : a - 5 + 10) + (c <= a ? a : c); assert(b == 26, "b must be 26"); }
the_stack_data/181393851.c
/* ===========Programa que cria o arquivo gabrielvictor.txt========*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int randomNumber(int inicial, int final); int *criarListaNumeros(int qtdNumeros); void criarGabrielTxt(int qtdNumeros); int main() { srand(time(NULL)); int N; printf("Qual a quantidade de numeros a serem gerados?"); scanf("%d", &N); criarGabrielTxt(N); return 0; } void criarGabrielTxt(int qtdNumeros) { int *listaNumeros = criarListaNumeros(qtdNumeros); FILE *fp; fp = fopen("gabrielvictor.txt", "w+"); for (int i = 0; i < qtdNumeros; i++) { fprintf(fp, "%d\n", listaNumeros[i]); } fclose(fp); printf("\ngabrielvictor.txt Criado com SUCESSO\n"); } int randomNumber(int inicial, int final) { int x; do { x = (rand() % (final - inicial + 1)) + inicial; } while (x < inicial); return x; } int *criarListaNumeros(int qtdNumeros) { int *lista; lista = (int *)malloc(qtdNumeros * sizeof(int)); for (int i = 0; i < qtdNumeros; i++) { lista[i] = randomNumber(65, 75); } return lista; }
the_stack_data/161079593.c
union test { long a; int b; char c[2]; } a = { -1 }; int main() { return 10 + a.c[0]; }
the_stack_data/143326.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/time.h> /* * Simple time measurement tool that returns elapsed time * to run another command (passed in arguments). */ int main(int argc, char** argv) { if (argc<2) { fprintf(stderr,"Needs program to execute.\n"); exit(1); } struct timeval t1, t2; gettimeofday(&t1, NULL); pid_t f=fork(); switch (f) { case -1: fprintf(stderr,"Fork failed.\n"); exit(1); case 0: execvp(argv[1], &(argv[1])); default: waitpid(f,NULL,0); } gettimeofday(&t2, NULL); long delta = (t2.tv_sec-t1.tv_sec)*1000000+(t2.tv_usec-t1.tv_usec); printf("Running time: %ld ms\n",delta / 1000); return 0; }
the_stack_data/104829216.c
/* This may look like nonsense, but really is -*- mode: C -*- */ #include <stdio.h> /* The main thing that this program does. */ int main() { // Declarations int i; double A[5] = { 9.0, 2.9, 3.E+25, .00007, }; // Doing some work for (i = 0; i < 5; ++i) { printf("element %d is %g, \tits square is %g\n", /*@\label{printf-start-badly}*/ i, A[i], A[i]*A[i]); /*@\label{printf-end-badly}*/ } return 0; /*@\label{main-return-badly}*/ }
the_stack_data/21186.c
#include <stdio.h> // #include "export.h" int k = 1111; int cogbee(int i) { int tmp = k + i; printf("i = %d\n", tmp); return 22; } int main(void) { cogbee(55); printf("Hello world\n"); return 0; }
the_stack_data/151705249.c
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> // Implementation of a user-level buddy allocator // Union structure that will be used to represent a block of memory. // It will also serve as elements of a linked list of free memory. union block { struct { unsigned int size; // size of the memory block (will always be 4096 bytes) int numID; // number that represents this memory block int parentID; // number that represents this memory block's parent (if it is not a root) int buddyID; // number that represents this memory block's buddy block (if it is not a root) bool isSplit; bool isRoot; // used to indicate whether the block is a root or child union block *nextRoot; // will be NULL for child blocks union block *leftC; union block *rightC; }; }; typedef union block Block; // pointer pointing to the first block of the free list (or NULL if empty) static Block *freeList; // will be used when giving number IDs to each memory block static int count = 0; void bfree(void *freedMem) { Block *newBlock, *current; newBlock = (Block*) freedMem - 1; if (newBlock->isRoot) { // Add root block of memory to the end of the list for (current = freeList; current->nextRoot != NULL; current = current->nextRoot); current->nextRoot = newBlock; } else { // Todo Freeing child block (check for buddy blocks) } } // Function used to add more memory to the free list of memory (root blocks) static Block* addmemory(unsigned int nBytes) { char *temp; Block *newRoot; // In case freelist has not been constructed yet if (freeList == NULL) { freeList = (Block*) malloc(sizeof(Block)); freeList->size = 0; freeList->isSplit = false; freeList->isRoot = true; freeList->numID = count; count = count + 1; } // Ensure that the requested size of memory is 4096 bytes if (nBytes != 4096) { nBytes = 4096; } // Allocate 4096 bytes + additional bytes for Root structure temp = (char*) malloc(nBytes + sizeof(Block)); if (temp == NULL) { return NULL; } newRoot = (Block*) temp; // Properly initialize certain variables of the new root block newRoot->size = nBytes; newRoot->numID = count; newRoot->isSplit = false; newRoot->isRoot = true; count = count + 1; // Add the new root to the free list of memory using the free function bfree((void*)(newRoot + 1)); return freeList; } void* balloc(unsigned int nBytes) { Block *current, *previous; if (freeList == NULL) { freeList = (Block*) malloc(sizeof(Block)); freeList->size = 0; freeList->isSplit = false; freeList->isRoot = true; freeList->numID = count; count = count + 1; } previous = freeList; for (current = previous->nextRoot; ; previous = current, current = current->nextRoot) { if (current == NULL) { addmemory(nBytes); current = previous->nextRoot; } if (current->size >= nBytes) { if (current->size == nBytes || (current->size / 2.0) < nBytes) { previous->nextRoot = current->nextRoot; return (void*) (current + 1); } else { // Todo: splitting int newSize = current->size / 2.0; while (newSize >= nBytes) { } } } } } // Test for just seeing that you can add root blocks, allocate them, and then free // the allocated roots. Also to see whether freed blocks of memory still contained their // union data. int main() { addmemory(4096); if (freeList->nextRoot != NULL) { printf("Size of block: %u \n", freeList->nextRoot->size); } void* temp = balloc(4096); if (freeList->nextRoot == NULL) { printf("Empty\n"); } bfree(temp); if (freeList->nextRoot != NULL) { printf("Size of block: %u \n", freeList->nextRoot->size); } return 0; }
the_stack_data/61073982.c
/* * Greatest Common Divisor algorithm defined recursively */ #include <assert.h> /* assert */ #include <stdio.h> /* printf */ /* Greatest Common Divisor */ int gcd(int a, int b) { /* pre-condition */ assert (a > 0 && b > 0); /* post-condition */ if(a == b) return a; else if(a > b) return gcd(a - b, b); else return gcd(a, b - a); } int main(void) { int a; int b; int f; scanf("%d", &a); scanf("%d", &b); f = gcd(a,b); printf("%d\n", f); return 0; }
the_stack_data/129437.c
/** ****************************************************************************** * @file stm32g4xx_ll_ucpd.c * @author MCD Application Team * @brief UCPD LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2018 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32g4xx_ll_ucpd.h" #include "stm32g4xx_ll_bus.h" #include "stm32g4xx_ll_rcc.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32G4xx_LL_Driver * @{ */ #if defined (UCPD1) /** @addtogroup UCPD_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup UCPD_LL_Private_Constants UCPD Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup UCPD_LL_Private_Macros UCPD Private Macros * @{ */ /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup UCPD_LL_Exported_Functions * @{ */ /** @addtogroup UCPD_LL_EF_Init * @{ */ /** * @brief De-initialize the UCPD registers to their default reset values. * @param UCPDx ucpd Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: ucpd registers are de-initialized * - ERROR: ucpd registers are not de-initialized */ ErrorStatus LL_UCPD_DeInit(UCPD_TypeDef *UCPDx) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_UCPD_ALL_INSTANCE(UCPDx)); LL_UCPD_Disable(UCPDx); if (UCPD1 == UCPDx) { /* Force reset of ucpd clock */ LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_UCPD1); /* Release reset of ucpd clock */ LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_UCPD1); /* Disbale ucpd clock */ LL_APB1_GRP2_DisableClock(LL_APB1_GRP2_PERIPH_UCPD1); status = SUCCESS; } return status; } /** * @brief Initialize the ucpd registers according to the specified parameters in UCPD_InitStruct. * @note As some bits in ucpd configuration registers can only be written when the ucpd is disabled (ucpd_CR1_SPE bit =0), * UCPD peripheral should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. * @param UCPDx UCPD Instance * @param UCPD_InitStruct pointer to a @ref LL_UCPD_InitTypeDef structure that contains * the configuration information for the UCPD peripheral. * @retval An ErrorStatus enumeration value. (Return always SUCCESS) */ ErrorStatus LL_UCPD_Init(UCPD_TypeDef *UCPDx, LL_UCPD_InitTypeDef *UCPD_InitStruct) { /* Check the ucpd Instance UCPDx*/ assert_param(IS_UCPD_ALL_INSTANCE(UCPDx)); if(UCPD1 == UCPDx) { LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_UCPD1); } LL_UCPD_Disable(UCPDx); /*---------------------------- UCPDx CFG1 Configuration ------------------------*/ MODIFY_REG(UCPDx->CFG1, UCPD_CFG1_PSC_UCPDCLK | UCPD_CFG1_TRANSWIN | UCPD_CFG1_IFRGAP | UCPD_CFG1_HBITCLKDIV, UCPD_InitStruct->psc_ucpdclk | (UCPD_InitStruct->transwin << UCPD_CFG1_TRANSWIN_Pos) | (UCPD_InitStruct->IfrGap << UCPD_CFG1_IFRGAP_Pos) | UCPD_InitStruct->HbitClockDiv); return SUCCESS; } /** * @brief Set each @ref LL_UCPD_InitTypeDef field to default value. * @param UCPD_InitStruct pointer to a @ref LL_UCPD_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_UCPD_StructInit(LL_UCPD_InitTypeDef *UCPD_InitStruct) { /* Set UCPD_InitStruct fields to default values */ UCPD_InitStruct->psc_ucpdclk = LL_UCPD_PSC_DIV1; UCPD_InitStruct->transwin = 0x7; /* Divide by 8 */ UCPD_InitStruct->IfrGap = 0x10; /* Divide by 17 */ UCPD_InitStruct->HbitClockDiv = 0x1A; /* Divide by 27 to produce HBITCLK */ } /** * @} */ /** * @} */ /** * @} */ #endif /* defined (UCPD1) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/166933.c
// stb_truetype.h - v0.8b - public domain // authored from 2009-2013 by Sean Barrett / RAD Game Tools // // This library processes TrueType files: // parse files // extract glyph metrics // extract glyph shapes // render glyphs to one-channel bitmaps with antialiasing (box filter) // // Todo: // non-MS cmaps // crashproof on bad data // hinting? (no longer patented) // cleartype-style AA? // optimize: use simple memory allocator for intermediates // optimize: build edge-list directly from curves // optimize: rasterize directly from curves? // // ADDITIONAL CONTRIBUTORS // // Mikko Mononen: compound shape support, more cmap formats // Tor Andersson: kerning, subpixel rendering // // Bug/warning reports: // "Zer" on mollyrocket (with fix) // Cass Everitt // stoiko (Haemimont Games) // Brian Hook // Walter van Niftrik // David Gow // David Given // Ivan-Assen Ivanov // Anthony Pesch // Johan Duparc // // VERSION HISTORY // // 0.8b (2014-07-07) fix a warning // 0.8 (2014-05-25) fix a few more warnings // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back // 0.6c (2012-07-24) improve documentation // 0.6b (2012-07-20) fix a few more warnings // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty // 0.5 (2011-12-09) bugfixes: // subpixel glyph renderer computed wrong bounding box // first vertex of shape can be off-curve (FreeSans) // 0.4b (2011-12-03) fixed an error in the font baking example // 0.4 (2011-12-01) kerning, subpixel rendering (tor) // bugfixes for: // codepoint-to-glyph conversion using table fmt=12 // codepoint-to-glyph conversion using table fmt=4 // stbtt_GetBakedQuad with non-square texture (Zer) // updated Hello World! sample to use kerning and subpixel // fixed some warnings // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) // userdata, malloc-from-userdata, non-zero fill (STB) // 0.2 (2009-03-11) Fix unsigned/signed char warnings // 0.1 (2009-03-09) First public release // // LICENSE // // This software is in the public domain. Where that dedication is not // recognized, you are granted a perpetual, irrevokable license to copy // and modify this file as you see fit. // // USAGE // // Include this file in whatever places neeed to refer to it. In ONE C/C++ // file, write: // #define STB_TRUETYPE_IMPLEMENTATION // before the #include of this file. This expands out the actual // implementation into that C/C++ file. // // Simple 3D API (don't ship this, but it's fine for tools and quick start, // and you can cut and paste from it to move to more advanced) // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture // stbtt_GetBakedQuad() -- compute quad to draw for a given char // // "Load" a font file from a memory buffer (you have to keep the buffer loaded) // stbtt_InitFont() // stbtt_GetFontOffsetForIndex() -- use for TTC font collections // // Render a unicode codepoint to a bitmap // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be // // Character advance/positioning // stbtt_GetCodepointHMetrics() // stbtt_GetFontVMetrics() // stbtt_GetCodepointKernAdvance() // // ADDITIONAL DOCUMENTATION // // Immediately after this block comment are a series of sample programs. // // After the sample programs is the "header file" section. This section // includes documentation for each API function. // // Some important concepts to understand to use this library: // // Codepoint // Characters are defined by unicode codepoints, e.g. 65 is // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is // the hiragana for "ma". // // Glyph // A visual character shape (every codepoint is rendered as // some glyph) // // Glyph index // A font-specific integer ID representing a glyph // // Baseline // Glyph shapes are defined relative to a baseline, which is the // bottom of uppercase characters. Characters extend both above // and below the baseline. // // Current Point // As you draw text to the screen, you keep track of a "current point" // which is the origin of each character. The current point's vertical // position is the baseline. Even "baked fonts" use this model. // // Vertical Font Metrics // The vertical qualities of the font, used to vertically position // and space the characters. See docs for stbtt_GetFontVMetrics. // // Font Size in Pixels or Points // The preferred interface for specifying font sizes in stb_truetype // is to specify how tall the font's vertical extent should be in pixels. // If that sounds good enough, skip the next paragraph. // // Most font APIs instead use "points", which are a common typographic // measurement for describing font size, defined as 72 points per inch. // stb_truetype provides a point API for compatibility. However, true // "per inch" conventions don't make much sense on computer displays // since they different monitors have different number of pixels per // inch. For example, Windows traditionally uses a convention that // there are 96 pixels per inch, thus making 'inch' measurements have // nothing to do with inches, and thus effectively defining a point to // be 1.333 pixels. Additionally, the TrueType font data provides // an explicit scale factor to scale a given font's glyphs to points, // but the author has observed that this scale factor is often wrong // for non-commercial fonts, thus making fonts scaled in points // according to the TrueType spec incoherently sized in practice. // // ADVANCED USAGE // // Quality: // // - Use the functions with Subpixel at the end to allow your characters // to have subpixel positioning. Since the font is anti-aliased, not // hinted, this is very import for quality. (This is not possible with // baked fonts.) // // - Kerning is now supported, and if you're supporting subpixel rendering // then kerning is worth using to give your text a polished look. // // Performance: // // - Convert Unicode codepoints to glyph indexes and operate on the glyphs; // if you don't do this, stb_truetype is forced to do the conversion on // every call. // // - There are a lot of memory allocations. We should modify it to take // a temp buffer and allocate from the temp buffer (without freeing), // should help performance a lot. // // NOTES // // The system uses the raw data found in the .ttf file without changing it // and without building auxiliary data structures. This is a bit inefficient // on little-endian systems (the data is big-endian), but assuming you're // caching the bitmaps or glyph shapes this shouldn't be a big deal. // // It appears to be very hard to programmatically determine what font a // given file is in a general way. I provide an API for this, but I don't // recommend it. // // // SOURCE STATISTICS (based on v0.6c, 2050 LOC) // // Documentation & header file 520 LOC \___ 660 LOC documentation // Sample code 140 LOC / // Truetype parsing 620 LOC ---- 620 LOC TrueType // Software rasterization 240 LOC \ . // Curve tesselation 120 LOC \__ 550 LOC Bitmap creation // Bitmap management 100 LOC / // Baked bitmap interface 70 LOC / // Font name matching & access 150 LOC ---- 150 // C runtime library abstraction 60 LOC ---- 60 ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //// //// SAMPLE PROGRAMS //// // // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless // #if 0 #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" char ttf_buffer[1<<20]; unsigned char temp_bitmap[512*512]; stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs GLstbtt_uint ftex; void my_stbtt_initfont(void) { fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb")); stbtt_BakeFontBitmap(data,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! // can free ttf_buffer at this point glGenTextures(1, &ftex); glBindTexture(GL_TEXTURE_2D, ftex); glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap); // can free temp_bitmap at this point glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } void my_stbtt_print(float x, float y, char *text) { // assume orthographic projection with units = screen pixels, origin at top left glBindTexture(GL_TEXTURE_2D, ftex); glBegin(GL_QUADS); while (*text) { if (*text >= 32 && *text < 128) { stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0); glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0); glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1); glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1); } ++text; } glEnd(); } #endif // // ////////////////////////////////////////////////////////////////////////////// // // Complete program (this compiles): get a single bitmap, print as ASCII art // #if 0 #include <stdio.h> #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" char ttf_buffer[1<<25]; int main(int argc, char **argv) { stbtt_fontinfo font; unsigned char *bitmap; int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); for (j=0; j < h; ++j) { for (i=0; i < w; ++i) putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); putchar('\n'); } return 0; } #endif // // Output: // // .ii. // @@@@@@. // V@Mio@@o // :i. V@V // :oM@@M // :@@@MM@M // @@o o@M // :@@. M@M // @@@o@@@@ // :M@@V:@@. // ////////////////////////////////////////////////////////////////////////////// // // Complete program: print "Hello World!" banner, with bugs // #if 0 char buffer[24<<20]; unsigned char screen[20][79]; int main(int arg, char **argv) { stbtt_fontinfo font; int i,j,ascent,baseline,ch=0; float scale, xpos=2; // leave a little padding in case the character extends left char *text = "Heljo World!"; fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, buffer, 0); scale = stbtt_ScaleForPixelHeight(&font, 15); stbtt_GetFontVMetrics(&font, &ascent,0,0); baseline = (int) (ascent*scale); while (text[ch]) { int advance,lsb,x0,y0,x1,y1; float x_shift = xpos - (float) floor(xpos); stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong // because this API is really for baking character bitmaps into textures. if you want to render // a sequence of characters, you really need to render each bitmap to a temp buffer, then // "alpha blend" that into the working buffer xpos += (advance * scale); if (text[ch+1]) xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); ++ch; } for (j=0; j < 20; ++j) { for (i=0; i < 78; ++i) putchar(" .:ioVM@"[screen[j][i]>>5]); putchar('\n'); } return 0; } #endif ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //// //// INTEGRATION WITH YOUR CODEBASE //// //// The following sections allow you to supply alternate definitions //// of C library functions used by stb_truetype. #ifndef STB_TRUETYPE_IMPLEMENTATION // #define your own (u)stbtt_int8/16/32 before including to override this #ifndef stbtt_uint8 typedef unsigned char stbtt_uint8; typedef signed char stbtt_int8; typedef unsigned short stbtt_uint16; typedef signed short stbtt_int16; typedef unsigned int stbtt_uint32; typedef signed int stbtt_int32; #endif typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; // #define your own STBTT_sort() to override this to avoid qsort #ifndef STBTT_sort #include <stdlib.h> #define STBTT_sort(data,num_items,item_size,compare_func) qsort(data,num_items,item_size,compare_func) #endif // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h #ifndef STBTT_ifloor #include <math.h> #define STBTT_ifloor(x) ((int) floor(x)) #define STBTT_iceil(x) ((int) ceil(x)) #endif #ifndef STBTT_sqrt #include <math.h> #define STBTT_sqrt(x) sqrt(x) #endif // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h #ifndef STBTT_malloc #include <stdlib.h> #define STBTT_malloc(x,u) ((void)(u),malloc(x)) #define STBTT_free(x,u) ((void)(u),free(x)) #endif #ifndef STBTT_assert #include <assert.h> #define STBTT_assert(x) assert(x) #endif #ifndef STBTT_strlen #include <string.h> #define STBTT_strlen(x) strlen(x) #endif #ifndef STBTT_memcpy #include <memory.h> #define STBTT_memcpy memcpy #define STBTT_memset memset #endif #endif /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// INTERFACE //// //// #ifndef __STB_INCLUDE_STB_TRUETYPE_H__ #define __STB_INCLUDE_STB_TRUETYPE_H__ #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 #define WExport __declspec(dllexport) #else #define WExport #endif ////////////////////////////////////////////////////////////////////////////// // // TEXTURE BAKING API // // If you use this API, you only have to call two functions ever. // typedef struct { unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap float xoff,yoff,xadvance; } stbtt_bakedchar; WExport extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata); // you allocate this, it's num_chars long // if return is positive, the first unused row of the bitmap // if return is negative, returns the negative of the number of characters that fit // if return is 0, no characters fit and no rows were used // This uses a very crappy packing. typedef struct { float x0,y0,s0,t0; // top-left float x1,y1,s1,t1; // bottom-right } stbtt_aligned_quad; WExport extern void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space stbtt_aligned_quad *q, // output: quad to draw int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier // Call GetBakedQuad with char_index = 'character - first_char', and it // creates the quad you need to draw and advances the current position. // // The coordinate system used assumes y increases downwards. // // Characters will extend both above and below the current position; // see discussion of "BASELINE" above. // // It's inefficient; you might want to c&p it and optimize it. ////////////////////////////////////////////////////////////////////////////// // // FONT LOADING // // WExport extern int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); // Each .ttf/.ttc file may have more than one font. Each font has a sequential // index number starting from 0. Call this function to get the font offset for // a given index; it returns -1 if the index is out of range. A regular .ttf // file will only define one font and it always be at offset 0, so it will // return '0' for index 0, and -1 for all other indices. You can just skip // this step if you know it's that kind of font. // The following structure is defined publically so you can declare one on // the stack or as a global or etc, but you should treat it as opaque. typedef struct stbtt_fontinfo { void * userdata; unsigned char * data; // pointer to .ttf file int fontstart; // offset of start of font int numGlyphs; // number of glyphs, needed for range checking int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph } stbtt_fontinfo; WExport extern int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); // Given an offset into the file that defines a font, this function builds // the necessary cached info for the rest of the system. You must allocate // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't // need to do anything special to free it, because the contents are pure // value data with no additional data structures. Returns 0 on failure. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER TO GLYPH-INDEX CONVERSIOn WExport int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); // If you're going to perform multiple operations on the same character // and you want a speed-up, call this function with the character you're // going to process, then use glyph-based functions instead of the // codepoint-based functions. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER PROPERTIES // WExport extern float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose "height" is 'pixels' tall. // Height is measured as the distance from the highest ascender to the lowest // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics // and computing: // scale = pixels / (ascent - descent) // so if you prefer to measure height by the ascent only, use a similar calculation. WExport extern float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose EM size is mapped to // 'pixels' tall. This is probably what traditional APIs compute, but // I'm not positive. WExport extern void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); // ascent is the coordinate above the baseline the font extends; descent // is the coordinate below the baseline the font extends (i.e. it is typically negative) // lineGap is the spacing between one row's descent and the next row's ascent... // so you should advance the vertical position by "*ascent - *descent + *lineGap" // these are expressed in unscaled coordinates, so you must multiply by // the scale factor for a given size WExport extern void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); // the bounding box around all possible characters WExport extern void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); // leftSideBearing is the offset from the current horizontal position to the left edge of the character // advanceWidth is the offset from the current horizontal position to the next horizontal position // these are expressed in unscaled coordinates WExport extern int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); // an additional amount to add to the 'advance' value between ch1 and ch2 WExport extern int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); // Gets the bounding box of the visible part of the glyph, in unscaled coordinates WExport extern void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); WExport extern int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); WExport extern int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); // as above, but takes one or more glyph indices for greater efficiency ////////////////////////////////////////////////////////////////////////////// // // GLYPH SHAPES (you probably don't need these, but they have to go before // the bitmaps for C declaration-order reasons) // #ifndef STBTT_vmove // you can predefine these to use different values (but why?) enum { STBTT_vmove=1, STBTT_vline, STBTT_vcurve }; #endif #ifndef stbtt_vertex // you can predefine this to use different values // (we share this with other code at RAD) #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file typedef struct { stbtt_vertex_type x,y,cx,cy; unsigned char type,padding; } stbtt_vertex; #endif WExport extern int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); // returns non-zero if nothing is drawn for this glyph WExport extern int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); WExport extern int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); // returns # of vertices and fills *vertices with the pointer to them // these are expressed in "unscaled" coordinates // // The shape is a series of countours. Each one starts with // a STBTT_moveto, then consists of a series of mixed // STBTT_lineto and STBTT_curveto segments. A lineto // draws a line from previous endpoint to its x,y; a curveto // draws a quadratic bezier from previous endpoint to // its x,y, using cx,cy as the bezier control point. WExport extern void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); // frees the data allocated above ////////////////////////////////////////////////////////////////////////////// // // BITMAP RENDERING // WExport extern void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); // frees the bitmap allocated below WExport extern unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // allocates a large-enough single-channel 8bpp bitmap and renders the // specified character/glyph at the specified scale into it, with // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). // *width & *height are filled out with the width & height of the bitmap, // which is stored left-to-right, top-to-bottom. // // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap WExport extern unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel // shift for the character WExport extern void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the // width and height and positioning info for it first. WExport extern void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel // shift for the character WExport extern void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); // get the bbox of the bitmap centered around the glyph origin; so the // bitmap width is ix1-ix0, height is iy1-iy0, and location to place // the bitmap top left is (leftSideBearing*scale,iy0). // (Note that the bitmap uses y-increases-down, but the shape uses // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) WExport extern void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel // shift for the character // the following functions are equivalent to the above functions, but operate // on glyph indices instead of Unicode codepoints (for efficiency) WExport extern unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); WExport extern unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); WExport extern void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); WExport extern void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); WExport extern void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); WExport extern void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); // @TODO: don't expose this structure typedef struct { int w,h,stride; unsigned char *pixels; } stbtt__bitmap; WExport extern void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata); ////////////////////////////////////////////////////////////////////////////// // // Finding the right font... // // You should really just solve this offline, keep your own tables // of what font is what, and don't try to get it out of the .ttf file. // That's because getting it out of the .ttf file is really hard, because // the names in the file can appear in many possible encodings, in many // possible languages, and e.g. if you need a case-insensitive comparison, // the details of that depend on the encoding & language in a complex way // (actually underspecified in truetype, but also gigantic). // // But you can use the provided functions in two possible ways: // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on // unicode-encoded names to try to find the font you want; // you can run this before calling stbtt_InitFont() // // stbtt_GetFontNameString() lets you get any of the various strings // from the file yourself and do your own comparisons on them. // You have to have called stbtt_InitFont() first. extern int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); // returns the offset (not index) of the font that matches, or -1 if none // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". // if you use any other flag, use a font name like "Arial"; this checks // the 'macStyle' header field; i don't know if fonts set this consistently #define STBTT_MACSTYLE_DONTCARE 0 #define STBTT_MACSTYLE_BOLD 1 #define STBTT_MACSTYLE_ITALIC 2 #define STBTT_MACSTYLE_UNDERSCORE 4 #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 WExport extern int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); // returns 1/0 whether the first string interpreted as utf8 is identical to // the second string interpreted as big-endian utf16... useful for strings from next func WExport extern const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); // returns the string (which may be big-endian double byte, e.g. for unicode) // and puts the length in bytes in *length. // // some of the values for the IDs are below; for more see the truetype spec: // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html // http://www.microsoft.com/typography/otspec/name.htm enum { // platformID STBTT_PLATFORM_ID_UNICODE =0, STBTT_PLATFORM_ID_MAC =1, STBTT_PLATFORM_ID_ISO =2, STBTT_PLATFORM_ID_MICROSOFT =3 }; enum { // encodingID for STBTT_PLATFORM_ID_UNICODE STBTT_UNICODE_EID_UNICODE_1_0 =0, STBTT_UNICODE_EID_UNICODE_1_1 =1, STBTT_UNICODE_EID_ISO_10646 =2, STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 }; enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT STBTT_MS_EID_SYMBOL =0, STBTT_MS_EID_UNICODE_BMP =1, STBTT_MS_EID_SHIFTJIS =2, STBTT_MS_EID_UNICODE_FULL =10 }; enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 }; enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D }; enum { // languageID for STBTT_PLATFORM_ID_MAC STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 }; #ifdef __cplusplus } #endif #endif // __STB_INCLUDE_STB_TRUETYPE_H__ /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// IMPLEMENTATION //// //// #ifndef STB_TRUETYPE_IMPLEMENTATION ////////////////////////////////////////////////////////////////////////// // // accessors to parse data from file // // on platforms that don't allow misaligned reads, if we want to allow // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE #define ttBYTE(p) (* (stbtt_uint8 *) (p)) #define ttCHAR(p) (* (stbtt_int8 *) (p)) #define ttFixed(p) ttLONG(p) #if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE) #define ttUSHORT(p) (* (stbtt_uint16 *) (p)) #define ttSHORT(p) (* (stbtt_int16 *) (p)) #define ttULONG(p) (* (stbtt_uint32 *) (p)) #define ttLONG(p) (* (stbtt_int32 *) (p)) #else stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; } stbtt_int16 ttSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; } stbtt_uint32 ttULONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } stbtt_int32 ttLONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } #endif #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) static int stbtt__isfont(const stbtt_uint8 *font) { // check the version number if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 return 0; } // @OPTIMIZE: binary search static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) { stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); stbtt_uint32 tabledir = fontstart + 12; stbtt_int32 i; for (i=0; i < num_tables; ++i) { stbtt_uint32 loc = tabledir + 16*i; if (stbtt_tag(data+loc+0, tag)) return ttULONG(data+loc+8); } return 0; } int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index) { // if it's just a font, there's only one valid index if (stbtt__isfont(font_collection)) return index == 0 ? 0 : -1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { stbtt_int32 n = ttLONG(font_collection+8); if (index >= n) return -1; return ttULONG(font_collection+12+index*14); } } return -1; } int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart) { stbtt_uint8 *data = (stbtt_uint8 *) data2; stbtt_uint32 cmap, t; stbtt_int32 i,numTables; info->data = data; info->fontstart = fontstart; cmap = stbtt__find_table(data, fontstart, "cmap"); // required info->loca = stbtt__find_table(data, fontstart, "loca"); // required info->head = stbtt__find_table(data, fontstart, "head"); // required info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required info->kern = stbtt__find_table(data, fontstart, "kern"); // not required if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx) return 0; t = stbtt__find_table(data, fontstart, "maxp"); if (t) info->numGlyphs = ttUSHORT(data+t+4); else info->numGlyphs = 0xffff; // find a cmap encoding table we understand *now* to avoid searching // later. (todo: could make this installable) // the same regardless of glyph. numTables = ttUSHORT(data + cmap + 2); info->index_map = 0; for (i=0; i < numTables; ++i) { stbtt_uint32 encoding_record = cmap + 4 + 8 * i; // find an encoding we understand: switch(ttUSHORT(data+encoding_record)) { case STBTT_PLATFORM_ID_MICROSOFT: switch (ttUSHORT(data+encoding_record+2)) { case STBTT_MS_EID_UNICODE_BMP: case STBTT_MS_EID_UNICODE_FULL: // MS/Unicode info->index_map = cmap + ttULONG(data+encoding_record+4); break; } break; } } if (info->index_map == 0) return 0; info->indexToLocFormat = ttUSHORT(data+info->head + 50); return 1; } int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) { stbtt_uint8 *data = info->data; stbtt_uint32 index_map = info->index_map; stbtt_uint16 format = ttUSHORT(data + index_map + 0); if (format == 0) { // apple byte encoding stbtt_int32 bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) return ttBYTE(data + index_map + 6 + unicode_codepoint); return 0; } else if (format == 6) { stbtt_uint32 first = ttUSHORT(data + index_map + 6); stbtt_uint32 count = ttUSHORT(data + index_map + 8); if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); return 0; } else if (format == 2) { STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean return 0; } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; stbtt_uint16 item, offset, start, end; // do a binary search of the segments stbtt_uint32 endCount = index_map + 14; stbtt_uint32 search = endCount; if (unicode_codepoint > 0xffff) return 0; // they lie from endCount .. endCount + segCount // but searchRange is the nearest power of two, so... if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) search += rangeShift*2; // now decrement to bias correctly to find smallest search -= 2; while (entrySelector) { searchRange >>= 1; start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2); end = ttUSHORT(data + search + searchRange*2); if (unicode_codepoint > end) search += searchRange*2; --entrySelector; } search += 2; item = (stbtt_uint16) ((search - endCount) >> 1); STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); end = ttUSHORT(data + index_map + 14 + 2 + 2*item); if (unicode_codepoint < start) return 0; offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); if (offset == 0) return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); } else if (format == 12 || format == 13) { stbtt_uint32 ngroups = ttULONG(data+index_map+12); stbtt_int32 low,high; low = 0; high = (stbtt_int32)ngroups; // Binary search the right group. while (low < high) { stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); if ((stbtt_uint32) unicode_codepoint < start_char) high = mid; else if ((stbtt_uint32) unicode_codepoint > end_char) low = mid+1; else { stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); if (format == 12) return start_glyph + unicode_codepoint-start_char; else // format == 13 return start_glyph; } } return 0; // not found } // @TODO STBTT_assert(0); return 0; } int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) { return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); } static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) { v->type = type; v->x = (stbtt_int16) x; v->y = (stbtt_int16) y; v->cx = (stbtt_int16) cx; v->cy = (stbtt_int16) cy; } static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) { int g1,g2; if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format if (info->indexToLocFormat == 0) { g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; } else { g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); } return g1==g2 ? -1 : g1; // if length is 0, return -1 } int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; if (x0) *x0 = ttSHORT(info->data + g + 2); if (y0) *y0 = ttSHORT(info->data + g + 4); if (x1) *x1 = ttSHORT(info->data + g + 6); if (y1) *y1 = ttSHORT(info->data + g + 8); return 1; } int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) { return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); } int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) { stbtt_int16 numberOfContours; int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 1; numberOfContours = ttSHORT(info->data + g); return numberOfContours == 0; } static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) { if (start_off) { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); } return num_vertices; } int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { stbtt_int16 numberOfContours; stbtt_uint8 *endPtsOfContours; stbtt_uint8 *data = info->data; stbtt_vertex *vertices=0; int num_vertices=0; int g = stbtt__GetGlyfOffset(info, glyph_index); *pvertices = NULL; if (g < 0) return 0; numberOfContours = ttSHORT(data + g); if (numberOfContours > 0) { stbtt_uint8 flags=0,flagcount; stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; stbtt_uint8 *points; endPtsOfContours = (data + g + 10); ins = ttUSHORT(data + g + 10 + numberOfContours * 2); points = data + g + 10 + numberOfContours * 2 + 2 + ins; n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); m = n + 2*numberOfContours; // a loose bound on how many vertices we might need vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); if (vertices == 0) return 0; next_move = 0; flagcount=0; // in first pass, we load uninterpreted data into the allocated array // above, shifted to the end of the array so we won't overwrite it when // we create our final data starting from the front off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated // first load flags for (i=0; i < n; ++i) { if (flagcount == 0) { flags = *points++; if (flags & 8) flagcount = *points++; } else --flagcount; vertices[off+i].type = flags; } // now load x coordinates x=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 2) { stbtt_int16 dx = *points++; x += (flags & 16) ? dx : -dx; // ??? } else { if (!(flags & 16)) { x = x + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].x = (stbtt_int16) x; } // now load y coordinates y=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 4) { stbtt_int16 dy = *points++; y += (flags & 32) ? dy : -dy; // ??? } else { if (!(flags & 32)) { y = y + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].y = (stbtt_int16) y; } // now convert them to our format num_vertices=0; sx = sy = cx = cy = scx = scy = 0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; x = (stbtt_int16) vertices[off+i].x; y = (stbtt_int16) vertices[off+i].y; if (next_move == i) { if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); // now start the new one start_off = !(flags & 1); if (start_off) { // if we start off with an off-curve point, then when we need to find a point on the curve // where we can start, and we need to save some state for when we wraparound. scx = x; scy = y; if (!(vertices[off+i+1].type & 1)) { // next point is also a curve point, so interpolate an on-point curve sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; } else { // otherwise just use the next point as our start point sx = (stbtt_int32) vertices[off+i+1].x; sy = (stbtt_int32) vertices[off+i+1].y; ++i; // we're using point i+1 as the starting point, so skip it } } else { sx = x; sy = y; } stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); was_off = 0; next_move = 1 + ttUSHORT(endPtsOfContours+j*2); ++j; } else { if (!(flags & 1)) { // if it's a curve if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); cx = x; cy = y; was_off = 1; } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); was_off = 0; } } } num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); } else if (numberOfContours == -1) { // Compound shapes. int more = 1; stbtt_uint8 *comp = data + g + 10; num_vertices = 0; vertices = 0; while (more) { stbtt_uint16 flags, gidx; int comp_num_verts = 0, i; stbtt_vertex *comp_verts = 0, *tmp = 0; float mtx[6] = {1,0,0,1,0,0}, m, n; flags = ttSHORT(comp); comp+=2; gidx = ttSHORT(comp); comp+=2; if (flags & 2) { // XY values if (flags & 1) { // shorts mtx[4] = ttSHORT(comp); comp+=2; mtx[5] = ttSHORT(comp); comp+=2; } else { mtx[4] = ttCHAR(comp); comp+=1; mtx[5] = ttCHAR(comp); comp+=1; } } else { // @TODO handle matching point STBTT_assert(0); } if (flags & (1<<3)) { // WE_HAVE_A_SCALE mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } // Find transformation scales. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); // Get indexed glyph. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); if (comp_num_verts > 0) { // Transform vertices. for (i = 0; i < comp_num_verts; ++i) { stbtt_vertex* v = &comp_verts[i]; stbtt_vertex_type x,y; x=v->x; y=v->y; v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); x=v->cx; y=v->cy; v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); } // Append vertices. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); if (!tmp) { if (vertices) STBTT_free(vertices, info->userdata); if (comp_verts) STBTT_free(comp_verts, info->userdata); return 0; } if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); if (vertices) STBTT_free(vertices, info->userdata); vertices = tmp; STBTT_free(comp_verts, info->userdata); num_vertices += comp_num_verts; } // More components ? more = flags & (1<<5); } } else if (numberOfContours < 0) { // @TODO other compound variations? STBTT_assert(0); } else { // numberOfCounters == 0, do nothing } *pvertices = vertices; return num_vertices; } void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) { stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); if (glyph_index < numOfLongHorMetrics) { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); } else { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); } } int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) { stbtt_uint8 *data = info->data + info->kern; stbtt_uint32 needle, straw; int l, r, m; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; l = 0; r = ttUSHORT(data+10) - 1; needle = glyph1 << 16 | glyph2; while (l <= r) { m = (l + r) >> 1; straw = ttULONG(data+18+(m*6)); // note: unaligned read if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else return ttSHORT(data+22+(m*6)); } return 0; } int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) { if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs return 0; return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); } void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) { stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); } void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) { if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); if (descent) *descent = ttSHORT(info->data+info->hhea + 6); if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); } void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) { *x0 = ttSHORT(info->data + info->head + 36); *y0 = ttSHORT(info->data + info->head + 38); *x1 = ttSHORT(info->data + info->head + 40); *y1 = ttSHORT(info->data + info->head + 42); } float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) { int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); return (float) height / fheight; } float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) { int unitsPerEm = ttUSHORT(info->data + info->head + 18); return pixels / unitsPerEm; } void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) { STBTT_free(v, info->userdata); } ////////////////////////////////////////////////////////////////////////////// // // antialiasing software rasterizer // void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { int x0,y0,x1,y1; if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) x0=y0=x1=y1=0; // e.g. space character // now move to integral bboxes (treating pixels as little squares, what pixels get touched)? if (ix0) *ix0 = STBTT_ifloor(x0 * scale_x + shift_x); if (iy0) *iy0 = -STBTT_iceil (y1 * scale_y + shift_y); if (ix1) *ix1 = STBTT_iceil (x1 * scale_x + shift_x); if (iy1) *iy1 = -STBTT_ifloor(y0 * scale_y + shift_y); } void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); } void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); } void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); } typedef struct stbtt__edge { float x0,y0, x1,y1; int invert; } stbtt__edge; typedef struct stbtt__active_edge { int x,dx; float ey; struct stbtt__active_edge *next; int valid; } stbtt__active_edge; #define FIXSHIFT 10 #define FIX (1 << FIXSHIFT) #define FIXMASK (FIX-1) static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata) { stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!! float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); STBTT_assert(e->y0 <= start_point); if (!z) return z; // round dx down to avoid going too far if (dxdy < 0) z->dx = -STBTT_ifloor(FIX * -dxdy); else z->dx = STBTT_ifloor(FIX * dxdy); z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0))); z->x -= off_x * FIX; z->ey = e->y1; z->next = 0; z->valid = e->invert ? 1 : -1; return z; } // note: this routine clips fills that extend off the edges... ideally this // wouldn't happen, but it could happen if the truetype glyph bounding boxes // are wrong, or if the user supplies a too-small bitmap static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) { // non-zero winding fill int x0=0, w=0; while (e) { if (w == 0) { // if we're currently at zero, we need to record the edge start point x0 = e->x; w += e->valid; } else { int x1 = e->x; w += e->valid; // if we went to zero, we need to draw if (w == 0) { int i = x0 >> FIXSHIFT; int j = x1 >> FIXSHIFT; if (i < len && j >= 0) { if (i == j) { // x0,x1 are the same pixel, so compute combined coverage scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> FIXSHIFT); } else { if (i >= 0) // add antialiasing for x0 scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT); else i = -1; // clip if (j < len) // add antialiasing for x1 scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> FIXSHIFT); else j = len; // clip for (++i; i < j; ++i) // fill pixels between x0 and x1 scanline[i] = scanline[i] + (stbtt_uint8) max_weight; } } } } e = e->next; } } static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { stbtt__active_edge *active = NULL; int y,j=0; int max_weight = (255 / vsubsample); // weight per vertical scanline int s; // vertical subsample index unsigned char scanline_data[512], *scanline; if (result->w > 512) scanline = (unsigned char *) STBTT_malloc(result->w, userdata); else scanline = scanline_data; y = off_y * vsubsample; e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; while (j < result->h) { STBTT_memset(scanline, 0, result->w); for (s=0; s < vsubsample; ++s) { // find center of pixel for this scanline float scan_y = y + 0.5f; stbtt__active_edge **step = &active; // update all active edges; // remove all active edges that terminate before the center of this scanline while (*step) { stbtt__active_edge * z = *step; if (z->ey <= scan_y) { *step = z->next; // delete from list STBTT_assert(z->valid); z->valid = 0; STBTT_free(z, userdata); } else { z->x += z->dx; // advance to position for current scanline step = &((*step)->next); // advance through list } } // resort the list if needed for(;;) { int changed=0; step = &active; while (*step && (*step)->next) { if ((*step)->x > (*step)->next->x) { stbtt__active_edge *t = *step; stbtt__active_edge *q = t->next; t->next = q->next; q->next = t; *step = q; changed = 1; } step = &(*step)->next; } if (!changed) break; } // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline while (e->y0 <= scan_y) { if (e->y1 > scan_y) { stbtt__active_edge *z = new_active(e, off_x, scan_y, userdata); // find insertion point if (active == NULL) active = z; else if (z->x < active->x) { // insert at front z->next = active; active = z; } else { // find thing to insert AFTER stbtt__active_edge *p = active; while (p->next && p->next->x < z->x) p = p->next; // at this point, p->next->x is NOT < z->x z->next = p->next; p->next = z; } } ++e; } // now process all active edges in XOR fashion if (active) stbtt__fill_active_edges(scanline, result->w, active, max_weight); ++y; } STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); ++j; } while (active) { stbtt__active_edge *z = active; active = active->next; STBTT_free(z, userdata); } if (scanline != scanline_data) STBTT_free(scanline, userdata); } static int stbtt__edge_compare(const void *p, const void *q) { stbtt__edge *a = (stbtt__edge *) p; stbtt__edge *b = (stbtt__edge *) q; if (a->y0 < b->y0) return -1; if (a->y0 > b->y0) return 1; return 0; } typedef struct { float x,y; } stbtt__point; static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) { float y_scale_inv = invert ? -scale_y : scale_y; stbtt__edge *e; int n,i,j,k,m; int vsubsample = result->h < 8 ? 15 : 5; // vsubsample should divide 255 evenly; otherwise we won't reach full opacity // now we have to blow out the windings into explicit edge lists n = 0; for (i=0; i < windings; ++i) n += wcount[i]; e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel if (e == 0) return; n = 0; m=0; for (i=0; i < windings; ++i) { stbtt__point *p = pts + m; m += wcount[i]; j = wcount[i]-1; for (k=0; k < wcount[i]; j=k++) { int a=k,b=j; // skip the edge if horizontal if (p[j].y == p[k].y) continue; // add edge from j to k to the list e[n].invert = 0; if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { e[n].invert = 1; a=j,b=k; } e[n].x0 = p[a].x * scale_x + shift_x; e[n].y0 = p[a].y * y_scale_inv * vsubsample + shift_y; e[n].x1 = p[b].x * scale_x + shift_x; e[n].y1 = p[b].y * y_scale_inv * vsubsample + shift_y; ++n; } } // now sort the edges by their highest point (should snap to integer, and then by x) STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); STBTT_free(e, userdata); } static void stbtt__add_point(stbtt__point *points, int n, float x, float y) { if (!points) return; // during first pass, it's unallocated points[n].x = x; points[n].y = y; } // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) { // midpoint float mx = (x0 + 2*x1 + x2)/4; float my = (y0 + 2*y1 + y2)/4; // versus directly drawn line float dx = (x0+x2)/2 - mx; float dy = (y0+y2)/2 - my; if (n > 16) // 65536 segments on one curve better be enough! return 1; if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); } else { stbtt__add_point(points, *num_points,x2,y2); *num_points = *num_points+1; } return 1; } // returns number of contours stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) { stbtt__point *points=0; int num_points=0; float objspace_flatness_squared = objspace_flatness * objspace_flatness; int i,n=0,start=0, pass; // count how many "moves" there are to get the contour count for (i=0; i < num_verts; ++i) if (vertices[i].type == STBTT_vmove) ++n; *num_contours = n; if (n == 0) return 0; *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); if (*contour_lengths == 0) { *num_contours = 0; return 0; } // make two passes through the points so we don't need to realloc for (pass=0; pass < 2; ++pass) { float x=0,y=0; if (pass == 1) { points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); if (points == NULL) goto error; } num_points = 0; n= -1; for (i=0; i < num_verts; ++i) { switch (vertices[i].type) { case STBTT_vmove: // start the next contour if (n >= 0) (*contour_lengths)[n] = num_points - start; ++n; start = num_points; x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x,y); break; case STBTT_vline: x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x, y); break; case STBTT_vcurve: stbtt__tesselate_curve(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; } } (*contour_lengths)[n] = num_points - start; } return points; error: STBTT_free(points, userdata); STBTT_free(*contour_lengths, userdata); *contour_lengths = 0; *num_contours = 0; return NULL; } void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) { float scale = scale_x > scale_y ? scale_y : scale_x; int winding_count, *winding_lengths; stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); if (windings) { stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); STBTT_free(winding_lengths, userdata); STBTT_free(windings, userdata); } } void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) { STBTT_free(bitmap, userdata); } unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) { int ix0,iy0,ix1,iy1; stbtt__bitmap gbm; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { if (scale_x == 0) return NULL; scale_y = scale_x; } stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); // now we get the size gbm.w = (ix1 - ix0); gbm.h = (iy1 - iy0); gbm.pixels = NULL; // in case we error if (width ) *width = gbm.w; if (height) *height = gbm.h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; if (gbm.w && gbm.h) { gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); if (gbm.pixels) { gbm.stride = gbm.w; stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); } } STBTT_free(vertices, info->userdata); return gbm.pixels; } unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); } void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) { int ix0,iy0; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); stbtt__bitmap gbm; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); gbm.pixels = output; gbm.w = out_w; gbm.h = out_h; gbm.stride = out_stride; if (gbm.w && gbm.h) stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); STBTT_free(vertices, info->userdata); } void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); } unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); } void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); } unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); } void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) { stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); } ////////////////////////////////////////////////////////////////////////////// // // bitmap baking // // This is SUPER-CRAPPY packing to keep source code small extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata) { float scale; int x,y,bottom_y, i; stbtt_fontinfo f; stbtt_InitFont(&f, data, offset); STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels x=y=1; bottom_y = 1; scale = stbtt_ScaleForPixelHeight(&f, pixel_height); for (i=0; i < num_chars; ++i) { int advance, lsb, x0,y0,x1,y1,gw,gh; int g = stbtt_FindGlyphIndex(&f, first_char + i); stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); gw = x1-x0; gh = y1-y0; if (x + gw + 1 >= pw) y = bottom_y, x = 1; // advance to next row if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row return -i; STBTT_assert(x+gw < pw); STBTT_assert(y+gh < ph); stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); chardata[i].x0 = (stbtt_int16) x; chardata[i].y0 = (stbtt_int16) y; chardata[i].x1 = (stbtt_int16) (x + gw); chardata[i].y1 = (stbtt_int16) (y + gh); chardata[i].xadvance = scale * advance; chardata[i].xoff = (float) x0; chardata[i].yoff = (float) y0; x = x + gw + 2; if (y+gh+2 > bottom_y) bottom_y = y+gh+2; } return bottom_y; } void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) { float d3d_bias = opengl_fillrule ? 0 : -0.5f; float ipw = 1.0f / pw, iph = 1.0f / ph; stbtt_bakedchar *b = chardata + char_index; int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5); int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5); q->x0 = round_x + d3d_bias; q->y0 = round_y + d3d_bias; q->x1 = round_x + b->x1 - b->x0 + d3d_bias; q->y1 = round_y + b->y1 - b->y0 + d3d_bias; q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } ////////////////////////////////////////////////////////////////////////////// // // font name matching -- recommended not to use this // // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 *s1, stbtt_int32 len1, const stbtt_uint8 *s2, stbtt_int32 len2) { stbtt_int32 i=0; // convert utf16 to utf8 and compare the results while converting while (len2) { stbtt_uint16 ch = s2[0]*256 + s2[1]; if (ch < 0x80) { if (i >= len1) return -1; if (s1[i++] != ch) return -1; } else if (ch < 0x800) { if (i+1 >= len1) return -1; if (s1[i++] != 0xc0 + (ch >> 6)) return -1; if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; } else if (ch >= 0xd800 && ch < 0xdc00) { stbtt_uint32 c; stbtt_uint16 ch2 = s2[2]*256 + s2[3]; if (i+3 >= len1) return -1; c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; if (s1[i++] != 0xf0 + (c >> 18)) return -1; if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; s2 += 2; // plus another 2 below len2 -= 2; } else if (ch >= 0xdc00 && ch < 0xe000) { return -1; } else { if (i+2 >= len1) return -1; if (s1[i++] != 0xe0 + (ch >> 12)) return -1; if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; } s2 += 2; len2 -= 2; } return i; } int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) { return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const stbtt_uint8*) s2, len2); } // returns results in whatever encoding you request... but note that 2-byte encodings // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) { stbtt_int32 i,count,stringOffset; stbtt_uint8 *fc = font->data; stbtt_uint32 offset = font->fontstart; stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); if (!nm) return NULL; count = ttUSHORT(fc+nm+2); stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { *length = ttUSHORT(fc+loc+8); return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); } } return NULL; } static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) { stbtt_int32 i; stbtt_int32 count = ttUSHORT(fc+nm+2); stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; stbtt_int32 id = ttUSHORT(fc+loc+6); if (id == target_id) { // find the encoding stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); // is this a Unicode encoding? if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { stbtt_int32 slen = ttUSHORT(fc+loc+8); stbtt_int32 off = ttUSHORT(fc+loc+10); // check if there's a prefix match stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); if (matchlen >= 0) { // check for target_id+1 immediately following, with same encoding & language if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { slen = ttUSHORT(fc+loc+12+8); off = ttUSHORT(fc+loc+12+10); if (slen == 0) { if (matchlen == nlen) return 1; } else if (matchlen < nlen && name[matchlen] == ' ') { ++matchlen; if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) return 1; } } else { // if nothing immediately following if (matchlen == nlen) return 1; } } } // @TODO handle other encodings } } return 0; } static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) { stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); stbtt_uint32 nm,hd; if (!stbtt__isfont(fc+offset)) return 0; // check italics/bold/underline flags in macStyle... if (flags) { hd = stbtt__find_table(fc, offset, "head"); if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; } nm = stbtt__find_table(fc, offset, "name"); if (!nm) return 0; if (flags) { // if we checked the macStyle flags, then just check the family and ignore the subfamily if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } else { if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } return 0; } int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags) { stbtt_int32 i; for (i=0;;++i) { stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); if (off < 0) return off; if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) return off; } } #endif // STB_TRUETYPE_IMPLEMENTATION
the_stack_data/389323.c
#include <stdio.h> #include <stdlib.h> #define min(a,b) (((a)<(b))?(a):(b)) #define max(a,b) (((a)>(b))?(a):(b)) #define TEXT_BLOCK_SIZE 32 #define EDIT_BLOCK_SIZE 8 #define CHANGE 'c' #define PRINT 'p' #define DELETE 'd' #define QUIT 'q' #define UNDO 'u' #define REDO 'r' #define SKIP 0 /* ===================================================================== */ /* typedefs */ typedef struct edit{ char code; int location, size, setlen, fill; char **lines; }edit_t; typedef struct state{ edit_t *undo, *redo; }state_t; /* ===================================================================== */ /* Function declarations */ void AdjustCapacity(int required_lines); void SetTextCapacity(int capacity); void SetTextLength(int length); void SetLine(int location, char **content); void UpdateHistory(); void FreeStateContent(int index); edit_t *GetStateEdit(char which); void SetupEdit(edit_t *e, char code, int loc, int setl, int size); void AddLineToEdit(edit_t *e, char **lineContent); void OnQuit(); void OnPrint(int from, int to); void OnChange(int from, int to); void OnDelete(int from, int to); void OnUndo(int steps); void OnRedo(int steps); void QueueUndos(int amount); void QueueRedos(int amount); void RestoreEdits(); void TryRestoreState(); /* ===================================================================== */ /* Globals */ char **text; // Text container int t_cap = 0; // Text capacity int t_len = 0; // Text length char *in_buf = NULL; // Buffer for all things input size_t in_size = 0; // Size of the buffer ssize_t in_len = 0; // Length of the input line char status = 0; // Program status (aka what action is being performed) state_t *history; // Edit timeline int h_cap = 0; // Allocated blocks int stateCount = 0; // Max time int currentState = 0; // Current time int actions_to_restore = 0; // Undo/Redo queue char **rightMost = NULL; // Most recent copy of the whole text before any undos are performed int rm_len = 0; // # of lines in the rightmost state int rm_state = 0; // what state is it? /* ===================================================================== */ /* Main */ int main(int argc, char* argv[]){ // Init text SetTextCapacity(TEXT_BLOCK_SIZE); // Init history (count = 1, current = 0) UpdateHistory(); int arg1, arg2; while(status != QUIT){ // Get input in_buf = NULL; in_len = getline(&in_buf, &in_size, stdin); // Execute input switch (status = in_buf[in_len - 2]){ case PRINT: RestoreEdits(); sscanf(in_buf, "%d,%dp", &arg1, &arg2); OnPrint(arg1, arg2); break; case CHANGE: RestoreEdits(); sscanf(in_buf, "%d,%dc", &arg1, &arg2); OnChange(arg1, arg2); break; case DELETE: RestoreEdits(); sscanf(in_buf, "%d,%dd", &arg1, &arg2); OnDelete(arg1, arg2); break; case UNDO: sscanf(in_buf, "%du", &arg1); QueueUndos(arg1); break; case REDO: sscanf(in_buf, "%dr", &arg1); QueueRedos(arg1); break; } } return 0; } /* ===================================================================== */ /* Text support */ void SetTextCapacity(int capacity){ t_cap = capacity; text = (char**)realloc(text, t_cap * sizeof(char*)); } void AdjustTextCapacity(int required_lines) { int capacity = t_cap; if(required_lines < capacity) { // Decrease capacity to trim out any non required text space while(capacity - TEXT_BLOCK_SIZE >= required_lines) capacity -= TEXT_BLOCK_SIZE; } else { // Increase capacity to fit the required text size while(required_lines > capacity) capacity += TEXT_BLOCK_SIZE; } SetTextCapacity(capacity); } void SetTextLength(int length){ t_len = length; AdjustTextCapacity(t_len); } void SetLine(int location, char** content){ text[location-1] = (*content); } /* ===================================================================== */ /* History support */ void UpdateHistory(){ // Making changes in the present if(stateCount == 0 || currentState == stateCount-1){ // Increase count by one state and reallocate memory stateCount++; } // Making changes in the past else { // Deallocate old states for(int i = currentState + 1; i < stateCount; i++){ FreeStateContent(i); } // Set new size and reallocate stateCount = currentState + 2; } int capacity = h_cap; while(stateCount >= capacity) capacity += EDIT_BLOCK_SIZE; while(stateCount < capacity - EDIT_BLOCK_SIZE) capacity -= EDIT_BLOCK_SIZE; // Resize history space if(capacity != h_cap) history = (state_t*)realloc(history, capacity * sizeof(state_t)); // Initialize new state history[stateCount - 1].undo = NULL; history[stateCount - 1].redo = NULL; h_cap = capacity; } void FreeStateContent(int index){ edit_t *e = history[index].undo; if(e != NULL){ free(e); history[index].undo = NULL; } e = history[index].redo; if(e != NULL){ free(e); history[index].redo = NULL; } } edit_t* GetStateEdit(char which){ if(which == UNDO){ // If empty, generate (could do realloc/calloc but is it necessary?) if(history[currentState + 1].undo == NULL) { history[currentState + 1].undo = (edit_t*)malloc(sizeof(edit_t)); history[currentState + 1].undo->code = 0; history[currentState + 1].undo->location = 0; history[currentState + 1].undo->size = 0; history[currentState + 1].undo->setlen = 0; history[currentState + 1].undo->lines = NULL; } return history[currentState+1].undo; } // If empty, generate (could do realloc/calloc but is it necessary?) if(history[currentState].redo == NULL){ history[currentState].redo = (edit_t*)malloc(sizeof(edit_t)); history[currentState].redo->code = 0; history[currentState].redo->location = 0; history[currentState].redo->size = 0; history[currentState].redo->setlen = 0; history[currentState].redo->lines = NULL; } return history[currentState].redo; } void SetupEdit(edit_t *e, char code, int loc, int setl, int size){ e->code = code; e->location = loc; e->setlen = setl; e->size = size; e->fill = 0; e->lines = NULL; e->lines = (char**)realloc(e->lines, size * sizeof(char*)); } void AddLineToEdit(edit_t *e, char **lineContent){ // Add line to edit and increase counter e->lines[e->fill] = (*lineContent); e->fill++; } /* ===================================================================== */ /* Command events */ void OnPrint(int from, int to){ // Prind valid lines, replace invalid ones with '.' for(int i = from; i <= to; i++){ if(i > 0 && i <= t_len) printf("%s", text[i-1]); else printf(".\n"); } } void OnChange(int from, int to){ int prevLen = t_len; // Expand/Trim text to fit SetTextLength(max(to, prevLen)); UpdateHistory(); // count = current + 2, current+1 is the undo's state edit_t *undo = GetStateEdit(UNDO); SetupEdit(undo, CHANGE, from, prevLen, to - from + 1); edit_t *redo = GetStateEdit(REDO); SetupEdit(redo, CHANGE, from, t_len, to - from + 1); for(int i = from; i <= to; i++){ // Get input in_buf = NULL; in_len = getline(&in_buf, &in_size, stdin); // If line is being overwritten if(i <= prevLen) { AddLineToEdit(undo, &text[i-1]); } SetLine(i, &in_buf); AddLineToEdit(redo, &in_buf); } currentState++; rm_state = 0; } void OnDelete(int from, int to){ if(from > t_len || to < 1) { UpdateHistory(); edit_t *undo = GetStateEdit(UNDO); SetupEdit(undo, SKIP, 0, 0, 0); edit_t *redo = GetStateEdit(REDO); SetupEdit(redo, SKIP, 0, 0, 0); currentState++; return; } int lastToRemove = min(to, t_len); int offset = lastToRemove - from + 1; UpdateHistory(); edit_t *undo = GetStateEdit(UNDO); SetupEdit(undo, DELETE, from, t_len, offset); edit_t *redo = GetStateEdit(REDO); SetupEdit(redo, DELETE, from, t_len-offset, offset); int cursor = from - 1; while(cursor < t_len){ if(cursor < lastToRemove){ AddLineToEdit(undo, &text[cursor]); } if(cursor + offset < t_len){ text[cursor] = text[cursor+offset]; text[cursor + offset] = NULL; } cursor++; } SetTextLength(t_len-offset); currentState++; rm_state = 0; } void OnUndo(int steps){ if(currentState == stateCount - 1){ rightMost = (char**)realloc(rightMost, t_cap * sizeof(char*)); rm_len = t_len; rm_state = currentState; for(int i = 0; i < rm_len; i++) rightMost[i] = text[i]; } edit_t *undo; while(currentState > 0 && steps > 0){ undo = history[currentState].undo; switch (undo->code){ case CHANGE: /* Undo Change ------------------ */ { SetTextLength(undo->setlen); for(int i = 0; i < undo->fill; i++){ SetLine(undo->location + i, &undo->lines[i]); } } break; case DELETE: /* Undo Delete (do insert) ------ */ { SetTextLength(undo->setlen); int cursor = t_len; while(cursor >= undo->location){ // Inserting at the end if(t_len - undo->fill == undo->location - 1){ SetLine(cursor, &undo->lines[cursor-undo->location]); } // Inserting in the middle else { if(cursor-undo->fill > 0) text[cursor - 1] = text[cursor-undo->fill - 1]; if(cursor <= undo->location + undo->fill - 1) SetLine(cursor, &undo->lines[cursor-undo->location]); } cursor--; } } break; } steps--; currentState--; } } void OnRedo(int steps){ edit_t *redo; while(currentState < stateCount - 1 && steps > 0){ redo = history[currentState].redo; switch (redo->code){ case CHANGE: /* Redo Change ------------------ */ { SetTextLength(redo->setlen); for(int i = 0; i < redo->fill; i++){ SetLine(redo->location + i, &redo->lines[i]); } } break; case DELETE: /* Redo Delete ------------------ */ { int cursor = redo->location - 1; while(cursor < t_len){ if(cursor + redo->size < t_len){ text[cursor] = text[cursor+redo->size]; text[cursor + redo->size] = NULL; } cursor++; } SetTextLength(redo->setlen); } break; } steps--; currentState++; } } void QueueUndos(int amount){ actions_to_restore -= amount; if(currentState + actions_to_restore < 0) actions_to_restore = -currentState; } void QueueRedos(int amount){ actions_to_restore += amount; if(actions_to_restore + currentState > stateCount - 1) actions_to_restore = stateCount - 1 - currentState; } void RestoreEdits(){ if(actions_to_restore == 0) return; TryRestoreState(); if(actions_to_restore > 0) OnRedo(actions_to_restore); else if(actions_to_restore < 0) OnUndo(-actions_to_restore); actions_to_restore = 0; } void TryRestoreState(){ // Calculate target state int target = currentState+actions_to_restore; // Check if 0 or the rm state are closer to the target if (actions_to_restore < 0 && target < -actions_to_restore){ actions_to_restore = target; SetTextLength(0); currentState = 0; } else if(actions_to_restore > 0 && rm_state > 0){ if(abs(target-rm_state)<actions_to_restore) { SetTextLength(rm_len); currentState = rm_state; for(int i = 0; i < rm_len; i++) text[i] = rightMost[i]; actions_to_restore = target-rm_state; } } } // Ōdī et amō. Quārē id faciam fortasse requīris. // Nesciō, sed fierī sentiō et excrucior.
the_stack_data/22012884.c
/* * Copyright (c) 2013, 2014 Jan-Piet Mens <[email protected]> * 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 mosquitto * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifdef BE_MYSQL #include <stdio.h> #include <stdlib.h> #include <string.h> #include <mosquitto.h> #include "be-mysql.h" #include "log.h" #include "hash.h" #include "backends.h" struct mysql_backend { MYSQL *mysql; char *host; int port; char *dbname; char *user; char *pass; bool auto_connect; char *userquery; //MUST return 1 row, 1 column char *superquery; //MUST return 1 row, 1 column,[0, 1] char *aclquery; //MAY return n rows, 1 column, string }; static char *get_bool(char *option, char *defval) { char *flag = p_stab(option); flag = flag ? flag : defval; if (!strcmp("true", flag) || !strcmp("false", flag)) { return flag; } _log(LOG_NOTICE, "WARN: %s is unexpected value -> %s", option, flag); return defval; } void *be_mysql_init() { struct mysql_backend *conf; char *host, *user, *pass, *dbname, *p; char *ssl_ca, *ssl_capath, *ssl_cert, *ssl_cipher, *ssl_key; char *userquery; char *opt_flag; int port; bool ssl_enabled; #if (defined(MYSQL_VERSION_ID)) && (MYSQL_VERSION_ID > 50012) int reconnect = false; #else my_bool reconnect = false; #endif _log(LOG_DEBUG, "}}}} MYSQL"); host = p_stab("host"); p = p_stab("port"); user = p_stab("user"); pass = p_stab("pass"); dbname = p_stab("dbname"); opt_flag = get_bool("ssl_enabled", "false"); if (!strcmp("true", opt_flag)) { ssl_enabled = true; _log(LOG_DEBUG, "SSL is enabled"); } else{ ssl_enabled = false; _log(LOG_DEBUG, "SSL is disabled"); } ssl_key = p_stab("ssl_key"); ssl_cert = p_stab("ssl_cert"); ssl_ca = p_stab("ssl_ca"); ssl_capath = p_stab("ssl_capath"); ssl_cipher = p_stab("ssl_cipher"); host = (host) ? host : strdup("localhost"); port = (!p) ? 3306 : atoi(p); userquery = p_stab("userquery"); if (!userquery) { _fatal("Mandatory option 'userquery' is missing"); return (NULL); } if ((conf = (struct mysql_backend *)malloc(sizeof(struct mysql_backend))) == NULL) return (NULL); conf->mysql = mysql_init(NULL); conf->host = host; conf->port = port; conf->user = user; conf->pass = pass; conf->auto_connect = false; conf->dbname = dbname; conf->userquery = userquery; conf->superquery = p_stab("superquery"); conf->aclquery = p_stab("aclquery"); if(ssl_enabled){ mysql_ssl_set(conf->mysql, ssl_key, ssl_cert, ssl_ca, ssl_capath, ssl_cipher); } opt_flag = get_bool("mysql_auto_connect", "true"); if (!strcmp("true", opt_flag)) { conf->auto_connect = true; } opt_flag = get_bool("mysql_opt_reconnect", "true"); if (!strcmp("true", opt_flag)) { reconnect = true; mysql_options(conf->mysql, MYSQL_OPT_RECONNECT, &reconnect); } if (!mysql_real_connect(conf->mysql, host, user, pass, dbname, port, NULL, 0)) { _log(LOG_NOTICE, "%s", mysql_error(conf->mysql)); if (!conf->auto_connect && !reconnect) { free(conf); mysql_close(conf->mysql); return (NULL); } } return ((void *)conf); } void be_mysql_destroy(void *handle) { struct mysql_backend *conf = (struct mysql_backend *)handle; if (conf) { mysql_close(conf->mysql); if (conf->userquery) free(conf->userquery); if (conf->superquery) free(conf->superquery); if (conf->aclquery) free(conf->aclquery); free(conf); } } static char *escape(void *handle, const char *value, long *vlen) { struct mysql_backend *conf = (struct mysql_backend *)handle; char *v; *vlen = strlen(value) * 2 + 1; if ((v = malloc(*vlen)) == NULL) return (NULL); mysql_real_escape_string(conf->mysql, v, value, strlen(value)); return (v); } static bool auto_connect(struct mysql_backend *conf) { if (conf->auto_connect) { if (!mysql_real_connect(conf->mysql, conf->host, conf->user, conf->pass, conf->dbname, conf->port, NULL, 0)) { fprintf(stderr, "do auto_connect but %s\n", mysql_error(conf->mysql)); return false; } return true; } return false; } int be_mysql_getuser(void *handle, const char *username, const char *password, char **phash, const char *clientid) { struct mysql_backend *conf = (struct mysql_backend *)handle; char *query = NULL, *u = NULL, *value = NULL, *v; long nrows, ulen; MYSQL_RES *res = NULL; MYSQL_ROW rowdata; // fprintf(stderr, "------>%s<-----\n", clientid); if (!conf || !conf->userquery || !username || !*username) return BACKEND_DEFER; if (mysql_ping(conf->mysql)) { fprintf(stderr, "%s\n", mysql_error(conf->mysql)); if (!auto_connect(conf)) { return BACKEND_ERROR; } } if ((u = escape(conf, username, &ulen)) == NULL) return BACKEND_ERROR; if ((query = malloc(strlen(conf->userquery) + ulen + 128)) == NULL) { free(u); return BACKEND_ERROR; } sprintf(query, conf->userquery, u, clientid); free(u); if (mysql_query(conf->mysql, query)) { fprintf(stderr, "%s\n", mysql_error(conf->mysql)); goto out; } res = mysql_store_result(conf->mysql); if ((nrows = mysql_num_rows(res)) != 1) { //DEBUG fprintf(stderr, "rowcount = %ld; not ok\n", nrows); goto out; } if (mysql_num_fields(res) != 1) { //DEBUG fprintf(stderr, "numfields not ok\n"); goto out; } if ((rowdata = mysql_fetch_row(res)) == NULL) { goto out; } v = rowdata[0]; value = (v) ? strdup(v) : NULL; out: mysql_free_result(res); free(query); *phash = value; return BACKEND_DEFER; } /* * Return T/F if user is superuser */ int be_mysql_superuser(void *handle, const char *username) { struct mysql_backend *conf = (struct mysql_backend *)handle; char *query = NULL, *u = NULL; long nrows, ulen; int issuper = BACKEND_DEFER; MYSQL_RES *res = NULL; MYSQL_ROW rowdata; if (!conf || !conf->superquery) return BACKEND_DEFER; if (mysql_ping(conf->mysql)) { fprintf(stderr, "%s\n", mysql_error(conf->mysql)); if (!auto_connect(conf)) { return (BACKEND_ERROR); } } if ((u = escape(conf, username, &ulen)) == NULL) return (BACKEND_ERROR); if ((query = malloc(strlen(conf->superquery) + ulen + 128)) == NULL) { free(u); return (BACKEND_ERROR); } sprintf(query, conf->superquery, u); free(u); if (mysql_query(conf->mysql, query)) { fprintf(stderr, "%s\n", mysql_error(conf->mysql)); issuper = BACKEND_ERROR; goto out; } res = mysql_store_result(conf->mysql); if ((nrows = mysql_num_rows(res)) != 1) { goto out; } if (mysql_num_fields(res) != 1) { //DEBUG fprintf(stderr, "numfields not ok\n"); goto out; } if ((rowdata = mysql_fetch_row(res)) == NULL) { goto out; } issuper = (atoi(rowdata[0])) ? BACKEND_ALLOW: BACKEND_DEFER; out: mysql_free_result(res); free(query); return (issuper); } /* * Check ACL. username is the name of the connected user attempting to access * topic is the topic user is trying to access (may contain wildcards) acc is * desired type of access: read/write for subscriptions (READ) (1) for * publish (WRITE) (2) * * SELECT topic FROM table WHERE username = '%s' AND (acc & %d) // * may user SUB or PUB topic? SELECT topic FROM table WHERE username = '%s' * / ignore ACC */ int be_mysql_aclcheck(void *handle, const char *clientid, const char *username, const char *topic, int acc) { struct mysql_backend *conf = (struct mysql_backend *)handle; char *query = NULL, *u = NULL, *v; long ulen; int match = BACKEND_DEFER; bool bf; MYSQL_RES *res = NULL; MYSQL_ROW rowdata; if (!conf || !conf->aclquery) return BACKEND_DEFER; if (mysql_ping(conf->mysql)) { fprintf(stderr, "%s\n", mysql_error(conf->mysql)); if (!auto_connect(conf)) { return (BACKEND_ERROR); } } if ((u = escape(conf, username, &ulen)) == NULL) return (BACKEND_ERROR); if ((query = malloc(strlen(conf->aclquery) + ulen + 128)) == NULL) { free(u); return (BACKEND_ERROR); } sprintf(query, conf->aclquery, u, acc); free(u); //_log(LOG_DEBUG, "SQL: %s", query); if (mysql_query(conf->mysql, query)) { _log(LOG_NOTICE, "%s", mysql_error(conf->mysql)); match = BACKEND_ERROR; goto out; } res = mysql_store_result(conf->mysql); if (mysql_num_fields(res) != 1) { fprintf(stderr, "numfields not ok\n"); goto out; } while (match == 0 && (rowdata = mysql_fetch_row(res)) != NULL) { if ((v = rowdata[0]) != NULL) { /* * Check mosquitto_match_topic. If true, if true, set * match and break out of loop. */ char *expanded; t_expand(clientid, username, v, &expanded); if (expanded && *expanded) { mosquitto_topic_matches_sub(expanded, topic, &bf); if (bf) match = BACKEND_ALLOW; _log(LOG_DEBUG, " mysql: topic_matches(%s, %s) == %d", expanded, v, bf); free(expanded); } } } out: mysql_free_result(res); free(query); return (match); } #endif /* BE_MYSQL */
the_stack_data/234518468.c
int main() { int i, j, rows; printf("Enter number of rows: "); scanf("%d",&rows); for(i=1; i<=rows; ++i) { for(j=1; j<=i; ++j) { printf("* "); } printf("\n"); } return 0; }
the_stack_data/91888.c
#define _GNU_SOURCE #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char* argv[]) { if (argc != 3) { fprintf(stderr, "usage: %s ip port\n", argv[0]); exit(-1); } const char* ip = argv[1]; int port = atoi(argv[2]); int sockfd; if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "create socket fd failed, msg: %s\n", strerror(errno)); exit(-1); } int reuse = 1; setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); struct sockaddr_in addr; bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); inet_pton(AF_INET, ip, &addr.sin_addr); if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { fprintf(stderr, "bind failed, msg: %s\n", strerror(errno)); close(sockfd); exit(-1); } if ((listen(sockfd, 5)) == -1) { fprintf(stderr, "listen failed, msg: %s\n", strerror(errno)); close(sockfd); exit(-1); } for (;;) { printf("waiting for connection\n"); struct sockaddr_in client; socklen_t client_addr_length = sizeof(client); int connfd; if ((connfd = accept(sockfd, (struct sockaddr*)&client, &client_addr_length)) < 0) { fprintf(stderr, "accept failed, msg: %s\n", strerror(errno)); close(sockfd); exit(-1); } printf("accepted connection\n"); int pipefd[2]; if (pipe(pipefd) == -1) { fprintf(stderr, "pipe fd failed, msg: %s\n", strerror(errno)); close(sockfd); close(connfd); exit(-1); } int n; for (;;) { if ((n = splice(connfd, NULL, pipefd[1], NULL, 32768, SPLICE_F_MOVE | SPLICE_F_MORE)) == -1) { fprintf(stderr, "splice connfd failed, msg: %s\n", strerror(errno)); close(connfd); close(sockfd); exit(-1); } fprintf(stderr, "recv %d bytes\n", n); if (n == 0) { break; } if (splice(pipefd[0], NULL, connfd, NULL, 32768, SPLICE_F_MOVE | SPLICE_F_MORE) == -1) { fprintf(stderr, "splice out fd failed, msg: %s\n", strerror(errno)); close(connfd); close(sockfd); exit(-1); } } close(connfd); printf("connection closed\n"); } close(sockfd); printf("program exited\n"); exit(0); }
the_stack_data/57900.c
/**/ #include<stdio.h> int main(){ double a,b,c,d,score; printf("Enter thresholds for A, B, C, D \nin that order, decreasing percentages > "); scanf("%lf %lf %lf %lf",&a,&b,&c,&d); printf("Thank you. Now enter student score (percent) >"); scanf("%lf", &score); if (score >= a){ printf("Student has an A grade\n"); } else if ((score >= b) && (score > a)){ printf("Student has an B grade\n"); } else if ((score >= c) && (score < b)){ printf("Student has an C grade\n"); } else if ( (score >= d) && (score < c)){ printf("Student has an D grade\n"); } else if (score < d){ printf("Student has failed the course\n"); } return 0; }
the_stack_data/103265259.c
const char venice[] = "\ \n\ Project Gutenberg Etext of The Merchant of Venice by Shakespeare\n\ PG has multiple editions of William Shakespeare\'s Complete Works\n\ \n\ \n\ Copyright laws are changing all over the world, be sure to check\n\ the copyright laws for your country before posting these files!!\n\ \n\ Please take a look at the important information in this header.\n\ We encourage you to keep this file on your own disk, keeping an\n\ electronic path open for the next readers. Do not remove this.\n\ \n\ \n\ **Welcome To The World of Free Plain Vanilla Electronic Texts**\n\ \n\ **Etexts Readable By Both Humans and By Computers, Since 1971**\n\ \n\ *These Etexts Prepared By Hundreds of Volunteers and Donations*\n\ \n\ Information on contacting Project Gutenberg to get Etexts, and\n\ further information is included below. We need your donations.\n\ \n\ \n\ The Merchant of Venice\n\ \n\ by William Shakespeare [Craig, Oxford edition]\n\ \n\ November, 1998 [Etext #1515]\n\ \n\ \n\ Project Gutenberg Etext of The Merchant of Venice by Shakespeare\n\ ******This file should be named 2ws1810.txt or 2ws1810.zip******\n\ \n\ Corrected EDITIONS of our etexts get a new NUMBER, 2ws1811.txt\n\ VERSIONS based on separate sources get new LETTER, 2ws1810a.txt\n\ \n\ \n\ This etext was prepared by the PG Shakespeare Team,\n\ a team of about twenty Project Gutenberg volunteers.\n\ \n\ \n\ Project Gutenberg Etexts are usually created from multiple editions,\n\ all of which are in the Public Domain in the United States, unless a\n\ copyright notice is included. Therefore, we usually do NOT! keep\n\ these books in compliance with any particular paper edition.\n\ \n\ \n\ We are now trying to release all our books one month in advance\n\ of the official release dates, leaving time for better editing.\n\ \n\ Please note: neither this list nor its contents are final till\n\ midnight of the last day of the month of any such announcement.\n\ The official release date of all Project Gutenberg Etexts is at\n\ Midnight, Central Time, of the last day of the stated month. A\n\ preliminary version may often be posted for suggestion, comment\n\ and editing by those who wish to do so. To be sure you have an\n\ up to date first edition [xxxxx10x.xxx] please check file sizes\n\ in the first week of the next month. Since our ftp program has\n\ a bug in it that scrambles the date [tried to fix and failed] a\n\ look at the file size will have to do, but we will try to see a\n\ new copy has at least one byte more or less.\n\ \n\ \n\ Information about Project Gutenberg (one page)\n\ \n\ We produce about two million dollars for each hour we work. The\n\ time it takes us, a rather conservative estimate, is fifty hours\n\ to get any etext selected, entered, proofread, edited, copyright\n\ searched and analyzed, the copyright letters written, etc. This\n\ projected audience is one hundred million readers. If our value\n\ per text is nominally estimated at one dollar then we produce $2\n\ million dollars per hour this year as we release thirty-six text\n\ files per month, or 432 more Etexts in 1999 for a total of 2000+\n\ If these reach just 10% of the computerized population, then the\n\ total should reach over 200 billion Etexts given away this year.\n\ \n\ The Goal of Project Gutenberg is to Give Away One Trillion Etext\n\ Files by December 31, 2001. [10,000 x 100,000,000 = 1 Trillion]\n\ This is ten thousand titles each to one hundred million readers,\n\ which is only ~5% of the present number of computer users.\n\ \n\ At our revised rates of production, we will reach only one-third\n\ of that goal by the end of 2001, or about 3,333 Etexts unless we\n\ manage to get some real funding; currently our funding is mostly\n\ from Michael Hart\'s salary at Carnegie-Mellon University, and an\n\ assortment of sporadic gifts; this salary is only good for a few\n\ more years, so we are looking for something to replace it, as we\n\ don\'t want Project Gutenberg to be so dependent on one person.\n\ \n\ We need your donations more than ever!\n\ \n\ \n\ All donations should be made to \"Project Gutenberg/CMU\": and are\n\ tax deductible to the extent allowable by law. (CMU = Carnegie-\n\ Mellon University).\n\ \n\ For these and other matters, please mail to:\n\ \n\ Project Gutenberg\n\ P. O. Box 2782\n\ Champaign, IL 61825\n\ \n\ When all other email fails. . .try our Executive Director:\n\ Michael S. Hart <[email protected]>\n\ [email protected] forwards to [email protected] and archive.org\n\ if your mail bounces from archive.org, I will still see it, if\n\ it bounces from prairienet.org, better resend later on. . . .\n\ \n\ We would prefer to send you this information by email.\n\ \n\ ******\n\ \n\ To access Project Gutenberg etexts, use any Web browser\n\ to view http://promo.net/pg. This site lists Etexts by\n\ author and by title, and includes information about how\n\ to get involved with Project Gutenberg. You could also\n\ download our past Newsletters, or subscribe here. This\n\ is one of our major sites, please email [email protected],\n\ for a more complete list of our various sites.\n\ \n\ To go directly to the etext collections, use FTP or any\n\ Web browser to visit a Project Gutenberg mirror (mirror\n\ sites are available on 7 continents; mirrors are listed\n\ at http://promo.net/pg).\n\ \n\ Mac users, do NOT point and click, typing works better.\n\ \n\ Example FTP session:\n\ \n\ ftp sunsite.unc.edu\n\ login: anonymous\n\ password: your@login\n\ cd pub/docs/books/gutenberg\n\ cd etext90 through etext99\n\ dir [to see files]\n\ get or mget [to get files. . .set bin for zip files]\n\ GET GUTINDEX.?? [to get a year\'s listing of books, e.g., GUTINDEX.99]\n\ GET GUTINDEX.ALL [to get a listing of ALL books]\n\ \n\ ***\n\ \n\ **Information prepared by the Project Gutenberg legal advisor**\n\ \n\ (Three Pages)\n\ \n\ \n\ ***START**THE SMALL PRINT!**FOR PUBLIC DOMAIN ETEXTS**START***\n\ Why is this \"Small Print!\" statement here? You know: lawyers.\n\ They tell us you might sue us if there is something wrong with\n\ your copy of this etext, even if you got it for free from\n\ someone other than us, and even if what\'s wrong is not our\n\ fault. So, among other things, this \"Small Print!\" statement\n\ disclaims most of our liability to you. It also tells you how\n\ you can distribute copies of this etext if you want to.\n\ \n\ *BEFORE!* YOU USE OR READ THIS ETEXT\n\ By using or reading any part of this PROJECT GUTENBERG-tm\n\ etext, you indicate that you understand, agree to and accept\n\ this \"Small Print!\" statement. If you do not, you can receive\n\ a refund of the money (if any) you paid for this etext by\n\ sending a request within 30 days of receiving it to the person\n\ you got it from. If you received this etext on a physical\n\ medium (such as a disk), you must return it with your request.\n\ \n\ ABOUT PROJECT GUTENBERG-TM ETEXTS\n\ This PROJECT GUTENBERG-tm etext, like most PROJECT GUTENBERG-\n\ tm etexts, is a \"public domain\" work distributed by Professor\n\ Michael S. Hart through the Project Gutenberg Association at\n\ Carnegie-Mellon University (the \"Project\"). Among other\n\ things, this means that no one owns a United States copyright\n\ on or for this work, so the Project (and you!) can copy and\n\ distribute it in the United States without permission and\n\ without paying copyright royalties. Special rules, set forth\n\ below, apply if you wish to copy and distribute this etext\n\ under the Project\'s \"PROJECT GUTENBERG\" trademark.\n\ \n\ To create these etexts, the Project expends considerable\n\ efforts to identify, transcribe and proofread public domain\n\ works. Despite these efforts, the Project\'s etexts and any\n\ medium they may be on may contain \"Defects\". Among other\n\ things, Defects may take the form of incomplete, inaccurate or\n\ corrupt data, transcription errors, a copyright or other\n\ intellectual property infringement, a defective or damaged\n\ disk or other etext medium, a computer virus, or computer\n\ codes that damage or cannot be read by your equipment.\n\ \n\ LIMITED WARRANTY; DISCLAIMER OF DAMAGES\n\ But for the \"Right of Replacement or Refund\" described below,\n\ [1] the Project (and any other party you may receive this\n\ etext from as a PROJECT GUTENBERG-tm etext) disclaims all\n\ liability to you for damages, costs and expenses, including\n\ legal fees, and [2] YOU HAVE NO REMEDIES FOR NEGLIGENCE OR\n\ UNDER STRICT LIABILITY, OR FOR BREACH OF WARRANTY OR CONTRACT,\n\ INCLUDING BUT NOT LIMITED TO INDIRECT, CONSEQUENTIAL, PUNITIVE\n\ OR INCIDENTAL DAMAGES, EVEN IF YOU GIVE NOTICE OF THE\n\ POSSIBILITY OF SUCH DAMAGES.\n\ \n\ If you discover a Defect in this etext within 90 days of\n\ receiving it, you can receive a refund of the money (if any)\n\ you paid for it by sending an explanatory note within that\n\ time to the person you received it from. If you received it\n\ on a physical medium, you must return it with your note, and\n\ such person may choose to alternatively give you a replacement\n\ copy. If you received it electronically, such person may\n\ choose to alternatively give you a second opportunity to\n\ receive it electronically.\n\ \n\ THIS ETEXT IS OTHERWISE PROVIDED TO YOU \"AS-IS\". NO OTHER\n\ WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, ARE MADE TO YOU AS\n\ TO THE ETEXT OR ANY MEDIUM IT MAY BE ON, INCLUDING BUT NOT\n\ LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A\n\ PARTICULAR PURPOSE.\n\ \n\ Some states do not allow disclaimers of implied warranties or\n\ the exclusion or limitation of consequential damages, so the\n\ above disclaimers and exclusions may not apply to you, and you\n\ may have other legal rights.\n\ \n\ INDEMNITY\n\ You will indemnify and hold the Project, its directors,\n\ officers, members and agents harmless from all liability, cost\n\ and expense, including legal fees, that arise directly or\n\ indirectly from any of the following that you do or cause:\n\ [1] distribution of this etext, [2] alteration, modification,\n\ or addition to the etext, or [3] any Defect.\n\ \n\ DISTRIBUTION UNDER \"PROJECT GUTENBERG-tm\"\n\ You may distribute copies of this etext electronically, or by\n\ disk, book or any other medium if you either delete this\n\ \"Small Print!\" and all other references to Project Gutenberg,\n\ or:\n\ \n\ [1] Only give exact copies of it. Among other things, this\n\ requires that you do not remove, alter or modify the\n\ etext or this \"small print!\" statement. You may however,\n\ if you wish, distribute this etext in machine readable\n\ binary, compressed, mark-up, or proprietary form,\n\ including any form resulting from conversion by word pro-\n\ cessing or hypertext software, but only so long as\n\ *EITHER*:\n\ \n\ [*] The etext, when displayed, is clearly readable, and\n\ does *not* contain characters other than those\n\ intended by the author of the work, although tilde\n\ (~), asterisk (*) and underline (_) characters may\n\ be used to convey punctuation intended by the\n\ author, and additional characters may be used to\n\ indicate hypertext links; OR\n\ \n\ [*] The etext may be readily converted by the reader at\n\ no expense into plain ASCII, EBCDIC or equivalent\n\ form by the program that displays the etext (as is\n\ the case, for instance, with most word processors);\n\ OR\n\ \n\ [*] You provide, or agree to also provide on request at\n\ no additional cost, fee or expense, a copy of the\n\ etext in its original plain ASCII form (or in EBCDIC\n\ or other equivalent proprietary form).\n\ \n\ [2] Honor the etext refund and replacement provisions of this\n\ \"Small Print!\" statement.\n\ \n\ [3] Pay a trademark license fee to the Project of 20% of the\n\ net profits you derive calculated using the method you\n\ already use to calculate your applicable taxes. If you\n\ don\'t derive profits, no royalty is due. Royalties are\n\ payable to \"Project Gutenberg Association/Carnegie-Mellon\n\ University\" within the 60 days following each\n\ date you prepare (or were legally required to prepare)\n\ your annual (or equivalent periodic) tax return.\n\ \n\ WHAT IF YOU *WANT* TO SEND MONEY EVEN IF YOU DON\'T HAVE TO?\n\ The Project gratefully accepts contributions in money, time,\n\ scanning machines, OCR software, public domain etexts, royalty\n\ free copyright licenses, and every other sort of contribution\n\ you can think of. Money should be paid to \"Project Gutenberg\n\ Association / Carnegie-Mellon University\".\n\ \n\ *END*THE SMALL PRINT! FOR PUBLIC DOMAIN ETEXTS*Ver.04.29.93*END*\n\ \n\ \n\ \n\ \n\ \n\ This etext was prepared by the PG Shakespeare Team,\n\ a team of about twenty Project Gutenberg volunteers.\n\ \n\ \n\ \n\ \n\ \n\ THE MERCHANT OF VENICE\n\ \n\ by William Shakespeare\n\ \n\ \n\ \n\ \n\ DRAMATIS PERSONAE\n\ \n\ THE DUKE OF VENICE\n\ THE PRINCE OF MOROCCO, suitor to Portia\n\ THE PRINCE OF ARRAGON, suitor to Portia\n\ ANTONIO, a merchant of Venice\n\ BASSANIO, his friend\n\ SALANIO, friend to Antonio and Bassanio\n\ SALARINO, friend to Antonio and Bassanio\n\ GRATIANO, friend to Antonio and Bassanio\n\ LORENZO, in love with Jessica\n\ SHYLOCK, a rich Jew\n\ TUBAL, a Jew, his friend\n\ LAUNCELOT GOBBO, a clown, servant to Shylock\n\ OLD GOBBO, father to Launcelot\n\ LEONARDO, servant to Bassanio\n\ BALTHASAR, servant to Portia\n\ STEPHANO, servant to Portia\n\ \n\ PORTIA, a rich heiress\n\ NERISSA, her waiting-maid\n\ JESSICA, daughter to Shylock \n\ \n\ Magnificoes of Venice, Officers of the Court of Justice,\n\ Gaoler, Servants to Portia, and other Attendants\n\ \n\ SCENE: Partly at Venice, and partly at Belmont, the seat of\n\ Portia, on the\n\ Continent\n\ \n\ \n\ \n\ ACT 1.\n\ \n\ SCENE I. Venice. A street\n\ \n\ [Enter ANTONIO, SALARINO, and SALANIO]\n\ \n\ ANTONIO.\n\ In sooth, I know not why I am so sad;\n\ It wearies me; you say it wearies you;\n\ But how I caught it, found it, or came by it,\n\ What stuff \'tis made of, whereof it is born,\n\ I am to learn;\n\ And such a want-wit sadness makes of me\n\ That I have much ado to know myself.\n\ \n\ SALARINO.\n\ Your mind is tossing on the ocean;\n\ There where your argosies, with portly sail--\n\ Like signiors and rich burghers on the flood,\n\ Or as it were the pageants of the sea--\n\ Do overpeer the petty traffickers,\n\ That curtsy to them, do them reverence,\n\ As they fly by them with their woven wings.\n\ \n\ SALANIO.\n\ Believe me, sir, had I such venture forth,\n\ The better part of my affections would\n\ Be with my hopes abroad. I should be still\n\ Plucking the grass to know where sits the wind,\n\ Peering in maps for ports, and piers, and roads;\n\ And every object that might make me fear\n\ Misfortune to my ventures, out of doubt\n\ Would make me sad.\n\ \n\ SALARINO.\n\ My wind, cooling my broth\n\ Would blow me to an ague, when I thought\n\ What harm a wind too great might do at sea.\n\ I should not see the sandy hour-glass run\n\ But I should think of shallows and of flats,\n\ And see my wealthy Andrew dock\'d in sand,\n\ Vailing her high top lower than her ribs\n\ To kiss her burial. Should I go to church\n\ And see the holy edifice of stone,\n\ And not bethink me straight of dangerous rocks,\n\ Which, touching but my gentle vessel\'s side,\n\ Would scatter all her spices on the stream,\n\ Enrobe the roaring waters with my silks,\n\ And, in a word, but even now worth this,\n\ And now worth nothing? Shall I have the thought\n\ To think on this, and shall I lack the thought\n\ That such a thing bechanc\'d would make me sad?\n\ But tell not me; I know Antonio\n\ Is sad to think upon his merchandise.\n\ \n\ ANTONIO.\n\ Believe me, no; I thank my fortune for it,\n\ My ventures are not in one bottom trusted,\n\ Nor to one place; nor is my whole estate\n\ Upon the fortune of this present year;\n\ Therefore my merchandise makes me not sad.\n\ \n\ SALARINO.\n\ Why, then you are in love.\n\ \n\ ANTONIO.\n\ Fie, fie!\n\ \n\ SALARINO.\n\ Not in love neither? Then let us say you are sad\n\ Because you are not merry; and \'twere as easy\n\ For you to laugh and leap and say you are merry,\n\ Because you are not sad. Now, by two-headed Janus,\n\ Nature hath fram\'d strange fellows in her time:\n\ Some that will evermore peep through their eyes,\n\ And laugh like parrots at a bag-piper;\n\ And other of such vinegar aspect\n\ That they\'ll not show their teeth in way of smile\n\ Though Nestor swear the jest be laughable.\n\ \n\ [Enter BASSANIO, LORENZO, and GRATIANO.]\n\ \n\ SALANIO.\n\ Here comes Bassanio, your most noble kinsman,\n\ Gratiano, and Lorenzo. Fare ye well;\n\ We leave you now with better company.\n\ \n\ SALARINO.\n\ I would have stay\'d till I had made you merry,\n\ If worthier friends had not prevented me.\n\ \n\ ANTONIO.\n\ Your worth is very dear in my regard.\n\ I take it your own business calls on you,\n\ And you embrace th\' occasion to depart.\n\ \n\ SALARINO.\n\ Good morrow, my good lords.\n\ \n\ BASSANIO.\n\ Good signiors both, when shall we laugh? Say when.\n\ You grow exceeding strange; must it be so?\n\ \n\ SALARINO.\n\ We\'ll make our leisures to attend on yours.\n\ \n\ [Exeunt SALARINO and SALANIO.]\n\ \n\ LORENZO.\n\ My Lord Bassanio, since you have found Antonio,\n\ We two will leave you; but at dinner-time,\n\ I pray you, have in mind where we must meet.\n\ \n\ BASSANIO.\n\ I will not fail you.\n\ \n\ GRATIANO.\n\ You look not well, Signior Antonio;\n\ You have too much respect upon the world;\n\ They lose it that do buy it with much care.\n\ Believe me, you are marvellously chang\'d.\n\ \n\ ANTONIO.\n\ I hold the world but as the world, Gratiano;\n\ A stage, where every man must play a part,\n\ And mine a sad one.\n\ \n\ GRATIANO.\n\ Let me play the fool;\n\ With mirth and laughter let old wrinkles come;\n\ And let my liver rather heat with wine\n\ Than my heart cool with mortifying groans.\n\ Why should a man whose blood is warm within\n\ Sit like his grandsire cut in alabaster,\n\ Sleep when he wakes, and creep into the jaundice\n\ By being peevish? I tell thee what, Antonio--\n\ I love thee, and \'tis my love that speaks--\n\ There are a sort of men whose visages\n\ Do cream and mantle like a standing pond,\n\ And do a wilful stillness entertain,\n\ With purpose to be dress\'d in an opinion\n\ Of wisdom, gravity, profound conceit;\n\ As who should say \'I am Sir Oracle,\n\ And when I ope my lips let no dog bark.\'\n\ O my Antonio, I do know of these\n\ That therefore only are reputed wise\n\ For saying nothing; when, I am very sure,\n\ If they should speak, would almost damn those ears\n\ Which, hearing them, would call their brothers fools.\n\ I\'ll tell thee more of this another time.\n\ But fish not with this melancholy bait,\n\ For this fool gudgeon, this opinion.\n\ Come, good Lorenzo. Fare ye well awhile;\n\ I\'ll end my exhortation after dinner.\n\ \n\ LORENZO.\n\ Well, we will leave you then till dinner-time.\n\ I must be one of these same dumb wise men,\n\ For Gratiano never lets me speak.\n\ \n\ GRATIANO.\n\ Well, keep me company but two years moe,\n\ Thou shalt not know the sound of thine own tongue.\n\ \n\ ANTONIO.\n\ Fare you well; I\'ll grow a talker for this gear.\n\ \n\ GRATIANO.\n\ Thanks, i\' faith, for silence is only commendable\n\ In a neat\'s tongue dried, and a maid not vendible.\n\ \n\ [Exeunt GRATIANO and LORENZO.]\n\ \n\ ANTONIO.\n\ Is that anything now?\n\ \n\ BASSANIO.\n\ Gratiano speaks an infinite deal of nothing, more than\n\ any man in all Venice. His reasons are as two grains of wheat hid\n\ in, two bushels of chaff: you shall seek all day ere you find\n\ them, and when you have them they are not worth the search.\n\ \n\ ANTONIO.\n\ Well; tell me now what lady is the same\n\ To whom you swore a secret pilgrimage,\n\ That you to-day promis\'d to tell me of?\n\ \n\ BASSANIO.\n\ \'Tis not unknown to you, Antonio,\n\ How much I have disabled mine estate\n\ By something showing a more swelling port\n\ Than my faint means would grant continuance;\n\ Nor do I now make moan to be abridg\'d\n\ From such a noble rate; but my chief care\n\ Is to come fairly off from the great debts\n\ Wherein my time, something too prodigal,\n\ Hath left me gag\'d. To you, Antonio,\n\ I owe the most, in money and in love;\n\ And from your love I have a warranty\n\ To unburden all my plots and purposes\n\ How to get clear of all the debts I owe.\n\ \n\ ANTONIO.\n\ I pray you, good Bassanio, let me know it;\n\ And if it stand, as you yourself still do,\n\ Within the eye of honour, be assur\'d\n\ My purse, my person, my extremest means,\n\ Lie all unlock\'d to your occasions.\n\ \n\ BASSANIO.\n\ In my school-days, when I had lost one shaft,\n\ I shot his fellow of the self-same flight\n\ The self-same way, with more advised watch,\n\ To find the other forth; and by adventuring both\n\ I oft found both. I urge this childhood proof,\n\ Because what follows is pure innocence.\n\ I owe you much; and, like a wilful youth,\n\ That which I owe is lost; but if you please\n\ To shoot another arrow that self way\n\ Which you did shoot the first, I do not doubt,\n\ As I will watch the aim, or to find both,\n\ Or bring your latter hazard back again\n\ And thankfully rest debtor for the first.\n\ \n\ ANTONIO.\n\ You know me well, and herein spend but time\n\ To wind about my love with circumstance;\n\ And out of doubt you do me now more wrong\n\ In making question of my uttermost\n\ Than if you had made waste of all I have.\n\ Then do but say to me what I should do\n\ That in your knowledge may by me be done,\n\ And I am prest unto it; therefore, speak.\n\ \n\ BASSANIO.\n\ In Belmont is a lady richly left,\n\ And she is fair and, fairer than that word,\n\ Of wondrous virtues. Sometimes from her eyes\n\ I did receive fair speechless messages:\n\ Her name is Portia--nothing undervalu\'d\n\ To Cato\'s daughter, Brutus\' Portia:\n\ Nor is the wide world ignorant of her worth,\n\ For the four winds blow in from every coast\n\ Renowned suitors, and her sunny locks\n\ Hang on her temples like a golden fleece;\n\ Which makes her seat of Belmont Colchos\' strond,\n\ And many Jasons come in quest of her.\n\ O my Antonio! had I but the means\n\ To hold a rival place with one of them,\n\ I have a mind presages me such thrift\n\ That I should questionless be fortunate.\n\ \n\ ANTONIO.\n\ Thou know\'st that all my fortunes are at sea;\n\ Neither have I money nor commodity\n\ To raise a present sum; therefore go forth,\n\ Try what my credit can in Venice do;\n\ That shall be rack\'d, even to the uttermost,\n\ To furnish thee to Belmont to fair Portia.\n\ Go presently inquire, and so will I,\n\ Where money is; and I no question make\n\ To have it of my trust or for my sake.\n\ \n\ [Exeunt]\n\ \n\ \n\ \n\ SCENE 2. Belmont. A room in PORTIA\'S house\n\ \n\ [Enter PORTIA and NERISSA.]\n\ \n\ PORTIA.\n\ By my troth, Nerissa, my little body is aweary of this\n\ great world.\n\ \n\ NERISSA.\n\ You would be, sweet madam, if your miseries were in the\n\ same abundance as your good fortunes are; and yet, for aught I\n\ see, they are as sick that surfeit with too much as they that\n\ starve with nothing. It is no mean happiness, therefore, to be\n\ seated in the mean: superfluity come sooner by white hairs, but\n\ competency lives longer.\n\ \n\ PORTIA.\n\ Good sentences, and well pronounced.\n\ \n\ NERISSA.\n\ They would be better, if well followed.\n\ \n\ PORTIA.\n\ If to do were as easy as to know what were good to do,\n\ chapels had been churches, and poor men\'s cottages princes\'\n\ palaces. It is a good divine that follows his own instructions; I\n\ can easier teach twenty what were good to be done than to be one\n\ of the twenty to follow mine own teaching. The brain may devise\n\ laws for the blood, but a hot temper leaps o\'er a cold decree;\n\ such a hare is madness the youth, to skip o\'er the meshes of good\n\ counsel the cripple. But this reasoning is not in the fashion to\n\ choose me a husband. O me, the word \'choose\'! I may neither\n\ choose who I would nor refuse who I dislike; so is the will of a\n\ living daughter curb\'d by the will of a dead father. Is it not\n\ hard, Nerissa, that I cannot choose one, nor refuse none?\n\ \n\ NERISSA.\n\ Your father was ever virtuous, and holy men at their death\n\ have good inspirations; therefore the lott\'ry that he hath\n\ devised in these three chests, of gold, silver, and lead, whereof\n\ who chooses his meaning chooses you, will no doubt never be\n\ chosen by any rightly but one who you shall rightly love. But\n\ what warmth is there in your affection towards any of these\n\ princely suitors that are already come?\n\ \n\ PORTIA.\n\ I pray thee over-name them; and as thou namest them, I will\n\ describe them; and according to my description, level at my\n\ affection.\n\ \n\ NERISSA.\n\ First, there is the Neapolitan prince.\n\ \n\ PORTIA.\n\ Ay, that\'s a colt indeed, for he doth nothing but talk of\n\ his horse; and he makes it a great appropriation to his own good\n\ parts that he can shoe him himself; I am much afeard my lady his\n\ mother play\'d false with a smith.\n\ \n\ NERISSA.\n\ Then is there the County Palatine.\n\ \n\ PORTIA.\n\ He doth nothing but frown, as who should say \'An you will\n\ not have me, choose.\' He hears merry tales and smiles not: I fear\n\ he will prove the weeping philosopher when he grows old, being so\n\ full of unmannerly sadness in his youth. I had rather be married\n\ to a death\'s-head with a bone in his mouth than to either of\n\ these. God defend me from these two!\n\ \n\ NERISSA.\n\ How say you by the French lord, Monsieur Le Bon?\n\ \n\ PORTIA.\n\ God made him, and therefore let him pass for a man. In\n\ truth, I know it is a sin to be a mocker, but he! why, he hath a\n\ horse better than the Neapolitan\'s, a better bad habit of\n\ frowning than the Count Palatine; he is every man in no man. If a\n\ throstle sing he falls straight a-capering; he will fence with\n\ his own shadow; if I should marry him, I should marry twenty\n\ husbands. If he would despise me, I would forgive him; for if he\n\ love me to madness, I shall never requite him.\n\ \n\ NERISSA.\n\ What say you, then, to Falconbridge, the young baron of\n\ England?\n\ \n\ PORTIA.\n\ You know I say nothing to him, for he understands not me,\n\ nor I him: he hath neither Latin, French, nor Italian, and you\n\ will come into the court and swear that I have a poor pennyworth\n\ in the English. He is a proper man\'s picture; but alas, who can\n\ converse with a dumb-show? How oddly he is suited! I think he\n\ bought his doublet in Italy, his round hose in France, his bonnet\n\ in Germany, and his behaviour everywhere.\n\ \n\ NERISSA.\n\ What think you of the Scottish lord, his neighbour?\n\ \n\ PORTIA.\n\ That he hath a neighbourly charity in him, for he borrowed\n\ a box of the ear of the Englishman, and swore he would pay him\n\ again when he was able; I think the Frenchman became his surety,\n\ and sealed under for another.\n\ \n\ NERISSA.\n\ How like you the young German, the Duke of Saxony\'s nephew?\n\ \n\ PORTIA.\n\ Very vilely in the morning when he is sober, and most\n\ vilely in the afternoon when he is drunk: when he is best, he is\n\ a little worse than a man, and when he is worst, he is little\n\ better than a beast. An the worst fall that ever fell, I hope I\n\ shall make shift to go without him.\n\ \n\ NERISSA.\n\ If he should offer to choose, and choose the right casket,\n\ you should refuse to perform your father\'s will, if you should\n\ refuse to accept him.\n\ \n\ PORTIA.\n\ Therefore, for fear of the worst, I pray thee set a deep\n\ glass of Rhenish wine on the contrary casket; for if the devil be\n\ within and that temptation without, I know he will choose it. I\n\ will do anything, Nerissa, ere I will be married to a sponge.\n\ \n\ NERISSA.\n\ You need not fear, lady, the having any of these lords;\n\ they have acquainted me with their determinations, which is\n\ indeed to return to their home, and to trouble you with no more\n\ suit, unless you may be won by some other sort than your father\'s\n\ imposition, depending on the caskets.\n\ \n\ PORTIA.\n\ If I live to be as old as Sibylla, I will die as chaste as\n\ Diana, unless I be obtained by the manner of my father\'s will. I\n\ am glad this parcel of wooers are so reasonable; for there is not\n\ one among them but I dote on his very absence, and I pray God\n\ grant them a fair departure.\n\ \n\ NERISSA.\n\ Do you not remember, lady, in your father\'s time, a Venetian, a\n\ scholar and a soldier, that came hither in company of the Marquis\n\ of Montferrat?\n\ \n\ PORTIA.\n\ Yes, yes, it was Bassanio; as I think, so was he called.\n\ \n\ NERISSA.\n\ True, madam; he, of all the men that ever my foolish eyes\n\ looked upon, was the best deserving a fair lady.\n\ \n\ PORTIA.\n\ I remember him well, and I remember him worthy of thy praise.\n\ \n\ [Enter a SERVANT.]\n\ \n\ How now! what news?\n\ \n\ SERVANT.\n\ The four strangers seek for you, madam, to take their\n\ leave; and there is a forerunner come from a fifth, the Prince of\n\ Morocco, who brings word the Prince his master will be here\n\ to-night.\n\ \n\ PORTIA.\n\ If I could bid the fifth welcome with so good heart as I\n\ can bid the other four farewell, I should be glad of his\n\ approach; if he have the condition of a saint and the complexion\n\ of a devil, I had rather he should shrive me than wive me.\n\ Come, Nerissa. Sirrah, go before.\n\ Whiles we shut the gate upon one wooer, another knocks at the\n\ door.\n\ \n\ [Exeunt]\n\ \n\ \n\ \n\ SCENE 3. Venice. A public place\n\ \n\ [Enter BASSANIO and SHYLOCK.]\n\ \n\ SHYLOCK.\n\ Three thousand ducats; well?\n\ \n\ BASSANIO.\n\ Ay, sir, for three months.\n\ \n\ SHYLOCK.\n\ For three months; well?\n\ \n\ BASSANIO.\n\ For the which, as I told you, Antonio shall be bound.\n\ \n\ SHYLOCK.\n\ Antonio shall become bound; well?\n\ \n\ BASSANIO.\n\ May you stead me? Will you pleasure me? Shall I know your\n\ answer?\n\ \n\ SHYLOCK.\n\ Three thousand ducats, for three months, and Antonio bound.\n\ \n\ BASSANIO.\n\ Your answer to that.\n\ \n\ SHYLOCK.\n\ Antonio is a good man.\n\ \n\ BASSANIO.\n\ Have you heard any imputation to the contrary?\n\ \n\ SHYLOCK.\n\ Ho, no, no, no, no: my meaning in saying he is a good man\n\ is to have you understand me that he is sufficient; yet his means\n\ are in supposition: he hath an argosy bound to Tripolis, another\n\ to the Indies; I understand, moreover, upon the Rialto, he hath a\n\ third at Mexico, a fourth for England, and other ventures he\n\ hath, squandered abroad. But ships are but boards, sailors but\n\ men; there be land-rats and water-rats, land-thieves and\n\ water-thieves,--I mean pirates,--and then there is the peril of\n\ waters, winds, and rocks. The man is, notwithstanding,\n\ sufficient. Three thousand ducats- I think I may take his bond.\n\ \n\ BASSANIO.\n\ Be assured you may.\n\ \n\ SHYLOCK.\n\ I will be assured I may; and, that I may be assured, I\n\ will bethink me. May I speak with Antonio?\n\ \n\ BASSANIO.\n\ If it please you to dine with us.\n\ \n\ SHYLOCK.\n\ Yes, to smell pork; to eat of the habitation which your\n\ prophet, the Nazarite, conjured the devil into. I will buy with\n\ you, sell with you, talk with you, walk with you, and so\n\ following; but I will not eat with you, drink with you, nor pray\n\ with you. What news on the Rialto? Who is he comes here?\n\ \n\ [Enter ANTONIO]\n\ \n\ BASSANIO.\n\ This is Signior Antonio.\n\ \n\ SHYLOCK.\n\ [Aside] How like a fawning publican he looks!\n\ I hate him for he is a Christian;\n\ But more for that in low simplicity\n\ He lends out money gratis, and brings down\n\ The rate of usance here with us in Venice.\n\ If I can catch him once upon the hip,\n\ I will feed fat the ancient grudge I bear him.\n\ He hates our sacred nation; and he rails,\n\ Even there where merchants most do congregate,\n\ On me, my bargains, and my well-won thrift,\n\ Which he calls interest. Cursed be my tribe\n\ If I forgive him!\n\ \n\ BASSANIO.\n\ Shylock, do you hear?\n\ \n\ SHYLOCK.\n\ I am debating of my present store,\n\ And, by the near guess of my memory,\n\ I cannot instantly raise up the gross\n\ Of full three thousand ducats. What of that?\n\ Tubal, a wealthy Hebrew of my tribe,\n\ Will furnish me. But soft! how many months\n\ Do you desire? [To ANTONIO] Rest you fair, good signior;\n\ Your worship was the last man in our mouths.\n\ \n\ ANTONIO.\n\ Shylock, albeit I neither lend nor borrow\n\ By taking nor by giving of excess,\n\ Yet, to supply the ripe wants of my friend,\n\ I\'ll break a custom. [To BASSANIO] Is he yet possess\'d\n\ How much ye would?\n\ \n\ SHYLOCK.\n\ Ay, ay, three thousand ducats.\n\ \n\ ANTONIO.\n\ And for three months.\n\ \n\ SHYLOCK.\n\ I had forgot; three months; you told me so.\n\ Well then, your bond; and, let me see. But hear you,\n\ Methought you said you neither lend nor borrow\n\ Upon advantage.\n\ \n\ ANTONIO.\n\ I do never use it.\n\ \n\ SHYLOCK.\n\ When Jacob graz\'d his uncle Laban\'s sheep,--\n\ This Jacob from our holy Abram was,\n\ As his wise mother wrought in his behalf,\n\ The third possessor; ay, he was the third,--\n\ \n\ ANTONIO.\n\ And what of him? Did he take interest?\n\ \n\ SHYLOCK.\n\ No, not take interest; not, as you would say,\n\ Directly interest; mark what Jacob did.\n\ When Laban and himself were compromis\'d\n\ That all the eanlings which were streak\'d and pied\n\ Should fall as Jacob\'s hire, the ewes, being rank,\n\ In end of autumn turned to the rams;\n\ And when the work of generation was\n\ Between these woolly breeders in the act,\n\ The skilful shepherd peel\'d me certain wands,\n\ And, in the doing of the deed of kind,\n\ He stuck them up before the fulsome ewes,\n\ Who, then conceiving, did in eaning time\n\ Fall parti-colour\'d lambs, and those were Jacob\'s.\n\ This was a way to thrive, and he was blest;\n\ And thrift is blessing, if men steal it not.\n\ \n\ ANTONIO.\n\ This was a venture, sir, that Jacob serv\'d for;\n\ A thing not in his power to bring to pass,\n\ But sway\'d and fashion\'d by the hand of heaven.\n\ Was this inserted to make interest good?\n\ Or is your gold and silver ewes and rams?\n\ \n\ SHYLOCK.\n\ I cannot tell; I make it breed as fast.\n\ But note me, signior.\n\ \n\ ANTONIO.\n\ Mark you this, Bassanio,\n\ The devil can cite Scripture for his purpose.\n\ An evil soul producing holy witness\n\ Is like a villain with a smiling cheek,\n\ A goodly apple rotten at the heart.\n\ O, what a goodly outside falsehood hath!\n\ \n\ SHYLOCK.\n\ Three thousand ducats; \'tis a good round sum.\n\ Three months from twelve; then let me see the rate.\n\ \n\ ANTONIO.\n\ Well, Shylock, shall we be beholding to you?\n\ \n\ SHYLOCK.\n\ Signior Antonio, many a time and oft\n\ In the Rialto you have rated me\n\ About my moneys and my usances;\n\ Still have I borne it with a patient shrug,\n\ For suff\'rance is the badge of all our tribe;\n\ You call me misbeliever, cut-throat dog,\n\ And spet upon my Jewish gaberdine,\n\ And all for use of that which is mine own.\n\ Well then, it now appears you need my help;\n\ Go to, then; you come to me, and you say\n\ \'Shylock, we would have moneys.\' You say so:\n\ You that did void your rheum upon my beard,\n\ And foot me as you spurn a stranger cur\n\ Over your threshold; moneys is your suit.\n\ What should I say to you? Should I not say\n\ \'Hath a dog money? Is it possible\n\ A cur can lend three thousand ducats?\' Or\n\ Shall I bend low and, in a bondman\'s key,\n\ With bated breath and whisp\'ring humbleness,\n\ Say this:--\n\ \'Fair sir, you spit on me on Wednesday last;\n\ You spurn\'d me such a day; another time\n\ You call\'d me dog; and for these courtesies\n\ I\'ll lend you thus much moneys?\'\n\ \n\ ANTONIO.\n\ I am as like to call thee so again,\n\ To spet on thee again, to spurn thee too.\n\ If thou wilt lend this money, lend it not\n\ As to thy friends,--for when did friendship take\n\ A breed for barren metal of his friend?--\n\ But lend it rather to thine enemy;\n\ Who if he break thou mayst with better face\n\ Exact the penalty.\n\ \n\ SHYLOCK.\n\ Why, look you, how you storm!\n\ I would be friends with you, and have your love,\n\ Forget the shames that you have stain\'d me with,\n\ Supply your present wants, and take no doit\n\ Of usance for my moneys, and you\'ll not hear me:\n\ This is kind I offer.\n\ \n\ BASSANIO.\n\ This were kindness.\n\ \n\ SHYLOCK.\n\ This kindness will I show.\n\ Go with me to a notary, seal me there\n\ Your single bond; and, in a merry sport,\n\ If you repay me not on such a day,\n\ In such a place, such sum or sums as are\n\ Express\'d in the condition, let the forfeit\n\ Be nominated for an equal pound\n\ Of your fair flesh, to be cut off and taken\n\ In what part of your body pleaseth me.\n\ \n\ ANTONIO.\n\ Content, in faith; I\'ll seal to such a bond,\n\ And say there is much kindness in the Jew.\n\ \n\ BASSANIO.\n\ You shall not seal to such a bond for me;\n\ I\'ll rather dwell in my necessity.\n\ \n\ ANTONIO.\n\ Why, fear not, man; I will not forfeit it;\n\ Within these two months, that\'s a month before\n\ This bond expires, I do expect return\n\ Of thrice three times the value of this bond.\n\ \n\ SHYLOCK.\n\ O father Abram, what these Christians are,\n\ Whose own hard dealings teaches them suspect\n\ The thoughts of others. Pray you, tell me this;\n\ If he should break his day, what should I gain\n\ By the exaction of the forfeiture?\n\ A pound of man\'s flesh, taken from a man,\n\ Is not so estimable, profitable neither,\n\ As flesh of muttons, beefs, or goats. I say,\n\ To buy his favour, I extend this friendship;\n\ If he will take it, so; if not, adieu;\n\ And, for my love, I pray you wrong me not.\n\ \n\ ANTONIO.\n\ Yes, Shylock, I will seal unto this bond.\n\ \n\ SHYLOCK.\n\ Then meet me forthwith at the notary\'s;\n\ Give him direction for this merry bond,\n\ And I will go and purse the ducats straight,\n\ See to my house, left in the fearful guard\n\ Of an unthrifty knave, and presently\n\ I\'ll be with you.\n\ \n\ ANTONIO.\n\ Hie thee, gentle Jew.\n\ \n\ [Exit SHYLOCK]\n\ \n\ This Hebrew will turn Christian: he grows kind.\n\ \n\ BASSANIO.\n\ I like not fair terms and a villain\'s mind.\n\ \n\ ANTONIO.\n\ Come on; in this there can be no dismay;\n\ My ships come home a month before the day.\n\ \n\ [Exeunt]\n\ \n\ \n\ \n\ ACT 2.\n\ \n\ SCENE I. Belmont. A room in PORTIA\'s house.\n\ \n\ [Flourish of cornets. Enter the PRINCE of MOROCCO, and his\n\ Followers;\n\ PORTIA, NERISSA, and Others of her train.]\n\ \n\ PRINCE OF Morocco.\n\ Mislike me not for my complexion,\n\ The shadow\'d livery of the burnish\'d sun,\n\ To whom I am a neighbour, and near bred.\n\ Bring me the fairest creature northward born,\n\ Where Phoebus\' fire scarce thaws the icicles,\n\ And let us make incision for your love\n\ To prove whose blood is reddest, his or mine.\n\ I tell thee, lady, this aspect of mine\n\ Hath fear\'d the valiant; by my love, I swear\n\ The best-regarded virgins of our clime\n\ Have lov\'d it too. I would not change this hue,\n\ Except to steal your thoughts, my gentle queen.\n\ \n\ PORTIA.\n\ In terms of choice I am not solely led\n\ By nice direction of a maiden\'s eyes;\n\ Besides, the lottery of my destiny\n\ Bars me the right of voluntary choosing;\n\ But, if my father had not scanted me\n\ And hedg\'d me by his wit, to yield myself\n\ His wife who wins me by that means I told you,\n\ Yourself, renowned Prince, then stood as fair\n\ As any comer I have look\'d on yet\n\ For my affection.\n\ \n\ PRINCE OF MOROCCO.\n\ Even for that I thank you:\n\ Therefore, I pray you, lead me to the caskets\n\ To try my fortune. By this scimitar,--\n\ That slew the Sophy and a Persian prince,\n\ That won three fields of Sultan Solyman,--\n\ I would o\'erstare the sternest eyes that look,\n\ Outbrave the heart most daring on the earth,\n\ Pluck the young sucking cubs from the she-bear,\n\ Yea, mock the lion when he roars for prey,\n\ To win thee, lady. But, alas the while!\n\ If Hercules and Lichas play at dice\n\ Which is the better man, the greater throw\n\ May turn by fortune from the weaker hand:\n\ So is Alcides beaten by his page;\n\ And so may I, blind Fortune leading me,\n\ Miss that which one unworthier may attain,\n\ And die with grieving.\n\ \n\ PORTIA.\n\ You must take your chance,\n\ And either not attempt to choose at all,\n\ Or swear before you choose, if you choose wrong,\n\ Never to speak to lady afterward\n\ In way of marriage; therefore be advis\'d.\n\ \n\ PRINCE OF MOROCCO.\n\ Nor will not; come, bring me unto my chance.\n\ \n\ PORTIA.\n\ First, forward to the temple: after dinner\n\ Your hazard shall be made.\n\ \n\ PRINCE OF MOROCCO.\n\ Good fortune then!\n\ To make me blest or cursed\'st among men!\n\ \n\ [Cornets, and exeunt.]\n\ \n\ \n\ \n\ SCENE 2. Venice. A street\n\ \n\ [Enter LAUNCELOT GOBBO.]\n\ \n\ LAUNCELOT.\n\ Certainly my conscience will serve me to run from this\n\ Jew my master. The fiend is at mine elbow and tempts me, saying\n\ to me \'Gobbo, Launcelot Gobbo, good Launcelot\' or \'good Gobbo\' or\n\ \'good Launcelot Gobbo, use your legs, take the start, run away.\'\n\ My conscience says \'No; take heed, honest Launcelot, take heed,\n\ honest Gobbo\' or, as aforesaid, \'honest Launcelot Gobbo, do not\n\ run; scorn running with thy heels.\' Well, the most courageous\n\ fiend bids me pack. \'Via!\' says the fiend; \'away!\' says the\n\ fiend. \'For the heavens, rouse up a brave mind,\' says the fiend\n\ \'and run.\' Well, my conscience, hanging about the neck of my\n\ heart, says very wisely to me \'My honest friend Launcelot, being\n\ an honest man\'s son\'--or rather \'an honest woman\'s son\';--for\n\ indeed my father did something smack, something grow to, he had a\n\ kind of taste;--well, my conscience says \'Launcelot, budge not.\'\n\ \'Budge,\' says the fiend. \'Budge not,\' says my conscience.\n\ \'Conscience,\' say I, (you counsel well.\' \'Fiend,\' say I, \'you\n\ counsel well.\' To be ruled by my conscience, I should stay with\n\ the Jew my master, who, God bless the mark! is a kind of devil;\n\ and, to run away from the Jew, I should be ruled by the fiend,\n\ who, saving your reverence! is the devil himself. Certainly the\n\ Jew is the very devil incarnal; and, in my conscience, my\n\ conscience is but a kind of hard conscience, to offer to counsel\n\ me to stay with the Jew. The fiend gives the more friendly\n\ counsel: I will run, fiend; my heels are at your commandment; I\n\ will run.\n\ \n\ [Enter OLD GOBBO, with a basket]\n\ \n\ GOBBO.\n\ Master young man, you, I pray you; which is the way to Master\n\ Jew\'s?\n\ \n\ LAUNCELOT.\n\ [Aside] O heavens! This is my true-begotten father, who, being\n\ more\n\ than sand-blind, high-gravel blind, knows me not: I will try\n\ confusions with him.\n\ \n\ GOBBO.\n\ Master young gentleman, I pray you, which is the way to Master\n\ Jew\'s?\n\ \n\ LAUNCELOT.\n\ Turn up on your right hand at the next turning, but, at\n\ the next turning of all, on your left; marry, at the very next\n\ turning, turn of no hand, but turn down indirectly to the Jew\'s\n\ house.\n\ \n\ GOBBO.\n\ Be God\'s sonties, \'twill be a hard way to hit. Can you tell\n\ me whether one Launcelot, that dwells with him, dwell with him or\n\ no?\n\ \n\ LAUNCELOT.\n\ Talk you of young Master Launcelot? [Aside] Mark me\n\ now; now will I raise the waters. Talk you of young Master\n\ Launcelot?\n\ \n\ GOBBO.\n\ No master, sir, but a poor man\'s son; his father, though I\n\ say\'t, is an honest exceeding poor man, and, God be thanked, well\n\ to live.\n\ \n\ LAUNCELOT.\n\ Well, let his father be what \'a will, we talk of young\n\ Master Launcelot.\n\ \n\ GOBBO.\n\ Your worship\'s friend, and Launcelot, sir.\n\ \n\ LAUNCELOT.\n\ But I pray you, ergo, old man, ergo, I beseech you, talk\n\ you of young Master Launcelot?\n\ \n\ GOBBO.\n\ Of Launcelot, an\'t please your mastership.\n\ \n\ LAUNCELOT.\n\ Ergo, Master Launcelot. Talk not of Master Launcelot,\n\ father; for the young gentleman,--according to Fates and\n\ Destinies\n\ and such odd sayings, the Sisters Three and such branches of\n\ learning,--is indeed deceased; or, as you would say in plain\n\ terms, gone to heaven.\n\ \n\ GOBBO.\n\ Marry, God forbid! The boy was the very staff of my age, my\n\ very prop.\n\ \n\ LAUNCELOT.\n\ Do I look like a cudgel or a hovel-post, a staff or a prop? Do\n\ you know me, father?\n\ \n\ GOBBO.\n\ Alack the day! I know you not, young gentleman; but I pray\n\ you tell me, is my boy--God rest his soul!--alive or dead?\n\ \n\ LAUNCELOT.\n\ Do you not know me, father?\n\ \n\ GOBBO.\n\ Alack, sir, I am sand-blind; I know you not.\n\ \n\ LAUNCELOT.\n\ Nay, indeed, if you had your eyes, you might fail of the\n\ knowing me: it is a wise father that knows his own child. Well,\n\ old man, I will tell you news of your son. Give me your blessing;\n\ truth will come to light; murder cannot be hid long; a man\'s son\n\ may, but in the end truth will out.\n\ \n\ GOBBO.\n\ Pray you, sir, stand up; I am sure you are not Launcelot, my boy.\n\ \n\ LAUNCELOT.\n\ Pray you, let\'s have no more fooling about it, but give\n\ me your blessing; I am Launcelot, your boy that was, your son\n\ that is, your child that shall be.\n\ \n\ GOBBO.\n\ I cannot think you are my son.\n\ \n\ LAUNCELOT.\n\ I know not what I shall think of that; but I am Launcelot, the\n\ Jew\'s man, and I am sure Margery your wife is my mother.\n\ \n\ GOBBO.\n\ Her name is Margery, indeed: I\'ll be sworn, if thou be\n\ Launcelot, thou art mine own flesh and blood. Lord worshipped\n\ might he be, what a beard hast thou got! Thou hast got more hair\n\ on thy chin than Dobbin my thill-horse has on his tail.\n\ \n\ LAUNCELOT.\n\ It should seem, then, that Dobbin\'s tail grows backward;\n\ I am sure he had more hair on his tail than I have on my face\n\ when I last saw him.\n\ \n\ GOBBO.\n\ Lord! how art thou changed! How dost thou and thy master\n\ agree? I have brought him a present. How \'gree you now?\n\ \n\ LAUNCELOT.\n\ Well, well; but, for mine own part, as I have set up my\n\ rest to run away, so I will not rest till I have run some ground.\n\ My master\'s a very Jew. Give him a present! Give him a halter. I\n\ am famished in his service; you may tell every finger I have with\n\ my ribs. Father, I am glad you are come; give me your present to\n\ one Master Bassanio, who indeed gives rare new liveries. If I\n\ serve not him, I will run as far as God has any ground. O rare\n\ fortune! Here comes the man: to him, father; for I am a Jew, if I\n\ serve the Jew any longer.\n\ \n\ [Enter BASSANIO, with LEONARDO, with and other Followers.]\n\ \n\ BASSANIO.\n\ You may do so; but let it be so hasted that supper be\n\ ready at the farthest by five of the clock. See these letters\n\ delivered, put the liveries to making, and desire Gratiano to\n\ come anon to my lodging.\n\ \n\ [Exit a SERVANT]\n\ \n\ LAUNCELOT.\n\ To him, father.\n\ \n\ GOBBO.\n\ God bless your worship!\n\ \n\ BASSANIO.\n\ Gramercy; wouldst thou aught with me?\n\ \n\ GOBBO.\n\ Here\'s my son, sir, a poor boy--\n\ \n\ LAUNCELOT.\n\ Not a poor boy, sir, but the rich Jew\'s man, that would,\n\ sir,--as my father shall specify--\n\ \n\ GOBBO.\n\ He hath a great infection, sir, as one would say, to serve--\n\ \n\ LAUNCELOT.\n\ Indeed the short and the long is, I serve the Jew, and\n\ have a desire, as my father shall specify--\n\ \n\ GOBBO.\n\ His master and he, saving your worship\'s reverence, are\n\ scarce cater-cousins--\n\ \n\ LAUNCELOT.\n\ To be brief, the very truth is that the Jew, having done\n\ me wrong, doth cause me,--as my father, being I hope an old man,\n\ shall frutify unto you--\n\ \n\ GOBBO.\n\ I have here a dish of doves that I would bestow upon your\n\ worship; and my suit is--\n\ \n\ LAUNCELOT.\n\ In very brief, the suit is impertinent to myself, as\n\ your worship shall know by this honest old man; and, though I say\n\ it, though old man, yet poor man, my father.\n\ \n\ BASSANIO.\n\ One speak for both. What would you?\n\ \n\ LAUNCELOT.\n\ Serve you, sir.\n\ \n\ GOBBO.\n\ That is the very defect of the matter, sir.\n\ \n\ BASSANIO.\n\ I know thee well; thou hast obtain\'d thy suit.\n\ Shylock thy master spoke with me this day,\n\ And hath preferr\'d thee, if it be preferment\n\ To leave a rich Jew\'s service to become\n\ The follower of so poor a gentleman.\n\ \n\ LAUNCELOT.\n\ The old proverb is very well parted between my master\n\ Shylock and you, sir: you have the grace of God, sir, and he hath\n\ enough.\n\ \n\ BASSANIO.\n\ Thou speak\'st it well. Go, father, with thy son.\n\ Take leave of thy old master, and inquire\n\ My lodging out. [To a SERVANT] Give him a livery\n\ More guarded than his fellows\'; see it done.\n\ \n\ LAUNCELOT.\n\ Father, in. I cannot get a service, no! I have ne\'er a\n\ tongue in my head! [Looking on his palm] Well; if any man in\n\ Italy have a fairer table which doth offer to swear upon a book,\n\ I\n\ shall have good fortune. Go to; here\'s a simple line of life:\n\ here\'s a small trifle of wives; alas, fifteen wives is nothing;\n\ a\'leven widows and nine maids is a simple coming-in for one man.\n\ And then to scape drowning thrice, and to be in peril of my life\n\ with the edge of a feather-bed; here are simple \'scapes. Well, if\n\ Fortune be a woman, she\'s a good wench for this gear. Father,\n\ come; I\'ll take my leave of the Jew in the twinkling of an eye.\n\ \n\ [Exeunt LAUNCELOT and OLD GOBBO.]\n\ \n\ BASSANIO.\n\ I pray thee, good Leonardo, think on this:\n\ These things being bought and orderly bestow\'d,\n\ Return in haste, for I do feast to-night\n\ My best esteem\'d acquaintance; hie thee, go.\n\ \n\ LEONARDO.\n\ My best endeavours shall be done herein.\n\ \n\ [Enter GRATIANO.]\n\ \n\ GRATIANO.\n\ Where\'s your master?\n\ \n\ LEONARDO.\n\ Yonder, sir, he walks.\n\ \n\ [Exit.]\n\ \n\ GRATIANO.\n\ Signior Bassanio!--\n\ \n\ BASSANIO.\n\ Gratiano!\n\ \n\ GRATIANO.\n\ I have suit to you.\n\ \n\ BASSANIO.\n\ You have obtain\'d it.\n\ \n\ GRATIANO.\n\ You must not deny me: I must go with you to Belmont.\n\ \n\ BASSANIO.\n\ Why, then you must. But hear thee, Gratiano;\n\ Thou art too wild, too rude, and bold of voice;\n\ Parts that become thee happily enough,\n\ And in such eyes as ours appear not faults;\n\ But where thou art not known, why there they show\n\ Something too liberal. Pray thee, take pain\n\ To allay with some cold drops of modesty\n\ Thy skipping spirit, lest through thy wild behaviour\n\ I be misconstrued in the place I go to,\n\ And lose my hopes.\n\ \n\ GRATIANO.\n\ Signior Bassanio, hear me:\n\ If I do not put on a sober habit,\n\ Talk with respect, and swear but now and then,\n\ Wear prayer-books in my pocket, look demurely,\n\ Nay more, while grace is saying, hood mine eyes\n\ Thus with my hat, and sigh, and say \'amen\';\n\ Use all the observance of civility,\n\ Like one well studied in a sad ostent\n\ To please his grandam, never trust me more.\n\ \n\ BASSANIO.\n\ Well, we shall see your bearing.\n\ \n\ GRATIANO.\n\ Nay, but I bar to-night; you shall not gauge me\n\ By what we do to-night.\n\ \n\ BASSANIO.\n\ No, that were pity;\n\ I would entreat you rather to put on\n\ Your boldest suit of mirth, for we have friends\n\ That purpose merriment. But fare you well;\n\ I have some business.\n\ \n\ GRATIANO.\n\ And I must to Lorenzo and the rest;\n\ But we will visit you at supper-time.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ SCENE 3. The same. A room in SHYLOCK\'s house.\n\ \n\ [Enter JESSICA and LAUNCELOT.]\n\ \n\ JESSICA.\n\ I am sorry thou wilt leave my father so:\n\ Our house is hell, and thou, a merry devil,\n\ Didst rob it of some taste of tediousness.\n\ But fare thee well; there is a ducat for thee;\n\ And, Launcelot, soon at supper shalt thou see\n\ Lorenzo, who is thy new master\'s guest:\n\ Give him this letter; do it secretly.\n\ And so farewell. I would not have my father\n\ See me in talk with thee.\n\ \n\ LAUNCELOT.\n\ Adieu! tears exhibit my tongue. Most beautiful pagan,\n\ most sweet Jew! If a Christian do not play the knave and get\n\ thee, I am much deceived. But, adieu! these foolish drops do\n\ something drown my manly spirit; adieu!\n\ \n\ JESSICA.\n\ Farewell, good Launcelot.\n\ \n\ [Exit LAUNCELOT]\n\ \n\ Alack, what heinous sin is it in me\n\ To be asham\'d to be my father\'s child!\n\ But though I am a daughter to his blood,\n\ I am not to his manners. O Lorenzo!\n\ If thou keep promise, I shall end this strife,\n\ Become a Christian and thy loving wife.\n\ \n\ [Exit]\n\ \n\ \n\ \n\ SCENE 4. The same. A street\n\ \n\ [Enter GRATIANO, LORENZO, SALARINO, and SALANIO.]\n\ \n\ LORENZO.\n\ Nay, we will slink away in supper-time,\n\ Disguise us at my lodging, and return\n\ All in an hour.\n\ \n\ GRATIANO.\n\ We have not made good preparation.\n\ \n\ SALARINO.\n\ We have not spoke us yet of torch-bearers.\n\ \n\ SALANIO.\n\ \'Tis vile, unless it may be quaintly order\'d,\n\ And better in my mind not undertook.\n\ \n\ LORENZO.\n\ \'Tis now but four o\'clock; we have two hours\n\ To furnish us.\n\ \n\ [Enter LAUNCELOT, With a letter.]\n\ \n\ Friend Launcelot, what\'s the news?\n\ \n\ LAUNCELOT.\n\ An it shall please you to break up this, it shall seem\n\ to signify.\n\ \n\ LORENZO.\n\ I know the hand; in faith, \'tis a fair hand,\n\ And whiter than the paper it writ on\n\ Is the fair hand that writ.\n\ \n\ GRATIANO.\n\ Love news, in faith.\n\ \n\ LAUNCELOT.\n\ By your leave, sir.\n\ \n\ LORENZO.\n\ Whither goest thou?\n\ \n\ LAUNCELOT.\n\ Marry, sir, to bid my old master, the Jew, to sup\n\ to-night with my new master, the Christian.\n\ \n\ LORENZO.\n\ Hold, here, take this. Tell gentle Jessica\n\ I will not fail her; speak it privately.\n\ Go, gentlemen,\n\ \n\ [Exit LAUNCELOT]\n\ \n\ Will you prepare you for this masque to-night?\n\ I am provided of a torch-bearer.\n\ \n\ SALARINO.\n\ Ay, marry, I\'ll be gone about it straight.\n\ \n\ SALANIO.\n\ And so will I.\n\ \n\ LORENZO.\n\ Meet me and Gratiano\n\ At Gratiano\'s lodging some hour hence.\n\ \n\ SALARINO.\n\ \'Tis good we do so.\n\ \n\ [Exeunt SALARINO and SALANIO.]\n\ \n\ GRATIANO.\n\ Was not that letter from fair Jessica?\n\ \n\ LORENZO.\n\ I must needs tell thee all. She hath directed\n\ How I shall take her from her father\'s house;\n\ What gold and jewels she is furnish\'d with;\n\ What page\'s suit she hath in readiness.\n\ If e\'er the Jew her father come to heaven,\n\ It will be for his gentle daughter\'s sake;\n\ And never dare misfortune cross her foot,\n\ Unless she do it under this excuse,\n\ That she is issue to a faithless Jew.\n\ Come, go with me, peruse this as thou goest;\n\ Fair Jessica shall be my torch-bearer.\n\ \n\ [Exeunt]\n\ \n\ \n\ \n\ SCENE 5. The same. Before SHYLOCK\'S house\n\ \n\ [Enter SHYLOCK and LAUNCELOT.]\n\ \n\ SHYLOCK.\n\ Well, thou shalt see; thy eyes shall be thy judge,\n\ The difference of old Shylock and Bassanio:--\n\ What, Jessica!--Thou shalt not gormandize,\n\ As thou hast done with me;--What, Jessica!--\n\ And sleep and snore, and rend apparel out--\n\ Why, Jessica, I say!\n\ \n\ LAUNCELOT.\n\ Why, Jessica!\n\ \n\ SHYLOCK.\n\ Who bids thee call? I do not bid thee call.\n\ \n\ LAUNCELOT.\n\ Your worship was wont to tell me I could do nothing\n\ without bidding.\n\ \n\ [Enter JESSICA.]\n\ \n\ JESSICA.\n\ Call you? What is your will?\n\ \n\ SHYLOCK.\n\ I am bid forth to supper, Jessica:\n\ There are my keys. But wherefore should I go?\n\ I am not bid for love; they flatter me;\n\ But yet I\'ll go in hate, to feed upon\n\ The prodigal Christian. Jessica, my girl,\n\ Look to my house. I am right loath to go;\n\ There is some ill a-brewing towards my rest,\n\ For I did dream of money-bags to-night.\n\ \n\ LAUNCELOT.\n\ I beseech you, sir, go: my young master doth expect your\n\ reproach.\n\ \n\ SHYLOCK.\n\ So do I his.\n\ \n\ LAUNCELOT.\n\ And they have conspired together; I will not say you\n\ shall see a masque, but if you do, then it was not for nothing\n\ that my nose fell a-bleeding on Black Monday last at six o\'clock\n\ i\' the morning, falling out that year on Ash-Wednesday was four\n\ year in the afternoon.\n\ \n\ SHYLOCK.\n\ What! are there masques? Hear you me, Jessica:\n\ Lock up my doors, and when you hear the drum,\n\ And the vile squealing of the wry-neck\'d fife,\n\ Clamber not you up to the casements then,\n\ Nor thrust your head into the public street\n\ To gaze on Christian fools with varnish\'d faces;\n\ But stop my house\'s ears- I mean my casements;\n\ Let not the sound of shallow fopp\'ry enter\n\ My sober house. By Jacob\'s staff, I swear\n\ I have no mind of feasting forth to-night;\n\ But I will go. Go you before me, sirrah;\n\ Say I will come.\n\ \n\ LAUNCELOT.\n\ I will go before, sir. Mistress, look out at window for all this;\n\ There will come a Christian by\n\ Will be worth a Jewess\' eye.\n\ \n\ [Exit LAUNCELOT.]\n\ \n\ SHYLOCK.\n\ What says that fool of Hagar\'s offspring, ha?\n\ \n\ JESSICA.\n\ His words were \'Farewell, mistress\'; nothing else.\n\ \n\ SHYLOCK.\n\ The patch is kind enough, but a huge feeder;\n\ Snail-slow in profit, and he sleeps by day\n\ More than the wild-cat; drones hive not with me,\n\ Therefore I part with him; and part with him\n\ To one that I would have him help to waste\n\ His borrow\'d purse. Well, Jessica, go in;\n\ Perhaps I will return immediately:\n\ Do as I bid you, shut doors after you:\n\ \'Fast bind, fast find,\'\n\ A proverb never stale in thrifty mind.\n\ \n\ [Exit.]\n\ \n\ JESSICA.\n\ Farewell; and if my fortune be not crost,\n\ I have a father, you a daughter, lost.\n\ \n\ [Exit.]\n\ \n\ \n\ \n\ SCENE 6. The same.\n\ \n\ [Enter GRATIANO and SALARINO, masqued.]\n\ \n\ GRATIANO.\n\ This is the pent-house under which Lorenzo\n\ Desir\'d us to make stand.\n\ \n\ SALARINO.\n\ His hour is almost past.\n\ \n\ GRATIANO.\n\ And it is marvel he out-dwells his hour,\n\ For lovers ever run before the clock.\n\ \n\ SALARINO.\n\ O! ten times faster Venus\' pigeons fly\n\ To seal love\'s bonds new made than they are wont\n\ To keep obliged faith unforfeited!\n\ \n\ GRATIANO.\n\ That ever holds: who riseth from a feast\n\ With that keen appetite that he sits down?\n\ Where is the horse that doth untread again\n\ His tedious measures with the unbated fire\n\ That he did pace them first? All things that are\n\ Are with more spirit chased than enjoy\'d.\n\ How like a younker or a prodigal\n\ The scarfed bark puts from her native bay,\n\ Hugg\'d and embraced by the strumpet wind!\n\ How like the prodigal doth she return,\n\ With over-weather\'d ribs and ragged sails,\n\ Lean, rent, and beggar\'d by the strumpet wind!\n\ \n\ SALARINO.\n\ Here comes Lorenzo; more of this hereafter.\n\ \n\ [Enter LORENZO.]\n\ \n\ LORENZO.\n\ Sweet friends, your patience for my long abode;\n\ Not I, but my affairs, have made you wait:\n\ When you shall please to play the thieves for wives,\n\ I\'ll watch as long for you then. Approach;\n\ Here dwells my father Jew. Ho! who\'s within?\n\ \n\ [Enter JESSICA, above, in boy\'s clothes.]\n\ \n\ JESSICA.\n\ Who are you? Tell me, for more certainty,\n\ Albeit I\'ll swear that I do know your tongue.\n\ \n\ LORENZO.\n\ Lorenzo, and thy love.\n\ \n\ JESSICA.\n\ Lorenzo, certain; and my love indeed,\n\ For who love I so much? And now who knows\n\ But you, Lorenzo, whether I am yours?\n\ \n\ LORENZO.\n\ Heaven and thy thoughts are witness that thou art.\n\ \n\ JESSICA.\n\ Here, catch this casket; it is worth the pains.\n\ I am glad \'tis night, you do not look on me,\n\ For I am much asham\'d of my exchange;\n\ But love is blind, and lovers cannot see\n\ The pretty follies that themselves commit,\n\ For, if they could, Cupid himself would blush\n\ To see me thus transformed to a boy.\n\ \n\ LORENZO.\n\ Descend, for you must be my torch-bearer.\n\ \n\ JESSICA.\n\ What! must I hold a candle to my shames?\n\ They in themselves, good sooth, are too-too light.\n\ Why, \'tis an office of discovery, love,\n\ And I should be obscur\'d.\n\ \n\ LORENZO.\n\ So are you, sweet,\n\ Even in the lovely garnish of a boy.\n\ But come at once;\n\ For the close night doth play the runaway,\n\ And we are stay\'d for at Bassanio\'s feast.\n\ \n\ JESSICA.\n\ I will make fast the doors, and gild myself\n\ With some moe ducats, and be with you straight.\n\ \n\ [Exit above.]\n\ \n\ GRATIANO.\n\ Now, by my hood, a Gentile, and no Jew.\n\ \n\ LORENZO.\n\ Beshrew me, but I love her heartily;\n\ For she is wise, if I can judge of her,\n\ And fair she is, if that mine eyes be true,\n\ And true she is, as she hath prov\'d herself;\n\ And therefore, like herself, wise, fair, and true,\n\ Shall she be placed in my constant soul.\n\ \n\ [Enter JESSICA.]\n\ \n\ What, art thou come? On, gentlemen, away!\n\ Our masquing mates by this time for us stay.\n\ \n\ [Exit with JESSICA and SALARINO.]\n\ \n\ [Enter ANTONIO]\n\ \n\ ANTONIO.\n\ Who\'s there?\n\ \n\ GRATIANO.\n\ Signior Antonio!\n\ \n\ ANTONIO.\n\ Fie, fie, Gratiano! where are all the rest?\n\ \'Tis nine o\'clock; our friends all stay for you.\n\ No masque to-night: the wind is come about;\n\ Bassanio presently will go aboard:\n\ I have sent twenty out to seek for you.\n\ \n\ GRATIANO.\n\ I am glad on\'t: I desire no more delight\n\ Than to be under sail and gone to-night.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ SCENE 7. Belmont. A room in PORTIA\'s house.\n\ \n\ [Flourish of cornets. Enter PORTIA, with the PRINCE OF MOROCCO,\n\ and their trains.]\n\ \n\ PORTIA.\n\ Go draw aside the curtains and discover\n\ The several caskets to this noble prince.\n\ Now make your choice.\n\ \n\ PRINCE OF MOROCCO.\n\ The first, of gold, who this inscription bears:\n\ \'Who chooseth me shall gain what many men desire.\'\n\ The second, silver, which this promise carries:\n\ \'Who chooseth me shall get as much as he deserves.\'\n\ This third, dull lead, with warning all as blunt:\n\ \'Who chooseth me must give and hazard all he hath.\'\n\ How shall I know if I do choose the right?\n\ \n\ PORTIA.\n\ The one of them contains my picture, prince;\n\ If you choose that, then I am yours withal.\n\ \n\ PRINCE OF MOROCCO.\n\ Some god direct my judgment! Let me see;\n\ I will survey the inscriptions back again.\n\ What says this leaden casket?\n\ \'Who chooseth me must give and hazard all he hath.\'\n\ Must give: for what? For lead? Hazard for lead!\n\ This casket threatens; men that hazard all\n\ Do it in hope of fair advantages:\n\ A golden mind stoops not to shows of dross;\n\ I\'ll then nor give nor hazard aught for lead.\n\ What says the silver with her virgin hue?\n\ \'Who chooseth me shall get as much as he deserves.\'\n\ As much as he deserves! Pause there, Morocco,\n\ And weigh thy value with an even hand.\n\ If thou be\'st rated by thy estimation,\n\ Thou dost deserve enough, and yet enough\n\ May not extend so far as to the lady;\n\ And yet to be afeard of my deserving\n\ Were but a weak disabling of myself.\n\ As much as I deserve! Why, that\'s the lady:\n\ I do in birth deserve her, and in fortunes,\n\ In graces, and in qualities of breeding;\n\ But more than these, in love I do deserve.\n\ What if I stray\'d no farther, but chose here?\n\ Let\'s see once more this saying grav\'d in gold:\n\ \'Who chooseth me shall gain what many men desire.\'\n\ Why, that\'s the lady: all the world desires her;\n\ From the four corners of the earth they come,\n\ To kiss this shrine, this mortal-breathing saint:\n\ The Hyrcanian deserts and the vasty wilds\n\ Of wide Arabia are as throughfares now\n\ For princes to come view fair Portia:\n\ The watery kingdom, whose ambitious head\n\ Spits in the face of heaven, is no bar\n\ To stop the foreign spirits, but they come\n\ As o\'er a brook to see fair Portia.\n\ One of these three contains her heavenly picture.\n\ Is\'t like that lead contains her? \'Twere damnation\n\ To think so base a thought; it were too gross\n\ To rib her cerecloth in the obscure grave.\n\ Or shall I think in silver she\'s immur\'d,\n\ Being ten times undervalu\'d to tried gold?\n\ O sinful thought! Never so rich a gem\n\ Was set in worse than gold. They have in England\n\ A coin that bears the figure of an angel\n\ Stamped in gold; but that\'s insculp\'d upon;\n\ But here an angel in a golden bed\n\ Lies all within. Deliver me the key;\n\ Here do I choose, and thrive I as I may!\n\ \n\ PORTIA.\n\ There, take it, prince, and if my form lie there,\n\ Then I am yours.\n\ \n\ [He unlocks the golden casket.]\n\ \n\ PRINCE OF MOROCCO.\n\ O hell! what have we here?\n\ A carrion Death, within whose empty eye\n\ There is a written scroll! I\'ll read the writing.\n\ \n\ \'All that glisters is not gold,\n\ Often have you heard that told;\n\ Many a man his life hath sold\n\ But my outside to behold:\n\ Gilded tombs do worms infold.\n\ Had you been as wise as bold,\n\ Young in limbs, in judgment old,\n\ Your answer had not been inscroll\'d:\n\ Fare you well, your suit is cold.\'\n\ \n\ Cold indeed; and labour lost:\n\ Then, farewell, heat, and welcome, frost!\n\ Portia, adieu! I have too griev\'d a heart\n\ To take a tedious leave; thus losers part.\n\ \n\ [Exit with his train. Flourish of cornets.]\n\ \n\ PORTIA.\n\ A gentle riddance. Draw the curtains: go.\n\ Let all of his complexion choose me so.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ SCENE 8. Venice. A street\n\ \n\ [Enter SALARINO and SALANIO.]\n\ \n\ SALARINO.\n\ Why, man, I saw Bassanio under sail;\n\ With him is Gratiano gone along;\n\ And in their ship I am sure Lorenzo is not.\n\ \n\ SALANIO.\n\ The villain Jew with outcries rais\'d the Duke,\n\ Who went with him to search Bassanio\'s ship.\n\ \n\ SALARINO.\n\ He came too late, the ship was under sail;\n\ But there the duke was given to understand\n\ That in a gondola were seen together\n\ Lorenzo and his amorous Jessica.\n\ Besides, Antonio certified the duke\n\ They were not with Bassanio in his ship.\n\ \n\ SALANIO.\n\ I never heard a passion so confus\'d,\n\ So strange, outrageous, and so variable,\n\ As the dog Jew did utter in the streets.\n\ \'My daughter! O my ducats! O my daughter!\n\ Fled with a Christian! O my Christian ducats!\n\ Justice! the law! my ducats and my daughter!\n\ A sealed bag, two sealed bags of ducats,\n\ Of double ducats, stol\'n from me by my daughter!\n\ And jewels! two stones, two rich and precious stones,\n\ Stol\'n by my daughter! Justice! find the girl!\n\ She hath the stones upon her and the ducats.\'\n\ \n\ SALARINO.\n\ Why, all the boys in Venice follow him,\n\ Crying, his stones, his daughter, and his ducats.\n\ \n\ SALANIO.\n\ Let good Antonio look he keep his day,\n\ Or he shall pay for this.\n\ \n\ SALARINO.\n\ Marry, well remember\'d.\n\ I reason\'d with a Frenchman yesterday,\n\ Who told me,--in the narrow seas that part\n\ The French and English,--there miscarried\n\ A vessel of our country richly fraught.\n\ I thought upon Antonio when he told me,\n\ And wish\'d in silence that it were not his.\n\ \n\ SALANIO.\n\ You were best to tell Antonio what you hear;\n\ Yet do not suddenly, for it may grieve him.\n\ \n\ SALARINO.\n\ A kinder gentleman treads not the earth.\n\ I saw Bassanio and Antonio part:\n\ Bassanio told him he would make some speed\n\ Of his return. He answer\'d \'Do not so;\n\ Slubber not business for my sake, Bassanio,\n\ But stay the very riping of the time;\n\ And for the Jew\'s bond which he hath of me,\n\ Let it not enter in your mind of love:\n\ Be merry, and employ your chiefest thoughts\n\ To courtship, and such fair ostents of love\n\ As shall conveniently become you there.\'\n\ And even there, his eye being big with tears,\n\ Turning his face, he put his hand behind him,\n\ And with affection wondrous sensible\n\ He wrung Bassanio\'s hand; and so they parted.\n\ \n\ SALANIO.\n\ I think he only loves the world for him.\n\ I pray thee, let us go and find him out,\n\ And quicken his embraced heaviness\n\ With some delight or other.\n\ \n\ SALARINO.\n\ Do we so.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ SCENE 9. Belmont. A room in PORTIA\'s house.\n\ \n\ [Enter NERISSA, with a SERVITOR.]\n\ \n\ NERISSA.\n\ Quick, quick, I pray thee, draw the curtain straight;\n\ The Prince of Arragon hath ta\'en his oath,\n\ And comes to his election presently.\n\ \n\ [Flourish of cornets. Enter the PRINCE OF ARRAGON, PORTIA, and\n\ their Trains.]\n\ \n\ PORTIA.\n\ Behold, there stand the caskets, noble Prince:\n\ If you choose that wherein I am contain\'d,\n\ Straight shall our nuptial rites be solemniz\'d;\n\ But if you fail, without more speech, my lord,\n\ You must be gone from hence immediately.\n\ \n\ ARRAGON.\n\ I am enjoin\'d by oath to observe three things:\n\ First, never to unfold to any one\n\ Which casket \'twas I chose; next, if I fail\n\ Of the right casket, never in my life\n\ To woo a maid in way of marriage;\n\ Lastly,\n\ If I do fail in fortune of my choice,\n\ Immediately to leave you and be gone.\n\ \n\ PORTIA.\n\ To these injunctions every one doth swear\n\ That comes to hazard for my worthless self.\n\ \n\ ARRAGON.\n\ And so have I address\'d me. Fortune now\n\ To my heart\'s hope! Gold, silver, and base lead.\n\ \'Who chooseth me must give and hazard all he hath.\'\n\ You shall look fairer ere I give or hazard.\n\ What says the golden chest? Ha! let me see:\n\ \'Who chooseth me shall gain what many men desire.\'\n\ What many men desire! that \'many\' may be meant\n\ By the fool multitude, that choose by show,\n\ Not learning more than the fond eye doth teach;\n\ Which pries not to th\' interior, but, like the martlet,\n\ Builds in the weather on the outward wall,\n\ Even in the force and road of casualty.\n\ I will not choose what many men desire,\n\ Because I will not jump with common spirits\n\ And rank me with the barbarous multitudes.\n\ Why, then to thee, thou silver treasure-house;\n\ Tell me once more what title thou dost bear:\n\ \'Who chooseth me shall get as much as he deserves.\'\n\ And well said too; for who shall go about\n\ To cozen fortune, and be honourable\n\ Without the stamp of merit? Let none presume\n\ To wear an undeserved dignity.\n\ O! that estates, degrees, and offices\n\ Were not deriv\'d corruptly, and that clear honour\n\ Were purchas\'d by the merit of the wearer!\n\ How many then should cover that stand bare;\n\ How many be commanded that command;\n\ How much low peasantry would then be glean\'d\n\ From the true seed of honour; and how much honour\n\ Pick\'d from the chaff and ruin of the times\n\ To be new varnish\'d! Well, but to my choice:\n\ \'Who chooseth me shall get as much as he deserves.\'\n\ I will assume desert. Give me a key for this,\n\ And instantly unlock my fortunes here.\n\ \n\ [He opens the silver casket.]\n\ \n\ PORTIA.\n\ Too long a pause for that which you find there.\n\ \n\ ARRAGON.\n\ What\'s here? The portrait of a blinking idiot,\n\ Presenting me a schedule! I will read it.\n\ How much unlike art thou to Portia!\n\ How much unlike my hopes and my deservings!\n\ \'Who chooseth me shall have as much as he deserves.\'\n\ Did I deserve no more than a fool\'s head?\n\ Is that my prize? Are my deserts no better?\n\ \n\ PORTIA.\n\ To offend, and judge, are distinct offices,\n\ And of opposed natures.\n\ \n\ ARRAGON.\n\ What is here?\n\ \n\ \'The fire seven times tried this;\n\ Seven times tried that judgment is\n\ That did never choose amiss.\n\ Some there be that shadows kiss;\n\ Such have but a shadow\'s bliss;\n\ There be fools alive, I wis,\n\ Silver\'d o\'er, and so was this.\n\ Take what wife you will to bed,\n\ I will ever be your head:\n\ So be gone; you are sped.\'\n\ \n\ Still more fool I shall appear\n\ By the time I linger here;\n\ With one fool\'s head I came to woo,\n\ But I go away with two.\n\ Sweet, adieu! I\'ll keep my oath,\n\ Patiently to bear my wroth.\n\ \n\ [Exit ARAGON with his train.]\n\ \n\ PORTIA.\n\ Thus hath the candle sing\'d the moth.\n\ O, these deliberate fools! When they do choose,\n\ They have the wisdom by their wit to lose.\n\ \n\ NERISSA.\n\ The ancient saying is no heresy:\n\ \'Hanging and wiving goes by destiny.\'\n\ \n\ PORTIA.\n\ Come, draw the curtain, Nerissa.\n\ \n\ [Enter a SERVANT.]\n\ \n\ SERVANT.\n\ Where is my lady?\n\ \n\ PORTIA.\n\ Here; what would my lord?\n\ \n\ SERVANT.\n\ Madam, there is alighted at your gate\n\ A young Venetian, one that comes before\n\ To signify th\' approaching of his lord;\n\ From whom he bringeth sensible regreets;\n\ To wit,--besides commends and courteous breath,--\n\ Gifts of rich value. Yet I have not seen\n\ So likely an ambassador of love.\n\ A day in April never came so sweet,\n\ To show how costly summer was at hand,\n\ As this fore-spurrer comes before his lord.\n\ \n\ PORTIA.\n\ No more, I pray thee; I am half afeard\n\ Thou wilt say anon he is some kin to thee,\n\ Thou spend\'st such high-day wit in praising him.\n\ Come, come, Nerissa, for I long to see\n\ Quick Cupid\'s post that comes so mannerly.\n\ \n\ NERISSA.\n\ Bassanio, lord Love, if thy will it be!\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ ACT 3.\n\ \n\ SCENE I. Venice. A street\n\ \n\ [Enter SALANIO and SALARINO.]\n\ \n\ SALANIO.\n\ Now, what news on the Rialto?\n\ \n\ SALARINO.\n\ Why, yet it lives there unchecked that Antonio hath a ship\n\ of rich lading wrack\'d on the narrow seas; the Goodwins, I think\n\ they call the place, a very dangerous flat and fatal, where the\n\ carcasses of many a tall ship lie buried, as they say, if my\n\ gossip Report be an honest woman of her word.\n\ \n\ SALANIO.\n\ I would she were as lying a gossip in that as ever knapped\n\ ginger or made her neighbours believe she wept for the death of a\n\ third husband. But it is true,--without any slips of prolixity or\n\ crossing the plain highway of talk,--that the good Antonio, the\n\ honest Antonio,--O that I had a title good enough to keep his\n\ name\n\ company!--\n\ \n\ SALARINO.\n\ Come, the full stop.\n\ \n\ SALANIO.\n\ Ha! What sayest thou? Why, the end is, he hath lost a\n\ ship.\n\ \n\ SALARINO.\n\ I would it might prove the end of his losses.\n\ \n\ SALANIO.\n\ Let me say \'amen\' betimes, lest the devil cross my prayer,\n\ for here he comes in the likeness of a Jew.\n\ \n\ [Enter SHYLOCK.]\n\ \n\ How now, Shylock! What news among the merchants?\n\ \n\ SHYLOCK.\n\ You knew, none so well, none so well as you, of my\n\ daughter\'s flight.\n\ \n\ SALARINO.\n\ That\'s certain; I, for my part, knew the tailor that made\n\ the wings she flew withal.\n\ \n\ SALANIO.\n\ And Shylock, for his own part, knew the bird was fledged;\n\ and then it is the complexion of them all to leave the dam.\n\ \n\ SHYLOCK.\n\ She is damned for it.\n\ \n\ SALARINO.\n\ That\'s certain, if the devil may be her judge.\n\ \n\ SHYLOCK.\n\ My own flesh and blood to rebel!\n\ \n\ SALANIO.\n\ Out upon it, old carrion! Rebels it at these years?\n\ \n\ SHYLOCK.\n\ I say my daughter is my flesh and my blood.\n\ \n\ SALARINO.\n\ There is more difference between thy flesh and hers than\n\ between jet and ivory; more between your bloods than there is\n\ between red wine and Rhenish. But tell us, do you hear whether\n\ Antonio have had any loss at sea or no?\n\ \n\ SHYLOCK.\n\ There I have another bad match: a bankrupt, a prodigal,\n\ who dare scarce show his head on the Rialto; a beggar, that used\n\ to come so smug upon the mart; let him look to his bond: he\n\ was wont to call me usurer; let him look to his bond: he was wont\n\ to lend money for a Christian courtesy; let him look to his bond.\n\ \n\ SALARINO.\n\ Why, I am sure, if he forfeit, thou wilt not take his\n\ flesh: what\'s that good for?\n\ \n\ SHYLOCK.\n\ To bait fish withal: if it will feed nothing else, it will\n\ feed my revenge. He hath disgrac\'d me and hind\'red me half a\n\ million; laugh\'d at my losses, mock\'d at my gains, scorned my\n\ nation, thwarted my bargains, cooled my friends, heated mine\n\ enemies. And what\'s his reason? I am a Jew. Hath not a Jew eyes?\n\ Hath not a Jew hands, organs, dimensions, senses, affections,\n\ passions, fed with the same food, hurt with the same weapons,\n\ subject to the same diseases, healed by the same means, warmed\n\ and cooled by the same winter and summer, as a Christian is? If\n\ you prick us, do we not bleed? If you tickle us, do we not laugh?\n\ If you poison us, do we not die? And if you wrong us, shall we\n\ not revenge? If we are like you in the rest, we will resemble you\n\ in that. If a Jew wrong a Christian, what is his humility?\n\ Revenge. If a Christian wrong a Jew, what should his sufferance\n\ be by Christian example? Why, revenge. The villaiy you teach me\n\ I will execute; and it shall go hard but I will better the\n\ instruction.\n\ \n\ [Enter a Servant.]\n\ \n\ SERVANT.\n\ Gentlemen, my master Antonio is at his house, and desires to\n\ speak with you both.\n\ \n\ SALARINO.\n\ We have been up and down to seek him.\n\ \n\ [Enter TUBAL.]\n\ \n\ SALANIO.\n\ Here comes another of the tribe: a third cannot be\n\ match\'d, unless the devil himself turn Jew.\n\ \n\ [Exeunt SALANIO, SALARINO, and Servant.]\n\ \n\ SHYLOCK.\n\ How now, Tubal! what news from Genoa? Hast thou found my\n\ daughter?\n\ \n\ TUBAL.\n\ I often came where I did hear of her, but cannot find her.\n\ \n\ SHYLOCK.\n\ Why there, there, there, there! A diamond gone, cost me\n\ two thousand ducats in Frankfort! The curse never fell upon our\n\ nation till now; I never felt it till now. Two thousand ducats in\n\ that, and other precious, precious jewels. I would my daughter\n\ were dead at my foot, and the jewels in her ear; would she were\n\ hearsed at my foot, and the ducats in her coffin! No news of\n\ them? Why, so: and I know not what\'s spent in the search. Why,\n\ thou--loss upon loss! The thief gone with so much, and so much to\n\ find the thief; and no satisfaction, no revenge; nor no ill luck\n\ stirring but what lights on my shoulders; no sighs but of my\n\ breathing; no tears but of my shedding.\n\ \n\ TUBAL.\n\ Yes, other men have ill luck too. Antonio, as I heard in\n\ Genoa,--\n\ \n\ SHYLOCK.\n\ What, what, what? Ill luck, ill luck?\n\ \n\ TUBAL.\n\ --hath an argosy cast away, coming from Tripolis.\n\ \n\ SHYLOCK.\n\ I thank God! I thank God! Is it true, is it true?\n\ \n\ TUBAL.\n\ I spoke with some of the sailors that escaped the wrack.\n\ \n\ SHYLOCK.\n\ I thank thee, good Tubal. Good news, good news! ha, ha!\n\ Where? in Genoa?\n\ \n\ TUBAL.\n\ Your daughter spent in Genoa, as I heard, one night,\n\ fourscore ducats.\n\ \n\ SHYLOCK.\n\ Thou stick\'st a dagger in me: I shall never see my gold\n\ again: fourscore ducats at a sitting! Fourscore ducats!\n\ \n\ TUBAL.\n\ There came divers of Antonio\'s creditors in my company to\n\ Venice that swear he cannot choose but break.\n\ \n\ SHYLOCK.\n\ I am very glad of it; I\'ll plague him, I\'ll torture him; I\n\ am glad of it.\n\ \n\ TUBAL.\n\ One of them showed me a ring that he had of your daughter\n\ for a monkey.\n\ \n\ SHYLOCK.\n\ Out upon her! Thou torturest me, Tubal: It was my\n\ turquoise; I had it of Leah when I was a bachelor; I would not\n\ have given it for a wilderness of monkeys.\n\ \n\ TUBAL.\n\ But Antonio is certainly undone.\n\ \n\ SHYLOCK.\n\ Nay, that\'s true; that\'s very true. Go, Tubal, fee me an\n\ officer; bespeak him a fortnight before. I will have the heart of\n\ him, if he forfeit; for, were he out of Venice, I can make what\n\ merchandise I will. Go, Tubal, and meet me at our synagogue; go,\n\ good Tubal; at our synagogue, Tubal.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ SCENE 2. Belmont. A room in PORTIA\'s house.\n\ \n\ [Enter BASSANIO, PORTIA, GRATIANO, NERISSA, and Attendants.]\n\ \n\ PORTIA.\n\ I pray you tarry; pause a day or two\n\ Before you hazard; for, in choosing wrong,\n\ I lose your company; therefore forbear a while.\n\ There\'s something tells me, but it is not love,\n\ I would not lose you; and you know yourself\n\ Hate counsels not in such a quality.\n\ But lest you should not understand me well,--\n\ And yet a maiden hath no tongue but thought,--\n\ I would detain you here some month or two\n\ Before you venture for me. I could teach you\n\ How to choose right, but then I am forsworn;\n\ So will I never be; so may you miss me;\n\ But if you do, you\'ll make me wish a sin,\n\ That I had been forsworn. Beshrew your eyes,\n\ They have o\'erlook\'d me and divided me:\n\ One half of me is yours, the other half yours,\n\ Mine own, I would say; but if mine, then yours,\n\ And so all yours. O! these naughty times\n\ Puts bars between the owners and their rights;\n\ And so, though yours, not yours. Prove it so,\n\ Let fortune go to hell for it, not I.\n\ I speak too long, but \'tis to peise the time,\n\ To eke it, and to draw it out in length,\n\ To stay you from election.\n\ \n\ BASSANIO.\n\ Let me choose;\n\ For as I am, I live upon the rack.\n\ \n\ PORTIA.\n\ Upon the rack, Bassanio! Then confess\n\ What treason there is mingled with your love.\n\ \n\ BASSANIO.\n\ None but that ugly treason of mistrust,\n\ Which makes me fear th\' enjoying of my love:\n\ There may as well be amity and life\n\ \'Tween snow and fire as treason and my love.\n\ \n\ PORTIA.\n\ Ay, but I fear you speak upon the rack,\n\ Where men enforced do speak anything.\n\ \n\ BASSANIO.\n\ Promise me life, and I\'ll confess the truth.\n\ \n\ PORTIA.\n\ Well then, confess and live.\n\ \n\ BASSANIO.\n\ \'Confess\' and \'love\'\n\ Had been the very sum of my confession:\n\ O happy torment, when my torturer\n\ Doth teach me answers for deliverance!\n\ But let me to my fortune and the caskets.\n\ \n\ PORTIA.\n\ Away, then! I am lock\'d in one of them:\n\ If you do love me, you will find me out.\n\ Nerissa and the rest, stand all aloof;\n\ Let music sound while he doth make his choice;\n\ Then, if he lose, he makes a swan-like end,\n\ Fading in music: that the comparison\n\ May stand more proper, my eye shall be the stream\n\ And watery death-bed for him. He may win;\n\ And what is music then? Then music is\n\ Even as the flourish when true subjects bow\n\ To a new-crowned monarch; such it is\n\ As are those dulcet sounds in break of day\n\ That creep into the dreaming bridegroom\'s ear\n\ And summon him to marriage. Now he goes,\n\ With no less presence, but with much more love,\n\ Than young Alcides when he did redeem\n\ The virgin tribute paid by howling Troy\n\ To the sea-monster: I stand for sacrifice;\n\ The rest aloof are the Dardanian wives,\n\ With bleared visages come forth to view\n\ The issue of th\' exploit. Go, Hercules!\n\ Live thou, I live. With much much more dismay\n\ I view the fight than thou that mak\'st the fray.\n\ \n\ [A Song, whilst BASSANIO comments on the caskets to himself.]\n\ \n\ Tell me where is fancy bred,\n\ Or in the heart or in the head,\n\ How begot, how nourished?\n\ Reply, reply.\n\ \n\ \n\ It is engend\'red in the eyes,\n\ With gazing fed; and fancy dies\n\ In the cradle where it lies.\n\ Let us all ring fancy\'s knell:\n\ I\'ll begin it.--Ding, dong, bell.\n\ \n\ [ALL.] Ding, dong, bell.\n\ \n\ BASSANIO.\n\ So may the outward shows be least themselves:\n\ The world is still deceiv\'d with ornament.\n\ In law, what plea so tainted and corrupt\n\ But, being season\'d with a gracious voice,\n\ Obscures the show of evil? In religion,\n\ What damned error but some sober brow\n\ Will bless it, and approve it with a text,\n\ Hiding the grossness with fair ornament?\n\ There is no vice so simple but assumes\n\ Some mark of virtue on his outward parts.\n\ How many cowards, whose hearts are all as false\n\ As stairs of sand, wear yet upon their chins\n\ The beards of Hercules and frowning Mars;\n\ Who, inward search\'d, have livers white as milk;\n\ And these assume but valour\'s excrement\n\ To render them redoubted! Look on beauty\n\ And you shall see \'tis purchas\'d by the weight:\n\ Which therein works a miracle in nature,\n\ Making them lightest that wear most of it:\n\ So are those crisped snaky golden locks\n\ Which make such wanton gambols with the wind,\n\ Upon supposed fairness, often known\n\ To be the dowry of a second head,\n\ The skull that bred them, in the sepulchre.\n\ Thus ornament is but the guiled shore\n\ To a most dangerous sea; the beauteous scarf\n\ Veiling an Indian beauty; in a word,\n\ The seeming truth which cunning times put on\n\ To entrap the wisest. Therefore, thou gaudy gold,\n\ Hard food for Midas, I will none of thee;\n\ Nor none of thee, thou pale and common drudge\n\ \'Tween man and man: but thou, thou meagre lead,\n\ Which rather threaten\'st than dost promise aught,\n\ Thy plainness moves me more than eloquence,\n\ And here choose I: joy be the consequence!\n\ \n\ PORTIA.\n\ [Aside] How all the other passions fleet to air,\n\ As doubtful thoughts, and rash-embrac\'d despair,\n\ And shuddering fear, and green-ey\'d jealousy!\n\ O love! be moderate; allay thy ecstasy;\n\ In measure rain thy joy; scant this excess;\n\ I feel too much thy blessing; make it less,\n\ For fear I surfeit!\n\ \n\ BASSANIO.\n\ What find I here? [Opening the leaden casket.]\n\ Fair Portia\'s counterfeit! What demi-god\n\ Hath come so near creation? Move these eyes?\n\ Or whether riding on the balls of mine,\n\ Seem they in motion? Here are sever\'d lips,\n\ Parted with sugar breath; so sweet a bar\n\ Should sunder such sweet friends. Here in her hairs\n\ The painter plays the spider, and hath woven\n\ A golden mesh t\' entrap the hearts of men\n\ Faster than gnats in cobwebs: but her eyes!--\n\ How could he see to do them? Having made one,\n\ Methinks it should have power to steal both his,\n\ And leave itself unfurnish\'d: yet look, how far\n\ The substance of my praise doth wrong this shadow\n\ In underprizing it, so far this shadow\n\ Doth limp behind the substance. Here\'s the scroll,\n\ The continent and summary of my fortune.\n\ \n\ \'You that choose not by the view,\n\ Chance as fair and choose as true!\n\ Since this fortune falls to you,\n\ Be content and seek no new.\n\ If you be well pleas\'d with this,\n\ And hold your fortune for your bliss,\n\ Turn to where your lady is\n\ And claim her with a loving kiss.\'\n\ \n\ A gentle scroll. Fair lady, by your leave; {Kissing her.]\n\ I come by note, to give and to receive.\n\ Like one of two contending in a prize,\n\ That thinks he hath done well in people\'s eyes,\n\ Hearing applause and universal shout,\n\ Giddy in spirit, still gazing in a doubt\n\ Whether those peals of praise be his or no;\n\ So, thrice-fair lady, stand I, even so,\n\ As doubtful whether what I see be true,\n\ Until confirm\'d, sign\'d, ratified by you.\n\ \n\ PORTIA.\n\ You see me, Lord Bassanio, where I stand,\n\ Such as I am: though for myself alone\n\ I would not be ambitious in my wish\n\ To wish myself much better, yet for you\n\ I would be trebled twenty times myself,\n\ A thousand times more fair, ten thousand times\n\ More rich;\n\ That only to stand high in your account,\n\ I might in virtues, beauties, livings, friends,\n\ Exceed account. But the full sum of me\n\ Is sum of something which, to term in gross,\n\ Is an unlesson\'d girl, unschool\'d, unpractis\'d;\n\ Happy in this, she is not yet so old\n\ But she may learn; happier than this,\n\ She is not bred so dull but she can learn;\n\ Happiest of all is that her gentle spirit\n\ Commits itself to yours to be directed,\n\ As from her lord, her governor, her king.\n\ Myself and what is mine to you and yours\n\ Is now converted. But now I was the lord\n\ Of this fair mansion, master of my servants,\n\ Queen o\'er myself; and even now, but now,\n\ This house, these servants, and this same myself,\n\ Are yours- my lord\'s. I give them with this ring,\n\ Which when you part from, lose, or give away,\n\ Let it presage the ruin of your love,\n\ And be my vantage to exclaim on you.\n\ \n\ BASSANIO.\n\ Madam, you have bereft me of all words,\n\ Only my blood speaks to you in my veins;\n\ And there is such confusion in my powers\n\ As, after some oration fairly spoke\n\ By a beloved prince, there doth appear\n\ Among the buzzing pleased multitude;\n\ Where every something, being blent together,\n\ Turns to a wild of nothing, save of joy,\n\ Express\'d and not express\'d. But when this ring\n\ Parts from this finger, then parts life from hence:\n\ O! then be bold to say Bassanio\'s dead.\n\ \n\ NERISSA.\n\ My lord and lady, it is now our time,\n\ That have stood by and seen our wishes prosper,\n\ To cry, good joy. Good joy, my lord and lady!\n\ \n\ GRATIANO.\n\ My Lord Bassanio, and my gentle lady,\n\ I wish you all the joy that you can wish;\n\ For I am sure you can wish none from me;\n\ And when your honours mean to solemnize\n\ The bargain of your faith, I do beseech you\n\ Even at that time I may be married too.\n\ \n\ BASSANIO.\n\ With all my heart, so thou canst get a wife.\n\ \n\ GRATIANO.\n\ I thank your lordship, you have got me one.\n\ My eyes, my lord, can look as swift as yours:\n\ You saw the mistress, I beheld the maid;\n\ You lov\'d, I lov\'d; for intermission\n\ No more pertains to me, my lord, than you.\n\ Your fortune stood upon the caskets there,\n\ And so did mine too, as the matter falls;\n\ For wooing here until I sweat again,\n\ And swearing till my very roof was dry\n\ With oaths of love, at last, if promise last,\n\ I got a promise of this fair one here\n\ To have her love, provided that your fortune\n\ Achiev\'d her mistress.\n\ \n\ PORTIA.\n\ Is this true, Nerissa?\n\ \n\ NERISSA.\n\ Madam, it is, so you stand pleas\'d withal.\n\ \n\ BASSANIO.\n\ And do you, Gratiano, mean good faith?\n\ \n\ GRATIANO.\n\ Yes, faith, my lord.\n\ \n\ BASSANIO.\n\ Our feast shall be much honour\'d in your marriage.\n\ \n\ GRATIANO.\n\ We\'ll play with them the first boy for a thousand\n\ ducats.\n\ \n\ NERISSA.\n\ What! and stake down?\n\ \n\ GRATIANO.\n\ No; we shall ne\'er win at that sport, and stake down.\n\ But who comes here? Lorenzo and his infidel?\n\ What, and my old Venetian friend, Salanio!\n\ \n\ [Enter LORENZO, JESSICA, and SALANIO.]\n\ \n\ BASSANIO.\n\ Lorenzo and Salanio, welcome hither,\n\ If that the youth of my new interest here\n\ Have power to bid you welcome. By your leave,\n\ I bid my very friends and countrymen,\n\ Sweet Portia, welcome.\n\ \n\ PORTIA.\n\ So do I, my lord;\n\ They are entirely welcome.\n\ \n\ LORENZO.\n\ I thank your honour. For my part, my lord,\n\ My purpose was not to have seen you here;\n\ But meeting with Salanio by the way,\n\ He did entreat me, past all saying nay,\n\ To come with him along.\n\ \n\ SALANIO.\n\ I did, my lord,\n\ And I have reason for it. Signior Antonio\n\ Commends him to you.\n\ \n\ [Gives BASSANIO a letter]\n\ \n\ BASSANIO.\n\ Ere I ope his letter,\n\ I pray you tell me how my good friend doth.\n\ \n\ SALANIO.\n\ Not sick, my lord, unless it be in mind;\n\ Nor well, unless in mind; his letter there\n\ Will show you his estate.\n\ \n\ GRATIANO.\n\ Nerissa, cheer yon stranger; bid her welcome.\n\ Your hand, Salanio. What\'s the news from Venice?\n\ How doth that royal merchant, good Antonio?\n\ I know he will be glad of our success:\n\ We are the Jasons, we have won the fleece.\n\ \n\ SALANIO.\n\ I would you had won the fleece that he hath lost.\n\ \n\ PORTIA.\n\ There are some shrewd contents in yon same paper.\n\ That steal the colour from Bassanio\'s cheek:\n\ Some dear friend dead, else nothing in the world\n\ Could turn so much the constitution\n\ Of any constant man. What, worse and worse!\n\ With leave, Bassanio: I am half yourself,\n\ And I must freely have the half of anything\n\ That this same paper brings you.\n\ \n\ BASSANIO.\n\ O sweet Portia!\n\ Here are a few of the unpleasant\'st words\n\ That ever blotted paper. Gentle lady,\n\ When I did first impart my love to you,\n\ I freely told you all the wealth I had\n\ Ran in my veins, I was a gentleman;\n\ And then I told you true. And yet, dear lady,\n\ Rating myself at nothing, you shall see\n\ How much I was a braggart. When I told you\n\ My state was nothing, I should then have told you\n\ That I was worse than nothing; for indeed\n\ I have engag\'d myself to a dear friend,\n\ Engag\'d my friend to his mere enemy,\n\ To feed my means. Here is a letter, lady,\n\ The paper as the body of my friend,\n\ And every word in it a gaping wound\n\ Issuing life-blood. But is it true, Salanio?\n\ Hath all his ventures fail\'d? What, not one hit?\n\ From Tripolis, from Mexico, and England,\n\ From Lisbon, Barbary, and India?\n\ And not one vessel scape the dreadful touch\n\ Of merchant-marring rocks?\n\ \n\ SALANIO.\n\ Not one, my lord.\n\ Besides, it should appear that, if he had\n\ The present money to discharge the Jew,\n\ He would not take it. Never did I know\n\ A creature that did bear the shape of man,\n\ So keen and greedy to confound a man.\n\ He plies the duke at morning and at night,\n\ And doth impeach the freedom of the state,\n\ If they deny him justice. Twenty merchants,\n\ The duke himself, and the magnificoes\n\ Of greatest port, have all persuaded with him;\n\ But none can drive him from the envious plea\n\ Of forfeiture, of justice, and his bond.\n\ \n\ JESSICA.\n\ When I was with him, I have heard him swear\n\ To Tubal and to Chus, his countrymen,\n\ That he would rather have Antonio\'s flesh\n\ Than twenty times the value of the sum\n\ That he did owe him; and I know, my lord,\n\ If law, authority, and power, deny not,\n\ It will go hard with poor Antonio.\n\ \n\ PORTIA.\n\ Is it your dear friend that is thus in trouble?\n\ \n\ BASSANIO.\n\ The dearest friend to me, the kindest man,\n\ The best condition\'d and unwearied spirit\n\ In doing courtesies; and one in whom\n\ The ancient Roman honour more appears\n\ Than any that draws breath in Italy.\n\ \n\ PORTIA.\n\ What sum owes he the Jew?\n\ \n\ BASSANIO.\n\ For me, three thousand ducats.\n\ \n\ PORTIA.\n\ What! no more?\n\ Pay him six thousand, and deface the bond;\n\ Double six thousand, and then treble that,\n\ Before a friend of this description\n\ Shall lose a hair through Bassanio\'s fault.\n\ First go with me to church and call me wife,\n\ And then away to Venice to your friend;\n\ For never shall you lie by Portia\'s side\n\ With an unquiet soul. You shall have gold\n\ To pay the petty debt twenty times over:\n\ When it is paid, bring your true friend along.\n\ My maid Nerissa and myself meantime,\n\ Will live as maids and widows. Come, away!\n\ For you shall hence upon your wedding day.\n\ Bid your friends welcome, show a merry cheer;\n\ Since you are dear bought, I will love you dear.\n\ But let me hear the letter of your friend.\n\ \n\ BASSANIO.\n\ \'Sweet Bassanio, my ships have all miscarried,\n\ my creditors grow cruel, my estate is very low, my bond to the\n\ Jew is forfeit; and since, in paying it, it is impossible I\n\ should live, all debts are clear\'d between you and I, if I might\n\ but see you at my death. Notwithstanding, use your pleasure; if\n\ your love do not persuade you to come, let not my letter.\'\n\ \n\ PORTIA.\n\ O love, dispatch all business and be gone!\n\ \n\ BASSANIO.\n\ Since I have your good leave to go away,\n\ I will make haste; but, till I come again,\n\ No bed shall e\'er be guilty of my stay,\n\ Nor rest be interposer \'twixt us twain.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ SCENE 3. Venice. A street\n\ \n\ [Enter SHYLOCK, SALARINO, ANTONIO, and Gaoler.]\n\ \n\ SHYLOCK.\n\ Gaoler, look to him. Tell not me of mercy;\n\ This is the fool that lent out money gratis:\n\ Gaoler, look to him.\n\ \n\ ANTONIO.\n\ Hear me yet, good Shylock.\n\ \n\ SHYLOCK.\n\ I\'ll have my bond; speak not against my bond.\n\ I have sworn an oath that I will have my bond.\n\ Thou call\'dst me dog before thou hadst a cause,\n\ But, since I am a dog, beware my fangs;\n\ The Duke shall grant me justice. I do wonder,\n\ Thou naughty gaoler, that thou art so fond\n\ To come abroad with him at his request.\n\ \n\ ANTONIO.\n\ I pray thee hear me speak.\n\ \n\ SHYLOCK.\n\ I\'ll have my bond. I will not hear thee speak;\n\ I\'ll have my bond; and therefore speak no more.\n\ I\'ll not be made a soft and dull-eyed fool,\n\ To shake the head, relent, and sigh, and yield\n\ To Christian intercessors. Follow not;\n\ I\'ll have no speaking; I will have my bond.\n\ \n\ [Exit.]\n\ \n\ SALARINO.\n\ It is the most impenetrable cur\n\ That ever kept with men.\n\ \n\ ANTONIO.\n\ Let him alone;\n\ I\'ll follow him no more with bootless prayers.\n\ He seeks my life; his reason well I know:\n\ I oft deliver\'d from his forfeitures\n\ Many that have at times made moan to me;\n\ Therefore he hates me.\n\ \n\ SALARINO.\n\ I am sure the Duke\n\ Will never grant this forfeiture to hold.\n\ \n\ ANTONIO.\n\ The Duke cannot deny the course of law;\n\ For the commodity that strangers have\n\ With us in Venice, if it be denied,\n\ \'Twill much impeach the justice of the state,\n\ Since that the trade and profit of the city\n\ Consisteth of all nations. Therefore, go;\n\ These griefs and losses have so bated me\n\ That I shall hardly spare a pound of flesh\n\ To-morrow to my bloody creditor.\n\ Well, gaoler, on; pray God Bassanio come\n\ To see me pay his debt, and then I care not.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ SCENE 4. Belmont. A room in PORTIA\'s house.\n\ \n\ [Enter PORTIA, NERISSA, LORENZO, JESSICA, and BALTHASAR.]\n\ \n\ LORENZO.\n\ Madam, although I speak it in your presence,\n\ You have a noble and a true conceit\n\ Of godlike amity, which appears most strongly\n\ In bearing thus the absence of your lord.\n\ But if you knew to whom you show this honour,\n\ How true a gentleman you send relief,\n\ How dear a lover of my lord your husband,\n\ I know you would be prouder of the work\n\ Than customary bounty can enforce you.\n\ \n\ PORTIA.\n\ I never did repent for doing good,\n\ Nor shall not now; for in companions\n\ That do converse and waste the time together,\n\ Whose souls do bear an equal yoke of love,\n\ There must be needs a like proportion\n\ Of lineaments, of manners, and of spirit,\n\ Which makes me think that this Antonio,\n\ Being the bosom lover of my lord,\n\ Must needs be like my lord. If it be so,\n\ How little is the cost I have bestowed\n\ In purchasing the semblance of my soul\n\ From out the state of hellish cruelty!\n\ This comes too near the praising of myself;\n\ Therefore, no more of it; hear other things.\n\ Lorenzo, I commit into your hands\n\ The husbandry and manage of my house\n\ Until my lord\'s return; for mine own part,\n\ I have toward heaven breath\'d a secret vow\n\ To live in prayer and contemplation,\n\ Only attended by Nerissa here,\n\ Until her husband and my lord\'s return.\n\ There is a monastery two miles off,\n\ And there we will abide. I do desire you\n\ Not to deny this imposition,\n\ The which my love and some necessity\n\ Now lays upon you.\n\ \n\ LORENZO.\n\ Madam, with all my heart\n\ I shall obey you in an fair commands.\n\ \n\ PORTIA.\n\ My people do already know my mind,\n\ And will acknowledge you and Jessica\n\ In place of Lord Bassanio and myself.\n\ So fare you well till we shall meet again.\n\ \n\ LORENZO.\n\ Fair thoughts and happy hours attend on you!\n\ \n\ JESSICA.\n\ I wish your ladyship all heart\'s content.\n\ \n\ PORTIA.\n\ I thank you for your wish, and am well pleas\'d\n\ To wish it back on you. Fare you well, Jessica.\n\ \n\ [Exeunt JESSICA and LORENZO.]\n\ \n\ Now, Balthasar,\n\ As I have ever found thee honest-true,\n\ So let me find thee still. Take this same letter,\n\ And use thou all th\' endeavour of a man\n\ In speed to Padua; see thou render this\n\ Into my cousin\'s hands, Doctor Bellario;\n\ And look what notes and garments he doth give thee,\n\ Bring them, I pray thee, with imagin\'d speed\n\ Unto the traject, to the common ferry\n\ Which trades to Venice. Waste no time in words,\n\ But get thee gone; I shall be there before thee.\n\ \n\ BALTHASAR.\n\ Madam, I go with all convenient speed.\n\ \n\ [Exit.]\n\ \n\ PORTIA.\n\ Come on, Nerissa, I have work in hand\n\ That you yet know not of; we\'ll see our husbands\n\ Before they think of us.\n\ \n\ NERISSA.\n\ Shall they see us?\n\ \n\ PORTIA.\n\ They shall, Nerissa; but in such a habit\n\ That they shall think we are accomplished\n\ With that we lack. I\'ll hold thee any wager,\n\ When we are both accoutred like young men,\n\ I\'ll prove the prettier fellow of the two,\n\ And wear my dagger with the braver grace,\n\ And speak between the change of man and boy\n\ With a reed voice; and turn two mincing steps\n\ Into a manly stride; and speak of frays\n\ Like a fine bragging youth; and tell quaint lies,\n\ How honourable ladies sought my love,\n\ Which I denying, they fell sick and died;\n\ I could not do withal. Then I\'ll repent,\n\ And wish for all that, that I had not kill\'d them.\n\ And twenty of these puny lies I\'ll tell,\n\ That men shall swear I have discontinu\'d school\n\ About a twelvemonth. I have within my mind\n\ A thousand raw tricks of these bragging Jacks,\n\ Which I will practise.\n\ \n\ NERISSA.\n\ Why, shall we turn to men?\n\ \n\ PORTIA.\n\ Fie, what a question\'s that,\n\ If thou wert near a lewd interpreter!\n\ But come, I\'ll tell thee all my whole device\n\ When I am in my coach, which stays for us\n\ At the park gate; and therefore haste away,\n\ For we must measure twenty miles to-day.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ SCENE 5. The same. A garden.\n\ \n\ [Enter LAUNCELOT and JESSICA.]\n\ \n\ LAUNCELOT.\n\ Yes, truly; for, look you, the sins of the father are to\n\ be laid upon the children; therefore, I promise you, I fear you.\n\ I was always plain with you, and so now I speak my agitation of\n\ the matter; therefore be of good cheer, for truly I think you are\n\ damn\'d. There is but one hope in it that can do you any good, and\n\ that is but a kind of bastard hope neither.\n\ \n\ JESSICA.\n\ And what hope is that, I pray thee?\n\ \n\ LAUNCELOT.\n\ Marry, you may partly hope that your father got you not,\n\ that you are not the Jew\'s daughter.\n\ \n\ JESSICA.\n\ That were a kind of bastard hope indeed; so the sins of my\n\ mother should be visited upon me.\n\ \n\ LAUNCELOT.\n\ Truly then I fear you are damn\'d both by father and\n\ mother; thus when I shun Scylla, your father, I fall into\n\ Charybdis, your mother; well, you are gone both ways.\n\ \n\ JESSICA.\n\ I shall be saved by my husband; he hath made me a Christian.\n\ \n\ LAUNCELOT.\n\ Truly, the more to blame he; we were Christians enow\n\ before, e\'en as many as could well live one by another. This\n\ making of Christians will raise the price of hogs; if we grow all\n\ to be pork-eaters, we shall not shortly have a rasher on the\n\ coals for money.\n\ \n\ JESSICA.\n\ I\'ll tell my husband, Launcelot, what you say; here he comes.\n\ \n\ [Enter LORENZO.]\n\ \n\ LORENZO.\n\ I shall grow jealous of you shortly, Launcelot, if you\n\ thus get my wife into corners.\n\ \n\ JESSICA.\n\ Nay, you need nor fear us, Lorenzo; Launcelot and I are\n\ out; he tells me flatly there\'s no mercy for me in heaven,\n\ because I am a Jew\'s daughter; and he says you are no good member\n\ of the commonwealth, for in converting Jews to Christians you\n\ raise the price of pork.\n\ \n\ LORENZO.\n\ I shall answer that better to the commonwealth than you\n\ can the getting up of the negro\'s belly; the Moor is with child\n\ by you, Launcelot.\n\ \n\ LAUNCELOT.\n\ It is much that the Moor should be more than reason; but\n\ if she be less than an honest woman, she is indeed more than I\n\ took her for.\n\ \n\ LORENZO.\n\ How every fool can play upon the word! I think the best\n\ grace of wit will shortly turn into silence, and discourse grow\n\ commendable in none only but parrots. Go in, sirrah; bid them\n\ prepare for dinner.\n\ \n\ LAUNCELOT.\n\ That is done, sir; they have all stomachs.\n\ \n\ LORENZO.\n\ Goodly Lord, what a wit-snapper are you! Then bid them\n\ prepare dinner.\n\ \n\ LAUNCELOT.\n\ That is done too, sir, only \'cover\' is the word.\n\ \n\ LORENZO.\n\ Will you cover, then, sir?\n\ \n\ LAUNCELOT.\n\ Not so, sir, neither; I know my duty.\n\ \n\ LORENZO.\n\ Yet more quarrelling with occasion! Wilt thou show the\n\ whole wealth of thy wit in an instant? I pray thee understand a\n\ plain man in his plain meaning: go to thy fellows, bid them cover\n\ the table, serve in the meat, and we will come in to dinner.\n\ \n\ LAUNCELOT.\n\ For the table, sir, it shall be served in; for the meat,\n\ sir, it shall be covered; for your coming in to dinner, sir, why,\n\ let it be as humours and conceits shall govern.\n\ \n\ [Exit.]\n\ \n\ LORENZO.\n\ O dear discretion, how his words are suited!\n\ The fool hath planted in his memory\n\ An army of good words; and I do know\n\ A many fools that stand in better place,\n\ Garnish\'d like him, that for a tricksy word\n\ Defy the matter. How cheer\'st thou, Jessica?\n\ And now, good sweet, say thy opinion,\n\ How dost thou like the Lord Bassanio\'s wife?\n\ \n\ JESSICA.\n\ Past all expressing. It is very meet\n\ The Lord Bassanio live an upright life,\n\ For, having such a blessing in his lady,\n\ He finds the joys of heaven here on earth;\n\ And if on earth he do not merit it,\n\ In reason he should never come to heaven.\n\ Why, if two gods should play some heavenly match,\n\ And on the wager lay two earthly women,\n\ And Portia one, there must be something else\n\ Pawn\'d with the other; for the poor rude world\n\ Hath not her fellow.\n\ \n\ LORENZO.\n\ Even such a husband\n\ Hast thou of me as she is for a wife.\n\ \n\ JESSICA.\n\ Nay, but ask my opinion too of that.\n\ \n\ LORENZO.\n\ I will anon; first let us go to dinner.\n\ \n\ JESSICA.\n\ Nay, let me praise you while I have a stomach.\n\ \n\ LORENZO.\n\ No, pray thee, let it serve for table-talk;\n\ Then howsoe\'er thou speak\'st, \'mong other things\n\ I shall digest it.\n\ \n\ JESSICA.\n\ Well, I\'ll set you forth.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ ACT 4.\n\ \n\ SCENE I. Venice. A court of justice\n\ \n\ [Enter the DUKE: the Magnificoes; ANTONIO, BASSANIO, GRATIANO,\n\ SALARINO, SALANIO, and Others.]\n\ \n\ DUKE.\n\ What, is Antonio here?\n\ \n\ ANTONIO.\n\ Ready, so please your Grace.\n\ \n\ DUKE.\n\ I am sorry for thee; thou art come to answer\n\ A stony adversary, an inhuman wretch,\n\ Uncapable of pity, void and empty\n\ From any dram of mercy.\n\ \n\ ANTONIO.\n\ I have heard\n\ Your Grace hath ta\'en great pains to qualify\n\ His rigorous course; but since he stands obdurate,\n\ And that no lawful means can carry me\n\ Out of his envy\'s reach, I do oppose\n\ My patience to his fury, and am arm\'d\n\ To suffer with a quietness of spirit\n\ The very tyranny and rage of his.\n\ \n\ DUKE.\n\ Go one, and call the Jew into the court.\n\ \n\ SALARINO.\n\ He is ready at the door; he comes, my lord.\n\ \n\ [Enter SHYLOCK.]\n\ \n\ DUKE.\n\ Make room, and let him stand before our face.\n\ Shylock, the world thinks, and I think so too,\n\ That thou but leadest this fashion of thy malice\n\ To the last hour of act; and then, \'tis thought,\n\ Thou\'lt show thy mercy and remorse, more strange\n\ Than is thy strange apparent cruelty;\n\ And where thou now exacts the penalty,--\n\ Which is a pound of this poor merchant\'s flesh,--\n\ Thou wilt not only loose the forfeiture,\n\ But, touch\'d with human gentleness and love,\n\ Forgive a moiety of the principal,\n\ Glancing an eye of pity on his losses,\n\ That have of late so huddled on his back,\n\ Enow to press a royal merchant down,\n\ And pluck commiseration of his state\n\ From brassy bosoms and rough hearts of flint,\n\ From stubborn Turks and Tartars, never train\'d\n\ To offices of tender courtesy.\n\ We all expect a gentle answer, Jew.\n\ \n\ SHYLOCK.\n\ I have possess\'d your Grace of what I purpose,\n\ And by our holy Sabbath have I sworn\n\ To have the due and forfeit of my bond.\n\ If you deny it, let the danger light\n\ Upon your charter and your city\'s freedom.\n\ You\'ll ask me why I rather choose to have\n\ A weight of carrion flesh than to receive\n\ Three thousand ducats. I\'ll not answer that,\n\ But say it is my humour: is it answer\'d?\n\ What if my house be troubled with a rat,\n\ And I be pleas\'d to give ten thousand ducats\n\ To have it ban\'d? What, are you answer\'d yet?\n\ Some men there are love not a gaping pig;\n\ Some that are mad if they behold a cat;\n\ And others, when the bagpipe sings i\' the nose,\n\ Cannot contain their urine; for affection,\n\ Mistress of passion, sways it to the mood\n\ Of what it likes or loathes. Now, for your answer:\n\ As there is no firm reason to be render\'d,\n\ Why he cannot abide a gaping pig;\n\ Why he, a harmless necessary cat;\n\ Why he, a wauling bagpipe; but of force\n\ Must yield to such inevitable shame\n\ As to offend, himself being offended;\n\ So can I give no reason, nor I will not,\n\ More than a lodg\'d hate and a certain loathing\n\ I bear Antonio, that I follow thus\n\ A losing suit against him. Are you answered?\n\ \n\ BASSANIO.\n\ This is no answer, thou unfeeling man,\n\ To excuse the current of thy cruelty.\n\ \n\ SHYLOCK.\n\ I am not bound to please thee with my answer.\n\ \n\ BASSANIO.\n\ Do all men kill the things they do not love?\n\ \n\ SHYLOCK.\n\ Hates any man the thing he would not kill?\n\ \n\ BASSANIO.\n\ Every offence is not a hate at first.\n\ \n\ SHYLOCK.\n\ What! wouldst thou have a serpent sting thee twice?\n\ \n\ ANTONIO.\n\ I pray you, think you question with the Jew:\n\ You may as well go stand upon the beach,\n\ And bid the main flood bate his usual height;\n\ You may as well use question with the wolf,\n\ Why he hath made the ewe bleat for the lamb;\n\ You may as well forbid the mountain pines\n\ To wag their high tops and to make no noise\n\ When they are fretten with the gusts of heaven;\n\ You may as well do anything most hard\n\ As seek to soften that--than which what\'s harder?--\n\ His Jewish heart: therefore, I do beseech you,\n\ Make no moe offers, use no farther means,\n\ But with all brief and plain conveniency.\n\ Let me have judgment, and the Jew his will.\n\ \n\ BASSANIO.\n\ For thy three thousand ducats here is six.\n\ \n\ SHYLOCK.\n\ If every ducat in six thousand ducats\n\ Were in six parts, and every part a ducat,\n\ I would not draw them; I would have my bond.\n\ \n\ DUKE.\n\ How shalt thou hope for mercy, rendering none?\n\ \n\ SHYLOCK.\n\ What judgment shall I dread, doing no wrong?\n\ You have among you many a purchas\'d slave,\n\ Which, fike your asses and your dogs and mules,\n\ You use in abject and in slavish parts,\n\ Because you bought them; shall I say to you\n\ \'Let them be free, marry them to your heirs?\n\ Why sweat they under burdens? let their beds\n\ Be made as soft as yours, and let their palates\n\ Be season\'d with such viands? You will answer\n\ \'The slaves are ours.\' So do I answer you:\n\ The pound of flesh which I demand of him\n\ Is dearly bought; \'tis mine, and I will have it.\n\ If you deny me, fie upon your law!\n\ There is no force in the decrees of Venice.\n\ I stand for judgment: answer; shall I have it?\n\ \n\ DUKE.\n\ Upon my power I may dismiss this court,\n\ Unless Bellario, a learned doctor,\n\ Whom I have sent for to determine this,\n\ Come here to-day.\n\ \n\ SALARINO.\n\ My lord, here stays without\n\ A messenger with letters from the doctor,\n\ New come from Padua.\n\ \n\ DUKE.\n\ Bring us the letters; call the messenger.\n\ \n\ BASSANIO.\n\ Good cheer, Antonio! What, man, courage yet!\n\ The Jew shall have my flesh, blood, bones, and all,\n\ Ere thou shalt lose for me one drop of blood.\n\ \n\ ANTONIO.\n\ I am a tainted wether of the flock,\n\ Meetest for death; the weakest kind of fruit\n\ Drops earliest to the ground, and so let me.\n\ You cannot better be employ\'d, Bassanio,\n\ Than to live still, and write mine epitaph.\n\ \n\ [Enter NERISSA dressed like a lawyer\'s clerk.]\n\ \n\ DUKE.\n\ Came you from Padua, from Bellario?\n\ \n\ NERISSA.\n\ From both, my lord. Bellario greets your Grace.\n\ \n\ [Presents a letter.]\n\ \n\ BASSANIO.\n\ Why dost thou whet thy knife so earnestly?\n\ \n\ SHYLOCK.\n\ To cut the forfeiture from that bankrupt there.\n\ \n\ GRATIANO.\n\ Not on thy sole, but on thy soul, harsh Jew,\n\ Thou mak\'st thy knife keen; but no metal can,\n\ No, not the hangman\'s axe, bear half the keenness\n\ Of thy sharp envy. Can no prayers pierce thee?\n\ \n\ SHYLOCK.\n\ No, none that thou hast wit enough to make.\n\ \n\ GRATIANO.\n\ O, be thou damn\'d, inexecrable dog!\n\ And for thy life let justice be accus\'d.\n\ Thou almost mak\'st me waver in my faith,\n\ To hold opinion with Pythagoras\n\ That souls of animals infuse themselves\n\ Into the trunks of men. Thy currish spirit\n\ Govern\'d a wolf who, hang\'d for human slaughter,\n\ Even from the gallows did his fell soul fleet,\n\ And, whilst thou lay\'st in thy unhallow\'d dam,\n\ Infus\'d itself in thee; for thy desires\n\ Are wolfish, bloody, starv\'d and ravenous.\n\ \n\ SHYLOCK.\n\ Till thou canst rail the seal from off my bond,\n\ Thou but offend\'st thy lungs to speak so loud;\n\ Repair thy wit, good youth, or it will fall\n\ To cureless ruin. I stand here for law.\n\ \n\ DUKE.\n\ This letter from Bellario doth commend\n\ A young and learned doctor to our court.\n\ Where is he?\n\ \n\ NERISSA.\n\ He attendeth here hard by,\n\ To know your answer, whether you\'ll admit him.\n\ \n\ DUKE OF VENICE.\n\ With all my heart: some three or four of you\n\ Go give him courteous conduct to this place.\n\ Meantime, the court shall hear Bellario\'s letter.\n\ \n\ CLERK.\n\ \'Your Grace shall understand that at the receipt\n\ of your letter I am very sick; but in the instant that your\n\ messenger came, in loving visitation was with me a young doctor\n\ of Rome; his name is Balthazar. I acquainted him with the cause\n\ in controversy between the Jew and Antonio the merchant; we\n\ turn\'d o\'er many books together; he is furnished with my opinion\n\ which, bettered with his own learning,--the greatness whereof I\n\ cannot enough commend,--comes with him at my importunity to fill\n\ up your Grace\'s request in my stead. I beseech you let his lack\n\ of years be no impediment to let him lack a reverend estimation,\n\ for I never knew so young a body with so old a head. I leave him\n\ to your gracious acceptance, whose trial shall better publish his\n\ commendation.\'\n\ \n\ DUKE.\n\ YOU hear the learn\'d Bellario, what he writes;\n\ And here, I take it, is the doctor come.\n\ \n\ [Enter PORTIA, dressed like a doctor of laws.]\n\ \n\ Give me your hand; come you from old Bellario?\n\ \n\ PORTIA.\n\ I did, my lord.\n\ \n\ DUKE.\n\ You are welcome; take your place.\n\ Are you acquainted with the difference\n\ That holds this present question in the court?\n\ \n\ PORTIA.\n\ I am informed throughly of the cause.\n\ Which is the merchant here, and which the Jew?\n\ \n\ DUKE OF VENICE.\n\ Antonio and old Shylock, both stand forth.\n\ \n\ PORTIA.\n\ Is your name Shylock?\n\ \n\ SHYLOCK.\n\ Shylock is my name.\n\ \n\ PORTIA.\n\ Of a strange nature is the suit you follow;\n\ Yet in such rule that the Venetian law\n\ Cannot impugn you as you do proceed.\n\ [To ANTONIO.] You stand within his danger, do you not?\n\ \n\ ANTONIO.\n\ Ay, so he says.\n\ \n\ PORTIA.\n\ Do you confess the bond?\n\ \n\ ANTONIO.\n\ I do.\n\ \n\ PORTIA.\n\ Then must the Jew be merciful.\n\ \n\ SHYLOCK.\n\ On what compulsion must I? Tell me that.\n\ \n\ PORTIA.\n\ The quality of mercy is not strain\'d;\n\ It droppeth as the gentle rain from heaven\n\ Upon the place beneath. It is twice blest:\n\ It blesseth him that gives and him that takes.\n\ \'Tis mightiest in the mightiest; it becomes\n\ The throned monarch better than his crown;\n\ His sceptre shows the force of temporal power,\n\ The attribute to awe and majesty,\n\ Wherein doth sit the dread and fear of kings;\n\ But mercy is above this sceptred sway,\n\ It is enthroned in the hearts of kings,\n\ It is an attribute to God himself;\n\ And earthly power doth then show likest God\'s\n\ When mercy seasons justice. Therefore, Jew,\n\ Though justice be thy plea, consider this,\n\ That in the course of justice none of us\n\ Should see salvation; we do pray for mercy,\n\ And that same prayer doth teach us all to render\n\ The deeds of mercy. I have spoke thus much\n\ To mitigate the justice of thy plea,\n\ Which if thou follow, this strict court of Venice\n\ Must needs give sentence \'gainst the merchant there.\n\ \n\ SHYLOCK.\n\ My deeds upon my head! I crave the law,\n\ The penalty and forfeit of my bond.\n\ \n\ PORTIA.\n\ Is he not able to discharge the money?\n\ \n\ BASSANIO.\n\ Yes; here I tender it for him in the court;\n\ Yea, twice the sum; if that will not suffice,\n\ I will be bound to pay it ten times o\'er\n\ On forfeit of my hands, my head, my heart;\n\ If this will not suffice, it must appear\n\ That malice bears down truth. And, I beseech you,\n\ Wrest once the law to your authority;\n\ To do a great right do a little wrong,\n\ And curb this cruel devil of his will.\n\ \n\ PORTIA.\n\ It must not be; there is no power in Venice\n\ Can alter a decree established;\n\ \'Twill be recorded for a precedent,\n\ And many an error by the same example\n\ Will rush into the state. It cannot be.\n\ \n\ SHYLOCK.\n\ A Daniel come to judgment! Yea, a Daniel!\n\ O wise young judge, how I do honour thee!\n\ \n\ PORTIA.\n\ I pray you, let me look upon the bond.\n\ \n\ SHYLOCK.\n\ Here \'tis, most reverend doctor; here it is.\n\ \n\ PORTIA.\n\ Shylock, there\'s thrice thy money offer\'d thee.\n\ \n\ SHYLOCK.\n\ An oath, an oath! I have an oath in heaven.\n\ Shall I lay perjury upon my soul?\n\ No, not for Venice.\n\ \n\ PORTIA.\n\ Why, this bond is forfeit;\n\ And lawfully by this the Jew may claim\n\ A pound of flesh, to be by him cut off\n\ Nearest the merchant\'s heart. Be merciful.\n\ Take thrice thy money; bid me tear the bond.\n\ \n\ SHYLOCK.\n\ When it is paid according to the tenour.\n\ It doth appear you are a worthy judge;\n\ You know the law; your exposition\n\ Hath been most sound; I charge you by the law,\n\ Whereof you are a well-deserving pillar,\n\ Proceed to judgment. By my soul I swear\n\ There is no power in the tongue of man\n\ To alter me. I stay here on my bond.\n\ \n\ ANTONIO.\n\ Most heartily I do beseech the court\n\ To give the judgment.\n\ \n\ PORTIA.\n\ Why then, thus it is:\n\ You must prepare your bosom for his knife.\n\ \n\ SHYLOCK.\n\ O noble judge! O excellent young man!\n\ \n\ PORTIA.\n\ For the intent and purpose of the law\n\ Hath full relation to the penalty,\n\ Which here appeareth due upon the bond.\n\ \n\ SHYLOCK.\n\ \'Tis very true. O wise and upright judge,\n\ How much more elder art thou than thy looks!\n\ \n\ PORTIA.\n\ Therefore, lay bare your bosom.\n\ \n\ SHYLOCK.\n\ Ay, \'his breast\':\n\ So says the bond:--doth it not, noble judge?--\n\ \'Nearest his heart\': those are the very words.\n\ \n\ PORTIA.\n\ It is so. Are there balance here to weigh\n\ The flesh?\n\ \n\ SHYLOCK.\n\ I have them ready.\n\ \n\ PORTIA.\n\ Have by some surgeon, Shylock, on your charge,\n\ To stop his wounds, lest he do bleed to death.\n\ \n\ SHYLOCK.\n\ Is it so nominated in the bond?\n\ \n\ PORTIA.\n\ It is not so express\'d; but what of that?\n\ \'Twere good you do so much for charity.\n\ \n\ SHYLOCK.\n\ I cannot find it; \'tis not in the bond.\n\ \n\ PORTIA.\n\ You, merchant, have you anything to say?\n\ \n\ ANTONIO.\n\ But little: I am arm\'d and well prepar\'d.\n\ Give me your hand, Bassanio: fare you well.!\n\ Grieve not that I am fallen to this for you,\n\ For herein Fortune shows herself more kind\n\ Than is her custom: it is still her use\n\ To let the wretched man outlive his wealth,\n\ To view with hollow eye and wrinkled brow\n\ An age of poverty; from which lingering penance\n\ Of such misery doth she cut me off.\n\ Commend me to your honourable wife:\n\ Tell her the process of Antonio\'s end;\n\ Say how I lov\'d you; speak me fair in death;\n\ And, when the tale is told, bid her be judge\n\ Whether Bassanio had not once a love.\n\ Repent but you that you shall lose your friend,\n\ And he repents not that he pays your debt;\n\ For if the Jew do cut but deep enough,\n\ I\'ll pay it instantly with all my heart.\n\ \n\ BASSANIO.\n\ Antonio, I am married to a wife\n\ Which is as dear to me as life itself;\n\ But life itself, my wife, and all the world,\n\ Are not with me esteem\'d above thy life;\n\ I would lose all, ay, sacrifice them all\n\ Here to this devil, to deliver you.\n\ \n\ PORTIA.\n\ Your wife would give you little thanks for that,\n\ If she were by to hear you make the offer.\n\ \n\ GRATIANO.\n\ I have a wife whom, I protest, I love;\n\ I would she were in heaven, so she could\n\ Entreat some power to change this currish Jew.\n\ \n\ NERISSA.\n\ \'Tis well you offer it behind her back;\n\ The wish would make else an unquiet house.\n\ \n\ SHYLOCK.\n\ These be the Christian husbands! I have a daughter;\n\ Would any of the stock of Barabbas\n\ Had been her husband, rather than a Christian!\n\ We trifle time; I pray thee, pursue sentence.\n\ \n\ PORTIA.\n\ A pound of that same merchant\'s flesh is thine.\n\ The court awards it and the law doth give it.\n\ \n\ SHYLOCK.\n\ Most rightful judge!\n\ \n\ PORTIA.\n\ And you must cut this flesh from off his breast.\n\ The law allows it and the court awards it.\n\ \n\ SHYLOCK.\n\ Most learned judge! A sentence! Come, prepare.\n\ \n\ PORTIA.\n\ Tarry a little; there is something else.\n\ This bond doth give thee here no jot of blood;\n\ The words expressly are \'a pound of flesh\':\n\ Take then thy bond, take thou thy pound of flesh;\n\ But, in the cutting it, if thou dost shed\n\ One drop of Christian blood, thy lands and goods\n\ Are, by the laws of Venice, confiscate\n\ Unto the state of Venice.\n\ \n\ GRATIANO.\n\ O upright judge! Mark, Jew: O learned judge!\n\ \n\ SHYLOCK.\n\ Is that the law?\n\ \n\ PORTIA.\n\ Thyself shalt see the act;\n\ For, as thou urgest justice, be assur\'d\n\ Thou shalt have justice, more than thou desir\'st.\n\ \n\ GRATIANO.\n\ O learned judge! Mark, Jew: alearned judge!\n\ \n\ SHYLOCK.\n\ I take this offer then: pay the bond thrice,\n\ And let the Christian go.\n\ \n\ BASSANIO.\n\ Here is the money.\n\ \n\ PORTIA.\n\ Soft!\n\ The Jew shall have all justice; soft! no haste:--\n\ He shall have nothing but the penalty.\n\ \n\ GRATIANO.\n\ O Jew! an upright judge, a learned judge!\n\ \n\ PORTIA.\n\ Therefore, prepare thee to cut off the flesh.\n\ Shed thou no blood; nor cut thou less nor more,\n\ But just a pound of flesh: if thou tak\'st more,\n\ Or less, than a just pound, be it but so much\n\ As makes it light or heavy in the substance,\n\ Or the division of the twentieth part\n\ Of one poor scruple; nay, if the scale do turn\n\ But in the estimation of a hair,\n\ Thou diest, and all thy goods are confiscate.\n\ \n\ GRATIANO.\n\ A second Daniel, a Daniel, Jew!\n\ Now, infidel, I have you on the hip.\n\ \n\ PORTIA.\n\ Why doth the Jew pause? Take thy forfeiture.\n\ \n\ SHYLOCK.\n\ Give me my principal, and let me go.\n\ \n\ BASSANIO.\n\ I have it ready for thee; here it is.\n\ \n\ PORTIA.\n\ He hath refus\'d it in the open court;\n\ He shall have merely justice, and his bond.\n\ \n\ GRATIANO.\n\ A Daniel still say I; a second Daniel!\n\ I thank thee, Jew, for teaching me that word.\n\ \n\ SHYLOCK.\n\ Shall I not have barely my principal?\n\ \n\ PORTIA.\n\ Thou shalt have nothing but the forfeiture\n\ To be so taken at thy peril, Jew.\n\ \n\ SHYLOCK.\n\ Why, then the devil give him good of it!\n\ I\'ll stay no longer question.\n\ \n\ PORTIA.\n\ Tarry, Jew.\n\ The law hath yet another hold on you.\n\ It is enacted in the laws of Venice,\n\ If it be prov\'d against an alien\n\ That by direct or indirect attempts\n\ He seek the life of any citizen,\n\ The party \'gainst the which he doth contrive\n\ Shall seize one half his goods; the other half\n\ Comes to the privy coffer of the state;\n\ And the offender\'s life lies in the mercy\n\ Of the duke only, \'gainst all other voice.\n\ In which predicament, I say, thou stand\'st;\n\ For it appears by manifest proceeding\n\ That indirectly, and directly too,\n\ Thou hast contrived against the very life\n\ Of the defendant; and thou hast incurr\'d\n\ The danger formerly by me rehears\'d.\n\ Down, therefore, and beg mercy of the duke.\n\ \n\ GRATIANO.\n\ Beg that thou mayst have leave to hang thyself;\n\ And yet, thy wealth being forfeit to the state,\n\ Thou hast not left the value of a cord;\n\ Therefore thou must be hang\'d at the state\'s charge.\n\ \n\ DUKE.\n\ That thou shalt see the difference of our spirits,\n\ I pardon thee thy life before thou ask it.\n\ For half thy wealth, it is Antonio\'s;\n\ The other half comes to the general state,\n\ Which humbleness may drive unto a fine.\n\ \n\ PORTIA.\n\ Ay, for the state; not for Antonio.\n\ \n\ SHYLOCK.\n\ Nay, take my life and all, pardon not that:\n\ You take my house when you do take the prop\n\ That doth sustain my house; you take my life\n\ When you do take the means whereby I live.\n\ \n\ PORTIA.\n\ What mercy can you render him, Antonio?\n\ \n\ GRATIANO.\n\ A halter gratis; nothing else, for God\'s sake!\n\ \n\ ANTONIO.\n\ So please my lord the Duke and all the court\n\ To quit the fine for one half of his goods;\n\ I am content, so he will let me have\n\ The other half in use, to render it\n\ Upon his death unto the gentleman\n\ That lately stole his daughter:\n\ Two things provided more, that, for this favour,\n\ He presently become a Christian;\n\ The other, that he do record a gift,\n\ Here in the court, of all he dies possess\'d\n\ Unto his son Lorenzo and his daughter.\n\ \n\ DUKE.\n\ He shall do this, or else I do recant\n\ The pardon that I late pronounced here.\n\ \n\ PORTIA.\n\ Art thou contented, Jew? What dost thou say?\n\ \n\ SHYLOCK.\n\ I am content.\n\ \n\ PORTIA.\n\ Clerk, draw a deed of gift.\n\ \n\ SHYLOCK.\n\ I pray you, give me leave to go from hence;\n\ I am not well; send the deed after me\n\ And I will sign it.\n\ \n\ DUKE.\n\ Get thee gone, but do it.\n\ \n\ GRATIANO.\n\ In christening shalt thou have two god-fathers;\n\ Had I been judge, thou shouldst have had ten more,\n\ To bring thee to the gallows, not to the font.\n\ \n\ [Exit SHYLOCK.]\n\ \n\ DUKE.\n\ Sir, I entreat you home with me to dinner.\n\ \n\ PORTIA.\n\ I humbly do desire your Grace of pardon;\n\ I must away this night toward Padua,\n\ And it is meet I presently set forth.\n\ \n\ DUKE.\n\ I am sorry that your leisure serves you not.\n\ Antonio, gratify this gentleman,\n\ For in my mind you are much bound to him.\n\ \n\ [Exeunt DUKE, Magnificoes, and Train.]\n\ \n\ BASSANIO.\n\ Most worthy gentleman, I and my friend\n\ Have by your wisdom been this day acquitted\n\ Of grievous penalties; in lieu whereof\n\ Three thousand ducats, due unto the Jew,\n\ We freely cope your courteous pains withal.\n\ \n\ ANTONIO.\n\ And stand indebted, over and above,\n\ In love and service to you evermore.\n\ \n\ PORTIA.\n\ He is well paid that is well satisfied;\n\ And I, delivering you, am satisfied,\n\ And therein do account myself well paid:\n\ My mind was never yet more mercenary.\n\ I pray you, know me when we meet again:\n\ I wish you well, and so I take my leave.\n\ \n\ BASSANIO.\n\ Dear sir, of force I must attempt you further;\n\ Take some remembrance of us, as a tribute,\n\ Not as fee. Grant me two things, I pray you,\n\ Not to deny me, and to pardon me.\n\ \n\ PORTIA.\n\ You press me far, and therefore I will yield.\n\ \n\ [To ANTONIO]\n\ Give me your gloves, I\'ll wear them for your sake.\n\ \n\ [To BASSANIO]\n\ And, for your love, I\'ll take this ring from you.\n\ Do not draw back your hand; I\'ll take no more;\n\ And you in love shall not deny me this.\n\ \n\ BASSANIO.\n\ This ring, good sir? alas, it is a trifle;\n\ I will not shame myself to give you this.\n\ \n\ PORTIA.\n\ I will have nothing else but only this;\n\ And now, methinks, I have a mind to it.\n\ \n\ BASSANIO.\n\ There\'s more depends on this than on the value.\n\ The dearest ring in Venice will I give you,\n\ And find it out by proclamation:\n\ Only for this, I pray you, pardon me.\n\ \n\ PORTIA.\n\ I see, sir, you are liberal in offers;\n\ You taught me first to beg, and now methinks\n\ You teach me how a beggar should be answer\'d.\n\ \n\ BASSANIO.\n\ Good sir, this ring was given me by my wife;\n\ And, when she put it on, she made me vow\n\ That I should neither sell, nor give, nor lose it.\n\ \n\ PORTIA.\n\ That \'scuse serves many men to save their gifts.\n\ And if your wife be not a mad-woman,\n\ And know how well I have deserv\'d this ring,\n\ She would not hold out enemy for ever\n\ For giving it to me. Well, peace be with you!\n\ \n\ [Exeunt PORTIA and NERISSA.]\n\ \n\ ANTONIO.\n\ My Lord Bassanio, let him have the ring:\n\ Let his deservings, and my love withal,\n\ Be valued \'gainst your wife\'s commandment.\n\ \n\ BASSANIO.\n\ Go, Gratiano, run and overtake him;\n\ Give him the ring, and bring him, if thou canst,\n\ Unto Antonio\'s house. Away! make haste.\n\ \n\ [Exit GRATIANO.]\n\ \n\ Come, you and I will thither presently;\n\ And in the morning early will we both\n\ Fly toward Belmont. Come, Antonio.\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ SCENE II. The same. A street\n\ \n\ [Enter PORTIA and NERISSA.]\n\ \n\ PORTIA.\n\ Inquire the Jew\'s house out, give him this deed,\n\ And let him sign it; we\'ll away tonight,\n\ And be a day before our husbands home.\n\ This deed will be well welcome to Lorenzo.\n\ \n\ [Enter GRATIANO.]\n\ \n\ GRATIANO.\n\ Fair sir, you are well o\'erta\'en.\n\ My Lord Bassanio, upon more advice,\n\ Hath sent you here this ring, and doth entreat\n\ Your company at dinner.\n\ \n\ PORTIA.\n\ That cannot be:\n\ His ring I do accept most thankfully;\n\ And so, I pray you, tell him: furthermore,\n\ I pray you show my youth old Shylock\'s house.\n\ \n\ GRATIANO.\n\ That will I do.\n\ \n\ NERISSA.\n\ Sir, I would speak with you.\n\ [Aside to PORTIA.]\n\ I\'ll see if I can get my husband\'s ring,\n\ Which I did make him swear to keep for ever.\n\ \n\ PORTIA.[To NERISSA]\n\ Thou Mayst, I warrant. We shall have old swearing\n\ That they did give the rings away to men;\n\ But we\'ll outface them, and outswear them too.\n\ Away! make haste: thou know\'st where I will tarry.\n\ \n\ NERISSA.\n\ Come, good sir, will you show me to this house?\n\ \n\ [Exeunt.]\n\ \n\ \n\ \n\ ACT V.\n\ \n\ SCENE I. Belmont. The avenue to PORTIA\'s house.\n\ \n\ [Enter LORENZO and JESSICA.]\n\ \n\ LORENZO.\n\ The moon shines bright: in such a night as this,\n\ When the sweet wind did gently kiss the trees,\n\ And they did make no noise, in such a night,\n\ Troilus methinks mounted the Troyan walls,\n\ And sigh\'d his soul toward the Grecian tents,\n\ Where Cressid lay that night.\n\ \n\ JESSICA.\n\ In such a night\n\ Did Thisby fearfully o\'ertrip the dew,\n\ And saw the lion\'s shadow ere himself,\n\ And ran dismay\'d away.\n\ \n\ LORENZO.\n\ In such a night\n\ Stood Dido with a willow in her hand\n\ Upon the wild sea-banks, and waft her love\n\ To come again to Carthage.\n\ \n\ JESSICA.\n\ In such a night\n\ Medea gather\'d the enchanted herbs\n\ That did renew old AEson.\n\ \n\ LORENZO.\n\ In such a night\n\ Did Jessica steal from the wealthy Jew,\n\ And with an unthrift love did run from Venice\n\ As far as Belmont.\n\ \n\ JESSICA.\n\ In such a night\n\ Did young Lorenzo swear he lov\'d her well,\n\ Stealing her soul with many vows of faith,--\n\ And ne\'er a true one.\n\ \n\ LORENZO.\n\ In such a night\n\ Did pretty Jessica, like a little shrew,\n\ Slander her love, and he forgave it her.\n\ \n\ JESSICA.\n\ I would out-night you, did no body come;\n\ But, hark, I hear the footing of a man.\n\ \n\ [Enter STEPHANO.]\n\ \n\ LORENZO.\n\ Who comes so fast in silence of the night?\n\ \n\ STEPHANO.\n\ A friend.\n\ \n\ LORENZO.\n\ A friend! What friend? Your name, I pray you, friend?\n\ \n\ STEPHANO.\n\ Stephano is my name, and I bring word\n\ My mistress will before the break of day\n\ Be here at Belmont; she doth stray about\n\ By holy crosses, where she kneels and prays\n\ For happy wedlock hours.\n\ \n\ LORENZO.\n\ Who comes with her?\n\ \n\ STEPHANO.\n\ None but a holy hermit and her maid.\n\ I pray you, is my master yet return\'d?\n\ \n\ LORENZO.\n\ He is not, nor we have not heard from him.\n\ But go we in, I pray thee, Jessica,\n\ And ceremoniously let us prepare\n\ Some welcome for the mistress of the house.\n\ \n\ [Enter LAUNCELOT.]\n\ \n\ LAUNCELOT. Sola, sola! wo ha, ho! sola, sola!\n\ \n\ LORENZO.\n\ Who calls?\n\ \n\ LAUNCELOT.\n\ Sola! Did you see Master Lorenzo? Master Lorenzo! Sola, sola!\n\ \n\ LORENZO.\n\ Leave holloaing, man. Here!\n\ \n\ LAUNCELOT.\n\ Sola! Where? where?\n\ \n\ LORENZO.\n\ Here!\n\ \n\ LAUNCELOT.\n\ Tell him there\'s a post come from my master with his\n\ horn full of good news; my master will be here ere morning.\n\ \n\ [Exit]\n\ \n\ LORENZO.\n\ Sweet soul, let\'s in, and there expect their coming.\n\ And yet no matter; why should we go in?\n\ My friend Stephano, signify, I pray you,\n\ Within the house, your mistress is at hand;\n\ And bring your music forth into the air.\n\ \n\ [Exit STEPHANO.]\n\ \n\ How sweet the moonlight sleeps upon this bank!\n\ Here will we sit and let the sounds of music\n\ Creep in our ears; soft stillness and the night\n\ Become the touches of sweet harmony.\n\ Sit, Jessica: look how the floor of heaven\n\ Is thick inlaid with patines of bright gold;\n\ There\'s not the smallest orb which thou behold\'st\n\ But in his motion like an angel sings,\n\ Still quiring to the young-eyed cherubins;\n\ Such harmony is in immortal souls;\n\ But, whilst this muddy vesture of decay\n\ Doth grossly close it in, we cannot hear it.\n\ \n\ [Enter Musicians.]\n\ \n\ Come, ho! and wake Diana with a hymn;\n\ With sweetest touches pierce your mistress\' ear.\n\ And draw her home with music.\n\ \n\ [Music.]\n\ \n\ JESSICA.\n\ I am never merry when I hear sweet music.\n\ \n\ LORENZO.\n\ The reason is, your spirits are attentive;\n\ For do but note a wild and wanton herd,\n\ Or race of youthful and unhandled colts,\n\ Fetching mad bounds, bellowing and neighing loud,\n\ Which is the hot condition of their blood;\n\ If they but hear perchance a trumpet sound,\n\ Or any air of music touch their ears,\n\ You shall perceive them make a mutual stand,\n\ Their savage eyes turn\'d to a modest gaze\n\ By the sweet power of music: therefore the poet\n\ Did feign that Orpheus drew trees, stones, and floods;\n\ Since nought so stockish, hard, and full of rage,\n\ But music for the time doth change his nature.\n\ The man that hath no music in himself,\n\ Nor is not mov\'d with concord of sweet sounds,\n\ Is fit for treasons, stratagems, and spoils;\n\ The motions of his spirit are dull as night,\n\ And his affections dark as Erebus.\n\ Let no such man be trusted. Mark the music.\n\ \n\ [Enter PORTIA and NERISSA, at a distance.]\n\ \n\ PORTIA.\n\ That light we see is burning in my hall.\n\ How far that little candle throws his beams!\n\ So shines a good deed in a naughty world.\n\ \n\ NERISSA.\n\ When the moon shone, we did not see the candle.\n\ \n\ PORTIA.\n\ So doth the greater glory dim the less:\n\ A substitute shines brightly as a king\n\ Until a king be by, and then his state\n\ Empties itself, as doth an inland brook\n\ Into the main of waters. Music! hark!\n\ \n\ NERISSA.\n\ It is your music, madam, of the house.\n\ \n\ PORTIA.\n\ Nothing is good, I see, without respect:\n\ Methinks it sounds much sweeter than by day.\n\ \n\ NERISSA.\n\ Silence bestows that virtue on it, madam.\n\ \n\ PORTIA.\n\ The crow doth sing as sweetly as the lark\n\ When neither is attended; and I think\n\ The nightingale, if she should sing by day,\n\ When every goose is cackling, would be thought\n\ No better a musician than the wren.\n\ How many things by season season\'d are\n\ To their right praise and true perfection!\n\ Peace, ho! The moon sleeps with Endymion,\n\ And would not be awak\'d!\n\ \n\ [Music ceases.]\n\ \n\ LORENZO.\n\ That is the voice,\n\ Or I am much deceiv\'d, of Portia.\n\ \n\ PORTIA.\n\ He knows me as the blind man knows the cuckoo,\n\ By the bad voice.\n\ \n\ LORENZO. Dear lady, welcome home.\n\ \n\ PORTIA.\n\ We have been praying for our husbands\' welfare,\n\ Which speed, we hope, the better for our words.\n\ Are they return\'d?\n\ \n\ LORENZO.\n\ Madam, they are not yet;\n\ But there is come a messenger before,\n\ To signify their coming.\n\ \n\ PORTIA.\n\ Go in, Nerissa:\n\ Give order to my servants that they take\n\ No note at all of our being absent hence;\n\ Nor you, Lorenzo; Jessica, nor you.\n\ \n\ [A tucket sounds.]\n\ \n\ LORENZO.\n\ Your husband is at hand; I hear his trumpet.\n\ We are no tell-tales, madam, fear you not.\n\ \n\ PORTIA.\n\ This night methinks is but the daylight sick;\n\ It looks a little paler; \'tis a day\n\ Such as the day is when the sun is hid.\n\ \n\ [Enter BASSANIO, ANTONIO, GRATIANO, and their Followers.]\n\ \n\ BASSANIO.\n\ We should hold day with the Antipodes,\n\ If you would walk in absence of the sun.\n\ \n\ PORTIA.\n\ Let me give light, but let me not be light,\n\ For a light wife doth make a heavy husband,\n\ And never be Bassanio so for me:\n\ But God sort all! You are welcome home, my lord.\n\ \n\ BASSANIO.\n\ I thank you, madam; give welcome to my friend:\n\ This is the man, this is Antonio,\n\ To whom I am so infinitely bound.\n\ \n\ PORTIA.\n\ You should in all sense be much bound to him,\n\ For, as I hear, he was much bound for you.\n\ \n\ ANTONIO.\n\ No more than I am well acquitted of.\n\ \n\ PORTIA.\n\ Sir, you are very welcome to our house.\n\ It must appear in other ways than words,\n\ Therefore I scant this breathing courtesy.\n\ \n\ GRATIANO. [To NERISSA]\n\ By yonder moon I swear you do me wrong;\n\ In faith, I gave it to the judge\'s clerk.\n\ Would he were gelt that had it, for my part,\n\ Since you do take it, love, so much at heart.\n\ \n\ PORTIA.\n\ A quarrel, ho, already! What\'s the matter?\n\ \n\ GRATIANO.\n\ About a hoop of gold, a paltry ring\n\ That she did give me, whose posy was\n\ For all the world like cutlers\' poetry\n\ Upon a knife, \'Love me, and leave me not.\'\n\ \n\ NERISSA.\n\ What talk you of the posy, or the value?\n\ You swore to me, when I did give it you,\n\ That you would wear it till your hour of death,\n\ And that it should lie with you in your grave;\n\ Though not for me, yet for your vehement oaths,\n\ You should have been respective and have kept it.\n\ Gave it a judge\'s clerk! No, God\'s my judge,\n\ The clerk will ne\'er wear hair on\'s face that had it.\n\ \n\ GRATIANO.\n\ He will, an if he live to be a man.\n\ \n\ NERISSA.\n\ Ay, if a woman live to be a man.\n\ \n\ GRATIANO.\n\ Now, by this hand, I gave it to a youth,\n\ A kind of boy, a little scrubbed boy\n\ No higher than thyself, the judge\'s clerk;\n\ A prating boy that begg\'d it as a fee;\n\ I could not for my heart deny it him.\n\ \n\ PORTIA.\n\ You were to blame,--I must be plain with you,--\n\ To part so slightly with your wife\'s first gift,\n\ A thing stuck on with oaths upon your finger,\n\ And so riveted with faith unto your flesh.\n\ I gave my love a ring, and made him swear\n\ Never to part with it, and here he stands,\n\ I dare be sworn for him he would not leave it\n\ Nor pluck it from his finger for the wealth\n\ That the world masters. Now, in faith, Gratiano,\n\ You give your wife too unkind a cause of grief;\n\ An \'twere to me, I should be mad at it.\n\ \n\ BASSANIO.[Aside]\n\ Why, I were best to cut my left hand off,\n\ And swear I lost the ring defending it.\n\ \n\ GRATIANO.\n\ My Lord Bassanio gave his ring away\n\ Unto the judge that begg\'d it, and indeed\n\ Deserv\'d it too; and then the boy, his clerk,\n\ That took some pains in writing, he begg\'d mine;\n\ And neither man nor master would take aught\n\ But the two rings.\n\ \n\ PORTIA.\n\ What ring gave you, my lord?\n\ Not that, I hope, which you receiv\'d of me.\n\ \n\ BASSANIO.\n\ If I could add a lie unto a fault,\n\ I would deny it; but you see my finger\n\ Hath not the ring upon it; it is gone.\n\ \n\ PORTIA.\n\ Even so void is your false heart of truth;\n\ By heaven, I will ne\'er come in your bed\n\ Until I see the ring.\n\ \n\ NERISSA.\n\ Nor I in yours\n\ Till I again see mine.\n\ \n\ BASSANIO.\n\ Sweet Portia,\n\ If you did know to whom I gave the ring,\n\ If you did know for whom I gave the ring,\n\ And would conceive for what I gave the ring,\n\ And how unwillingly I left the ring,\n\ When nought would be accepted but the ring,\n\ You would abate the strength of your displeasure.\n\ \n\ PORTIA.\n\ If you had known the virtue of the ring,\n\ Or half her worthiness that gave the ring,\n\ Or your own honour to contain the ring,\n\ You would not then have parted with the ring.\n\ What man is there so much unreasonable,\n\ If you had pleas\'d to have defended it\n\ With any terms of zeal, wanted the modesty\n\ To urge the thing held as a ceremony?\n\ Nerissa teaches me what to believe:\n\ I\'ll die for\'t but some woman had the ring.\n\ \n\ BASSANIO.\n\ No, by my honour, madam, by my soul,\n\ No woman had it, but a civil doctor,\n\ Which did refuse three thousand ducats of me,\n\ And begg\'d the ring; the which I did deny him,\n\ And suffer\'d him to go displeas\'d away;\n\ Even he that had held up the very life\n\ Of my dear friend. What should I say, sweet lady?\n\ I was enforc\'d to send it after him;\n\ I was beset with shame and courtesy;\n\ My honour would not let ingratitude\n\ So much besmear it. Pardon me, good lady;\n\ For, by these blessed candles of the night,\n\ Had you been there, I think you would have begg\'d\n\ The ring of me to give the worthy doctor.\n\ \n\ PORTIA.\n\ Let not that doctor e\'er come near my house;\n\ Since he hath got the jewel that I loved,\n\ And that which you did swear to keep for me,\n\ I will become as liberal as you;\n\ I\'ll not deny him anything I have,\n\ No, not my body, nor my husband\'s bed.\n\ Know him I shall, I am well sure of it.\n\ Lie not a night from home; watch me like Argus;\n\ If you do not, if I be left alone,\n\ Now, by mine honour which is yet mine own,\n\ I\'ll have that doctor for mine bedfellow.\n\ \n\ NERISSA.\n\ And I his clerk; therefore be well advis\'d\n\ How you do leave me to mine own protection.\n\ \n\ GRATIANO.\n\ Well, do you so: let not me take him then;\n\ For, if I do, I\'ll mar the young clerk\'s pen.\n\ \n\ ANTONIO.\n\ I am the unhappy subject of these quarrels.\n\ \n\ PORTIA.\n\ Sir, grieve not you; you are welcome notwithstanding.\n\ \n\ BASSANIO.\n\ Portia, forgive me this enforced wrong;\n\ And in the hearing of these many friends\n\ I swear to thee, even by thine own fair eyes,\n\ Wherein I see myself,--\n\ \n\ PORTIA.\n\ Mark you but that!\n\ In both my eyes he doubly sees himself,\n\ In each eye one; swear by your double self,\n\ And there\'s an oath of credit.\n\ \n\ BASSANIO.\n\ Nay, but hear me:\n\ Pardon this fault, and by my soul I swear\n\ I never more will break an oath with thee.\n\ \n\ ANTONIO.\n\ I once did lend my body for his wealth,\n\ Which, but for him that had your husband\'s ring,\n\ Had quite miscarried; I dare be bound again,\n\ My soul upon the forfeit, that your lord\n\ Will never more break faith advisedly.\n\ \n\ PORTIA.\n\ Then you shall be his surety. Give him this,\n\ And bid him keep it better than the other.\n\ \n\ ANTONIO.\n\ Here, Lord Bassanio, swear to keep this ring.\n\ \n\ BASSANIO.\n\ By heaven! it is the same I gave the doctor!\n\ \n\ PORTIA.\n\ I had it of him: pardon me, Bassanio,\n\ For, by this ring, the doctor lay with me.\n\ \n\ NERISSA.\n\ And pardon me, my gentle Gratiano,\n\ For that same scrubbed boy, the doctor\'s clerk,\n\ In lieu of this, last night did lie with me.\n\ \n\ GRATIANO.\n\ Why, this is like the mending of high ways\n\ In summer, where the ways are fair enough.\n\ What! are we cuckolds ere we have deserv\'d it?\n\ \n\ PORTIA.\n\ Speak not so grossly. You are all amaz\'d:\n\ Here is a letter; read it at your leisure;\n\ It comes from Padua, from Bellario:\n\ There you shall find that Portia was the doctor,\n\ Nerissa there, her clerk: Lorenzo here\n\ Shall witness I set forth as soon as you,\n\ And even but now return\'d; I have not yet\n\ Enter\'d my house. Antonio, you are welcome;\n\ And I have better news in store for you\n\ Than you expect: unseal this letter soon;\n\ There you shall find three of your argosies\n\ Are richly come to harbour suddenly.\n\ You shall not know by what strange accident\n\ I chanced on this letter.\n\ \n\ ANTONIO.\n\ I am dumb.\n\ \n\ BASSANIO.\n\ Were you the doctor, and I knew you not?\n\ \n\ GRATIANO.\n\ Were you the clerk that is to make me cuckold?\n\ \n\ NERISSA.\n\ Ay, but the clerk that never means to do it,\n\ Unless he live until he be a man.\n\ \n\ BASSANIO.\n\ Sweet doctor, you shall be my bedfellow:\n\ When I am absent, then lie with my wife.\n\ \n\ ANTONIO.\n\ Sweet lady, you have given me life and living;\n\ For here I read for certain that my ships\n\ Are safely come to road.\n\ \n\ PORTIA.\n\ How now, Lorenzo!\n\ My clerk hath some good comforts too for you.\n\ \n\ NERISSA.\n\ Ay, and I\'ll give them him without a fee.\n\ There do I give to you and Jessica,\n\ From the rich Jew, a special deed of gift,\n\ After his death, of all he dies possess\'d of.\n\ \n\ LORENZO.\n\ Fair ladies, you drop manna in the way\n\ Of starved people.\n\ \n\ PORTIA.\n\ It is almost morning,\n\ And yet I am sure you are not satisfied\n\ Of these events at full. Let us go in;\n\ And charge us there upon inter\'gatories,\n\ And we will answer all things faithfully.\n\ \n\ GRATIANO.\n\ Let it be so: he first inter\'gatory\n\ That my Nerissa shall be sworn on is,\n\ Whe\'r till the next night she had rather stay,\n\ Or go to bed now, being two hours to day:\n\ But were the day come, I should wish it dark,\n\ Till I were couching with the doctor\'s clerk.\n\ Well, while I live, I\'ll fear no other thing\n\ So sore as keeping safe Nerissa\'s ring.\n\ \n\ [Exeunt.}\n\ \n\ \n\ \n\ \n\ \n\ End of Project Gutenberg Etext of The Merchant of Venice by Shakespeare\n\ PG has multiple editions of William Shakespeare\'s Complete Works\n\ \n\ ";
the_stack_data/40764002.c
#include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; #ifdef _MSC_VER static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;} static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;} static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;} static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;} #else static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #endif #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #ifdef _MSC_VER #define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);} #define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);} #else #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #endif #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimagf(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #ifdef _MSC_VER static _Fcomplex cpow_ui(complex x, integer n) { complex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i; for(u = n; ; ) { if(u & 01) pow.r *= x.r, pow.i *= x.i; if(u >>= 1) x.r *= x.r, x.i *= x.i; else break; } } _Fcomplex p={pow.r, pow.i}; return p; } #else static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif #ifdef _MSC_VER static _Dcomplex zpow_ui(_Dcomplex x, integer n) { _Dcomplex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1]; for(u = n; ; ) { if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1]; if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1]; else break; } } _Dcomplex p = {pow._Val[0], pow._Val[1]}; return p; } #else static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* > \brief \b DLASRT sorts numbers in increasing or decreasing order. */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download DLASRT + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dlasrt. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dlasrt. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dlasrt. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE DLASRT( ID, N, D, INFO ) */ /* CHARACTER ID */ /* INTEGER INFO, N */ /* DOUBLE PRECISION D( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > Sort the numbers in D in increasing order (if ID = 'I') or */ /* > in decreasing order (if ID = 'D' ). */ /* > */ /* > Use Quick Sort, reverting to Insertion sort on arrays of */ /* > size <= 20. Dimension of STACK limits N to about 2**32. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] ID */ /* > \verbatim */ /* > ID is CHARACTER*1 */ /* > = 'I': sort D in increasing order; */ /* > = 'D': sort D in decreasing order. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The length of the array D. */ /* > \endverbatim */ /* > */ /* > \param[in,out] D */ /* > \verbatim */ /* > D is DOUBLE PRECISION array, dimension (N) */ /* > On entry, the array to be sorted. */ /* > On exit, D has been sorted into increasing order */ /* > (D(1) <= ... <= D(N) ) or into decreasing order */ /* > (D(1) >= ... >= D(N) ), depending on ID. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date June 2016 */ /* > \ingroup auxOTHERcomputational */ /* ===================================================================== */ /* Subroutine */ int dlasrt_(char *id, integer *n, doublereal *d__, integer * info) { /* System generated locals */ integer i__1, i__2; /* Local variables */ integer endd, i__, j; extern logical lsame_(char *, char *); integer stack[64] /* was [2][32] */; doublereal dmnmx, d1, d2, d3; integer start; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); integer stkpnt, dir; doublereal tmp; /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* June 2016 */ /* ===================================================================== */ /* Test the input parameters. */ /* Parameter adjustments */ --d__; /* Function Body */ *info = 0; dir = -1; if (lsame_(id, "D")) { dir = 0; } else if (lsame_(id, "I")) { dir = 1; } if (dir == -1) { *info = -1; } else if (*n < 0) { *info = -2; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASRT", &i__1, (ftnlen)6); return 0; } /* Quick return if possible */ if (*n <= 1) { return 0; } stkpnt = 1; stack[0] = 1; stack[1] = *n; L10: start = stack[(stkpnt << 1) - 2]; endd = stack[(stkpnt << 1) - 1]; --stkpnt; if (endd - start <= 20 && endd - start > 0) { /* Do Insertion sort on D( START:ENDD ) */ if (dir == 0) { /* Sort into decreasing order */ i__1 = endd; for (i__ = start + 1; i__ <= i__1; ++i__) { i__2 = start + 1; for (j = i__; j >= i__2; --j) { if (d__[j] > d__[j - 1]) { dmnmx = d__[j]; d__[j] = d__[j - 1]; d__[j - 1] = dmnmx; } else { goto L30; } /* L20: */ } L30: ; } } else { /* Sort into increasing order */ i__1 = endd; for (i__ = start + 1; i__ <= i__1; ++i__) { i__2 = start + 1; for (j = i__; j >= i__2; --j) { if (d__[j] < d__[j - 1]) { dmnmx = d__[j]; d__[j] = d__[j - 1]; d__[j - 1] = dmnmx; } else { goto L50; } /* L40: */ } L50: ; } } } else if (endd - start > 20) { /* Partition D( START:ENDD ) and stack parts, largest one first */ /* Choose partition entry as median of 3 */ d1 = d__[start]; d2 = d__[endd]; i__ = (start + endd) / 2; d3 = d__[i__]; if (d1 < d2) { if (d3 < d1) { dmnmx = d1; } else if (d3 < d2) { dmnmx = d3; } else { dmnmx = d2; } } else { if (d3 < d2) { dmnmx = d2; } else if (d3 < d1) { dmnmx = d3; } else { dmnmx = d1; } } if (dir == 0) { /* Sort into decreasing order */ i__ = start - 1; j = endd + 1; L60: L70: --j; if (d__[j] < dmnmx) { goto L70; } L80: ++i__; if (d__[i__] > dmnmx) { goto L80; } if (i__ < j) { tmp = d__[i__]; d__[i__] = d__[j]; d__[j] = tmp; goto L60; } if (j - start > endd - j - 1) { ++stkpnt; stack[(stkpnt << 1) - 2] = start; stack[(stkpnt << 1) - 1] = j; ++stkpnt; stack[(stkpnt << 1) - 2] = j + 1; stack[(stkpnt << 1) - 1] = endd; } else { ++stkpnt; stack[(stkpnt << 1) - 2] = j + 1; stack[(stkpnt << 1) - 1] = endd; ++stkpnt; stack[(stkpnt << 1) - 2] = start; stack[(stkpnt << 1) - 1] = j; } } else { /* Sort into increasing order */ i__ = start - 1; j = endd + 1; L90: L100: --j; if (d__[j] > dmnmx) { goto L100; } L110: ++i__; if (d__[i__] < dmnmx) { goto L110; } if (i__ < j) { tmp = d__[i__]; d__[i__] = d__[j]; d__[j] = tmp; goto L90; } if (j - start > endd - j - 1) { ++stkpnt; stack[(stkpnt << 1) - 2] = start; stack[(stkpnt << 1) - 1] = j; ++stkpnt; stack[(stkpnt << 1) - 2] = j + 1; stack[(stkpnt << 1) - 1] = endd; } else { ++stkpnt; stack[(stkpnt << 1) - 2] = j + 1; stack[(stkpnt << 1) - 1] = endd; ++stkpnt; stack[(stkpnt << 1) - 2] = start; stack[(stkpnt << 1) - 1] = j; } } } if (stkpnt > 0) { goto L10; } return 0; /* End of DLASRT */ } /* dlasrt_ */
the_stack_data/36075576.c
/* DO NOT EDIT! ** This file is automatically generated by the script in the canonical ** SQLite source tree at tool/mkshellc.tcl. That script combines source ** code from various constituent source files of SQLite into this single ** "shell.c" file used to implement the SQLite command-line shell. ** ** Most of the code found below comes from the "src/shell.c.in" file in ** the canonical SQLite source tree. That main file contains "INCLUDE" ** lines that specify other files in the canonical source tree that are ** inserted to getnerate this complete program source file. ** ** The code from multiple files is combined into this single "shell.c" ** source file to help make the command-line program easier to compile. ** ** To modify this program, get a copy of the canonical SQLite source tree, ** edit the src/shell.c.in" and/or some of the other files that are included ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script. */ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code to implement the "sqlite" command line ** utility for accessing SQLite databases. */ #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) /* This needs to come before any includes for MSVC compiler */ #define _CRT_SECURE_NO_WARNINGS #endif /* ** Warning pragmas copied from msvc.h in the core. */ #if defined(_MSC_VER) #pragma warning(disable : 4054) #pragma warning(disable : 4055) #pragma warning(disable : 4100) #pragma warning(disable : 4127) #pragma warning(disable : 4130) #pragma warning(disable : 4152) #pragma warning(disable : 4189) #pragma warning(disable : 4206) #pragma warning(disable : 4210) #pragma warning(disable : 4232) #pragma warning(disable : 4244) #pragma warning(disable : 4305) #pragma warning(disable : 4306) #pragma warning(disable : 4702) #pragma warning(disable : 4706) #endif /* defined(_MSC_VER) */ /* ** No support for loadable extensions in VxWorks. */ #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION # define SQLITE_OMIT_LOAD_EXTENSION 1 #endif /* ** Enable large-file support for fopen() and friends on unix. */ #ifndef SQLITE_DISABLE_LFS # define _LARGE_FILE 1 # ifndef _FILE_OFFSET_BITS # define _FILE_OFFSET_BITS 64 # endif # define _LARGEFILE_SOURCE 1 #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> #include "sqlite3.h" typedef sqlite3_int64 i64; typedef sqlite3_uint64 u64; typedef unsigned char u8; #if SQLITE_USER_AUTHENTICATION # include "sqlite3userauth.h" #endif #include <ctype.h> #include <stdarg.h> #if !defined(_WIN32) && !defined(WIN32) # include <signal.h> # if !defined(__RTP__) && !defined(_WRS_KERNEL) # include <pwd.h> # endif #endif #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) # include <unistd.h> # include <dirent.h> # if defined(__MINGW32__) # define DIRENT dirent # ifndef S_ISLNK # define S_ISLNK(mode) (0) # endif # endif #endif #include <sys/types.h> #include <sys/stat.h> #if HAVE_READLINE # include <readline/readline.h> # include <readline/history.h> #endif #if HAVE_EDITLINE # include <editline/readline.h> #endif #if HAVE_EDITLINE || HAVE_READLINE # define shell_add_history(X) add_history(X) # define shell_read_history(X) read_history(X) # define shell_write_history(X) write_history(X) # define shell_stifle_history(X) stifle_history(X) # define shell_readline(X) readline(X) #elif HAVE_LINENOISE # include "linenoise.h" # define shell_add_history(X) linenoiseHistoryAdd(X) # define shell_read_history(X) linenoiseHistoryLoad(X) # define shell_write_history(X) linenoiseHistorySave(X) # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) # define shell_readline(X) linenoise(X) #else # define shell_read_history(X) # define shell_write_history(X) # define shell_stifle_history(X) # define SHELL_USE_LOCAL_GETLINE 1 #endif #if defined(_WIN32) || defined(WIN32) # include <io.h> # include <fcntl.h> # define isatty(h) _isatty(h) # ifndef access # define access(f,m) _access((f),(m)) # endif # ifndef unlink # define unlink _unlink # endif # undef popen # define popen _popen # undef pclose # define pclose _pclose #else /* Make sure isatty() has a prototype. */ extern int isatty(int); # if !defined(__RTP__) && !defined(_WRS_KERNEL) /* popen and pclose are not C89 functions and so are ** sometimes omitted from the <stdio.h> header */ extern FILE *popen(const char*,const char*); extern int pclose(FILE*); # else # define SQLITE_OMIT_POPEN 1 # endif #endif #if defined(_WIN32_WCE) /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() * thus we always assume that we have a console. That can be * overridden with the -batch command line option. */ #define isatty(x) 1 #endif /* ctype macros that work with signed characters */ #define IsSpace(X) isspace((unsigned char)X) #define IsDigit(X) isdigit((unsigned char)X) #define ToLower(X) (char)tolower((unsigned char)X) #if defined(_WIN32) || defined(WIN32) #include <windows.h> /* string conversion routines only needed on Win32 */ extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int); extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int); extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText); #endif /* On Windows, we normally run with output mode of TEXT so that \n characters ** are automatically translated into \r\n. However, this behavior needs ** to be disabled in some cases (ex: when generating CSV output and when ** rendering quoted strings that contain \n characters). The following ** routines take care of that. */ #if defined(_WIN32) || defined(WIN32) static void setBinaryMode(FILE *file, int isOutput){ if( isOutput ) fflush(file); _setmode(_fileno(file), _O_BINARY); } static void setTextMode(FILE *file, int isOutput){ if( isOutput ) fflush(file); _setmode(_fileno(file), _O_TEXT); } #else # define setBinaryMode(X,Y) # define setTextMode(X,Y) #endif /* True if the timer is enabled */ static int enableTimer = 0; /* Return the current wall-clock time */ static sqlite3_int64 timeOfDay(void){ static sqlite3_vfs *clockVfs = 0; sqlite3_int64 t; if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ clockVfs->xCurrentTimeInt64(clockVfs, &t); }else{ double r; clockVfs->xCurrentTime(clockVfs, &r); t = (sqlite3_int64)(r*86400000.0); } return t; } #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) #include <sys/time.h> #include <sys/resource.h> /* VxWorks does not support getrusage() as far as we can determine */ #if defined(_WRS_KERNEL) || defined(__RTP__) struct rusage { struct timeval ru_utime; /* user CPU time used */ struct timeval ru_stime; /* system CPU time used */ }; #define getrusage(A,B) memset(B,0,sizeof(*B)) #endif /* Saved resource information for the beginning of an operation */ static struct rusage sBegin; /* CPU time at start */ static sqlite3_int64 iBegin; /* Wall-clock time at start */ /* ** Begin timing an operation */ static void beginTimer(void){ if( enableTimer ){ getrusage(RUSAGE_SELF, &sBegin); iBegin = timeOfDay(); } } /* Return the difference of two time_structs in seconds */ static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + (double)(pEnd->tv_sec - pStart->tv_sec); } /* ** Print the timing results. */ static void endTimer(void){ if( enableTimer ){ sqlite3_int64 iEnd = timeOfDay(); struct rusage sEnd; getrusage(RUSAGE_SELF, &sEnd); printf("Run Time: real %.3f user %f sys %f\n", (iEnd - iBegin)*0.001, timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); } } #define BEGIN_TIMER beginTimer() #define END_TIMER endTimer() #define HAS_TIMER 1 #elif (defined(_WIN32) || defined(WIN32)) /* Saved resource information for the beginning of an operation */ static HANDLE hProcess; static FILETIME ftKernelBegin; static FILETIME ftUserBegin; static sqlite3_int64 ftWallBegin; typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME); static GETPROCTIMES getProcessTimesAddr = NULL; /* ** Check to see if we have timer support. Return 1 if necessary ** support found (or found previously). */ static int hasTimer(void){ if( getProcessTimesAddr ){ return 1; } else { /* GetProcessTimes() isn't supported in WIN95 and some other Windows ** versions. See if the version we are running on has it, and if it ** does, save off a pointer to it and the current process handle. */ hProcess = GetCurrentProcess(); if( hProcess ){ HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); if( NULL != hinstLib ){ getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); if( NULL != getProcessTimesAddr ){ return 1; } FreeLibrary(hinstLib); } } } return 0; } /* ** Begin timing an operation */ static void beginTimer(void){ if( enableTimer && getProcessTimesAddr ){ FILETIME ftCreation, ftExit; getProcessTimesAddr(hProcess,&ftCreation,&ftExit, &ftKernelBegin,&ftUserBegin); ftWallBegin = timeOfDay(); } } /* Return the difference of two FILETIME structs in seconds */ static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ sqlite_int64 i64Start = *((sqlite_int64 *) pStart); sqlite_int64 i64End = *((sqlite_int64 *) pEnd); return (double) ((i64End - i64Start) / 10000000.0); } /* ** Print the timing results. */ static void endTimer(void){ if( enableTimer && getProcessTimesAddr){ FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; sqlite3_int64 ftWallEnd = timeOfDay(); getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); printf("Run Time: real %.3f user %f sys %f\n", (ftWallEnd - ftWallBegin)*0.001, timeDiff(&ftUserBegin, &ftUserEnd), timeDiff(&ftKernelBegin, &ftKernelEnd)); } } #define BEGIN_TIMER beginTimer() #define END_TIMER endTimer() #define HAS_TIMER hasTimer() #else #define BEGIN_TIMER #define END_TIMER #define HAS_TIMER 0 #endif /* ** Used to prevent warnings about unused parameters */ #define UNUSED_PARAMETER(x) (void)(x) /* ** Number of elements in an array */ #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) /* ** If the following flag is set, then command execution stops ** at an error if we are not interactive. */ static int bail_on_error = 0; /* ** Threat stdin as an interactive input if the following variable ** is true. Otherwise, assume stdin is connected to a file or pipe. */ static int stdin_is_interactive = 1; /* ** On Windows systems we have to know if standard output is a console ** in order to translate UTF-8 into MBCS. The following variable is ** true if translation is required. */ static int stdout_is_console = 1; /* ** The following is the open SQLite database. We make a pointer ** to this database a static variable so that it can be accessed ** by the SIGINT handler to interrupt database processing. */ static sqlite3 *globalDb = 0; /* ** True if an interrupt (Control-C) has been received. */ static volatile int seenInterrupt = 0; /* ** This is the name of our program. It is set in main(), used ** in a number of other places, mostly for error messages. */ static char *Argv0; /* ** Prompt strings. Initialized in main. Settable with ** .prompt main continue */ static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ /* ** Render output like fprintf(). Except, if the output is going to the ** console and if this is running on a Windows machine, translate the ** output from UTF-8 into MBCS. */ #if defined(_WIN32) || defined(WIN32) void utf8_printf(FILE *out, const char *zFormat, ...){ va_list ap; va_start(ap, zFormat); if( stdout_is_console && (out==stdout || out==stderr) ){ char *z1 = sqlite3_vmprintf(zFormat, ap); char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); sqlite3_free(z1); fputs(z2, out); sqlite3_free(z2); }else{ vfprintf(out, zFormat, ap); } va_end(ap); } #elif !defined(utf8_printf) # define utf8_printf fprintf #endif /* ** Render output like fprintf(). This should not be used on anything that ** includes string formatting (e.g. "%s"). */ #if !defined(raw_printf) # define raw_printf fprintf #endif /* ** Write I/O traces to the following stream. */ #ifdef SQLITE_ENABLE_IOTRACE static FILE *iotrace = 0; #endif /* ** This routine works like printf in that its first argument is a ** format string and subsequent arguments are values to be substituted ** in place of % fields. The result of formatting this string ** is written to iotrace. */ #ifdef SQLITE_ENABLE_IOTRACE static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ va_list ap; char *z; if( iotrace==0 ) return; va_start(ap, zFormat); z = sqlite3_vmprintf(zFormat, ap); va_end(ap); utf8_printf(iotrace, "%s", z); sqlite3_free(z); } #endif /* ** Output string zUtf to stream pOut as w characters. If w is negative, ** then right-justify the text. W is the width in UTF-8 characters, not ** in bytes. This is different from the %*.*s specification in printf ** since with %*.*s the width is measured in bytes, not characters. */ static void utf8_width_print(FILE *pOut, int w, const char *zUtf){ int i; int n; int aw = w<0 ? -w : w; char zBuf[1000]; if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3; for(i=n=0; zUtf[i]; i++){ if( (zUtf[i]&0xc0)!=0x80 ){ n++; if( n==aw ){ do{ i++; }while( (zUtf[i]&0xc0)==0x80 ); break; } } } if( n>=aw ){ utf8_printf(pOut, "%.*s", i, zUtf); }else if( w<0 ){ utf8_printf(pOut, "%*s%s", aw-n, "", zUtf); }else{ utf8_printf(pOut, "%s%*s", zUtf, aw-n, ""); } } /* ** Determines if a string is a number of not. */ static int isNumber(const char *z, int *realnum){ if( *z=='-' || *z=='+' ) z++; if( !IsDigit(*z) ){ return 0; } z++; if( realnum ) *realnum = 0; while( IsDigit(*z) ){ z++; } if( *z=='.' ){ z++; if( !IsDigit(*z) ) return 0; while( IsDigit(*z) ){ z++; } if( realnum ) *realnum = 1; } if( *z=='e' || *z=='E' ){ z++; if( *z=='+' || *z=='-' ) z++; if( !IsDigit(*z) ) return 0; while( IsDigit(*z) ){ z++; } if( realnum ) *realnum = 1; } return *z==0; } /* ** Compute a string length that is limited to what can be stored in ** lower 30 bits of a 32-bit signed integer. */ static int strlen30(const char *z){ const char *z2 = z; while( *z2 ){ z2++; } return 0x3fffffff & (int)(z2 - z); } /* ** Return the length of a string in characters. Multibyte UTF8 characters ** count as a single character. */ static int strlenChar(const char *z){ int n = 0; while( *z ){ if( (0xc0&*(z++))!=0x80 ) n++; } return n; } /* ** This routine reads a line of text from FILE in, stores ** the text in memory obtained from malloc() and returns a pointer ** to the text. NULL is returned at end of file, or if malloc() ** fails. ** ** If zLine is not NULL then it is a malloced buffer returned from ** a previous call to this routine that may be reused. */ static char *local_getline(char *zLine, FILE *in){ int nLine = zLine==0 ? 0 : 100; int n = 0; while( 1 ){ if( n+100>nLine ){ nLine = nLine*2 + 100; zLine = realloc(zLine, nLine); if( zLine==0 ) return 0; } if( fgets(&zLine[n], nLine - n, in)==0 ){ if( n==0 ){ free(zLine); return 0; } zLine[n] = 0; break; } while( zLine[n] ) n++; if( n>0 && zLine[n-1]=='\n' ){ n--; if( n>0 && zLine[n-1]=='\r' ) n--; zLine[n] = 0; break; } } #if defined(_WIN32) || defined(WIN32) /* For interactive input on Windows systems, translate the ** multi-byte characterset characters into UTF-8. */ if( stdin_is_interactive && in==stdin ){ char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); if( zTrans ){ int nTrans = strlen30(zTrans)+1; if( nTrans>nLine ){ zLine = realloc(zLine, nTrans); if( zLine==0 ){ sqlite3_free(zTrans); return 0; } } memcpy(zLine, zTrans, nTrans); sqlite3_free(zTrans); } } #endif /* defined(_WIN32) || defined(WIN32) */ return zLine; } /* ** Retrieve a single line of input text. ** ** If in==0 then read from standard input and prompt before each line. ** If isContinuation is true, then a continuation prompt is appropriate. ** If isContinuation is zero, then the main prompt should be used. ** ** If zPrior is not NULL then it is a buffer from a prior call to this ** routine that can be reused. ** ** The result is stored in space obtained from malloc() and must either ** be freed by the caller or else passed back into this routine via the ** zPrior argument for reuse. */ static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ char *zPrompt; char *zResult; if( in!=0 ){ zResult = local_getline(zPrior, in); }else{ zPrompt = isContinuation ? continuePrompt : mainPrompt; #if SHELL_USE_LOCAL_GETLINE printf("%s", zPrompt); fflush(stdout); zResult = local_getline(zPrior, stdin); #else free(zPrior); zResult = shell_readline(zPrompt); if( zResult && *zResult ) shell_add_history(zResult); #endif } return zResult; } /* ** Return the value of a hexadecimal digit. Return -1 if the input ** is not a hex digit. */ static int hexDigitValue(char c){ if( c>='0' && c<='9' ) return c - '0'; if( c>='a' && c<='f' ) return c - 'a' + 10; if( c>='A' && c<='F' ) return c - 'A' + 10; return -1; } /* ** Interpret zArg as an integer value, possibly with suffixes. */ static sqlite3_int64 integerValue(const char *zArg){ sqlite3_int64 v = 0; static const struct { char *zSuffix; int iMult; } aMult[] = { { "KiB", 1024 }, { "MiB", 1024*1024 }, { "GiB", 1024*1024*1024 }, { "KB", 1000 }, { "MB", 1000000 }, { "GB", 1000000000 }, { "K", 1000 }, { "M", 1000000 }, { "G", 1000000000 }, }; int i; int isNeg = 0; if( zArg[0]=='-' ){ isNeg = 1; zArg++; }else if( zArg[0]=='+' ){ zArg++; } if( zArg[0]=='0' && zArg[1]=='x' ){ int x; zArg += 2; while( (x = hexDigitValue(zArg[0]))>=0 ){ v = (v<<4) + x; zArg++; } }else{ while( IsDigit(zArg[0]) ){ v = v*10 + zArg[0] - '0'; zArg++; } } for(i=0; i<ArraySize(aMult); i++){ if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ v *= aMult[i].iMult; break; } } return isNeg? -v : v; } /* ** A variable length string to which one can append text. */ typedef struct ShellText ShellText; struct ShellText { char *z; int n; int nAlloc; }; /* ** Initialize and destroy a ShellText object */ static void initText(ShellText *p){ memset(p, 0, sizeof(*p)); } static void freeText(ShellText *p){ free(p->z); initText(p); } /* zIn is either a pointer to a NULL-terminated string in memory obtained ** from malloc(), or a NULL pointer. The string pointed to by zAppend is ** added to zIn, and the result returned in memory obtained from malloc(). ** zIn, if it was not NULL, is freed. ** ** If the third argument, quote, is not '\0', then it is used as a ** quote character for zAppend. */ static void appendText(ShellText *p, char const *zAppend, char quote){ int len; int i; int nAppend = strlen30(zAppend); len = nAppend+p->n+1; if( quote ){ len += 2; for(i=0; i<nAppend; i++){ if( zAppend[i]==quote ) len++; } } if( p->n+len>=p->nAlloc ){ p->nAlloc = p->nAlloc*2 + len + 20; p->z = realloc(p->z, p->nAlloc); if( p->z==0 ){ memset(p, 0, sizeof(*p)); return; } } if( quote ){ char *zCsr = p->z+p->n; *zCsr++ = quote; for(i=0; i<nAppend; i++){ *zCsr++ = zAppend[i]; if( zAppend[i]==quote ) *zCsr++ = quote; } *zCsr++ = quote; p->n = (int)(zCsr - p->z); *zCsr = '\0'; }else{ memcpy(p->z+p->n, zAppend, nAppend); p->n += nAppend; p->z[p->n] = '\0'; } } /* ** Attempt to determine if identifier zName needs to be quoted, either ** because it contains non-alphanumeric characters, or because it is an ** SQLite keyword. Be conservative in this estimate: When in doubt assume ** that quoting is required. ** ** Return '"' if quoting is required. Return 0 if no quoting is required. */ static char quoteChar(const char *zName){ /* All SQLite keywords, in alphabetical order */ static const char *azKeywords[] = { "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY", "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT", "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH", "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN", "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF", "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER", "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY", "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL", "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA", "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP", "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT", "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP", "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE", "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE", "WITH", "WITHOUT", }; int i, lwr, upr, mid, c; if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; for(i=0; zName[i]; i++){ if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; } lwr = 0; upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1; while( lwr<=upr ){ mid = (lwr+upr)/2; c = sqlite3_stricmp(azKeywords[mid], zName); if( c==0 ) return '"'; if( c<0 ){ lwr = mid+1; }else{ upr = mid-1; } } return 0; } /* ** Construct a fake object name and column list to describe the structure ** of the view, virtual table, or table valued function zSchema.zName. */ static char *shellFakeSchema( sqlite3 *db, /* The database connection containing the vtab */ const char *zSchema, /* Schema of the database holding the vtab */ const char *zName /* The name of the virtual table */ ){ sqlite3_stmt *pStmt = 0; char *zSql; ShellText s; char cQuote; char *zDiv = "("; int nRow = 0; zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", zSchema ? zSchema : "main", zName); sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); initText(&s); if( zSchema ){ cQuote = quoteChar(zSchema); if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; appendText(&s, zSchema, cQuote); appendText(&s, ".", 0); } cQuote = quoteChar(zName); appendText(&s, zName, cQuote); while( sqlite3_step(pStmt)==SQLITE_ROW ){ const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); nRow++; appendText(&s, zDiv, 0); zDiv = ","; cQuote = quoteChar(zCol); appendText(&s, zCol, cQuote); } appendText(&s, ")", 0); sqlite3_finalize(pStmt); if( nRow==0 ){ freeText(&s); s.z = 0; } return s.z; } /* ** SQL function: shell_module_schema(X) ** ** Return a fake schema for the table-valued function or eponymous virtual ** table X. */ static void shellModuleSchema( sqlite3_context *pCtx, int nVal, sqlite3_value **apVal ){ const char *zName = (const char*)sqlite3_value_text(apVal[0]); char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName); UNUSED_PARAMETER(nVal); if( zFake ){ sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), -1, sqlite3_free); free(zFake); } } /* ** SQL function: shell_add_schema(S,X) ** ** Add the schema name X to the CREATE statement in S and return the result. ** Examples: ** ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); ** ** Also works on ** ** CREATE INDEX ** CREATE UNIQUE INDEX ** CREATE VIEW ** CREATE TRIGGER ** CREATE VIRTUAL TABLE ** ** This UDF is used by the .schema command to insert the schema name of ** attached databases into the middle of the sqlite_master.sql field. */ static void shellAddSchemaName( sqlite3_context *pCtx, int nVal, sqlite3_value **apVal ){ static const char *aPrefix[] = { "TABLE", "INDEX", "UNIQUE INDEX", "VIEW", "TRIGGER", "VIRTUAL TABLE" }; int i = 0; const char *zIn = (const char*)sqlite3_value_text(apVal[0]); const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); const char *zName = (const char*)sqlite3_value_text(apVal[2]); sqlite3 *db = sqlite3_context_db_handle(pCtx); UNUSED_PARAMETER(nVal); if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){ for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){ int n = strlen30(aPrefix[i]); if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ char *z = 0; char *zFake = 0; if( zSchema ){ char cQuote = quoteChar(zSchema); if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8); }else{ z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); } } if( zName && aPrefix[i][0]=='V' && (zFake = shellFakeSchema(db, zSchema, zName))!=0 ){ if( z==0 ){ z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake); }else{ z = sqlite3_mprintf("%z\n/* %s */", z, zFake); } free(zFake); } if( z ){ sqlite3_result_text(pCtx, z, -1, sqlite3_free); return; } } } } sqlite3_result_value(pCtx, apVal[0]); } /* ** The source code for several run-time loadable extensions is inserted ** below by the ../tool/mkshellc.tcl script. Before processing that included ** code, we need to override some macros to make the included program code ** work here in the middle of this regular program. */ #define SQLITE_EXTENSION_INIT1 #define SQLITE_EXTENSION_INIT2(X) (void)(X) #if defined(_WIN32) && defined(_MSC_VER) /************************* Begin test_windirent.h ******************/ /* ** 2015 November 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains declarations for most of the opendir() family of ** POSIX functions on Win32 using the MSVCRT. */ #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H) #define SQLITE_WINDIRENT_H /* ** We need several data types from the Windows SDK header. */ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include "windows.h" /* ** We need several support functions from the SQLite core. */ /* ** We need several things from the ANSI and MSVCRT headers. */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <io.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> /* ** We may need several defines that should have been in "sys/stat.h". */ #ifndef S_ISREG #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) #endif #ifndef S_ISDIR #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) #endif #ifndef S_ISLNK #define S_ISLNK(mode) (0) #endif /* ** We may need to provide the "mode_t" type. */ #ifndef MODE_T_DEFINED #define MODE_T_DEFINED typedef unsigned short mode_t; #endif /* ** We may need to provide the "ino_t" type. */ #ifndef INO_T_DEFINED #define INO_T_DEFINED typedef unsigned short ino_t; #endif /* ** We need to define "NAME_MAX" if it was not present in "limits.h". */ #ifndef NAME_MAX # ifdef FILENAME_MAX # define NAME_MAX (FILENAME_MAX) # else # define NAME_MAX (260) # endif #endif /* ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T". */ #ifndef NULL_INTPTR_T # define NULL_INTPTR_T ((intptr_t)(0)) #endif #ifndef BAD_INTPTR_T # define BAD_INTPTR_T ((intptr_t)(-1)) #endif /* ** We need to provide the necessary structures and related types. */ #ifndef DIRENT_DEFINED #define DIRENT_DEFINED typedef struct DIRENT DIRENT; typedef DIRENT *LPDIRENT; struct DIRENT { ino_t d_ino; /* Sequence number, do not use. */ unsigned d_attributes; /* Win32 file attributes. */ char d_name[NAME_MAX + 1]; /* Name within the directory. */ }; #endif #ifndef DIR_DEFINED #define DIR_DEFINED typedef struct DIR DIR; typedef DIR *LPDIR; struct DIR { intptr_t d_handle; /* Value returned by "_findfirst". */ DIRENT d_first; /* DIRENT constructed based on "_findfirst". */ DIRENT d_next; /* DIRENT constructed based on "_findnext". */ }; #endif /* ** Provide a macro, for use by the implementation, to determine if a ** particular directory entry should be skipped over when searching for ** the next directory entry that should be returned by the readdir() or ** readdir_r() functions. */ #ifndef is_filtered # define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM)) #endif /* ** Provide the function prototype for the POSIX compatiable getenv() ** function. This function is not thread-safe. */ extern const char *windirent_getenv(const char *name); /* ** Finally, we can provide the function prototypes for the opendir(), ** readdir(), readdir_r(), and closedir() POSIX functions. */ extern LPDIR opendir(const char *dirname); extern LPDIRENT readdir(LPDIR dirp); extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result); extern INT closedir(LPDIR dirp); #endif /* defined(WIN32) && defined(_MSC_VER) */ /************************* End test_windirent.h ********************/ /************************* Begin test_windirent.c ******************/ /* ** 2015 November 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code to implement most of the opendir() family of ** POSIX functions on Win32 using the MSVCRT. */ #if defined(_WIN32) && defined(_MSC_VER) /* #include "test_windirent.h" */ /* ** Implementation of the POSIX getenv() function using the Win32 API. ** This function is not thread-safe. */ const char *windirent_getenv( const char *name ){ static char value[32768]; /* Maximum length, per MSDN */ DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */ DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */ memset(value, 0, sizeof(value)); dwRet = GetEnvironmentVariableA(name, value, dwSize); if( dwRet==0 || dwRet>dwSize ){ /* ** The function call to GetEnvironmentVariableA() failed -OR- ** the buffer is not large enough. Either way, return NULL. */ return 0; }else{ /* ** The function call to GetEnvironmentVariableA() succeeded ** -AND- the buffer contains the entire value. */ return value; } } /* ** Implementation of the POSIX opendir() function using the MSVCRT. */ LPDIR opendir( const char *dirname ){ struct _finddata_t data; LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR)); SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]); if( dirp==NULL ) return NULL; memset(dirp, 0, sizeof(DIR)); /* TODO: Remove this if Unix-style root paths are not used. */ if( sqlite3_stricmp(dirname, "/")==0 ){ dirname = windirent_getenv("SystemDrive"); } memset(&data, 0, sizeof(struct _finddata_t)); _snprintf(data.name, namesize, "%s\\*", dirname); dirp->d_handle = _findfirst(data.name, &data); if( dirp->d_handle==BAD_INTPTR_T ){ closedir(dirp); return NULL; } /* TODO: Remove this block to allow hidden and/or system files. */ if( is_filtered(data) ){ next: memset(&data, 0, sizeof(struct _finddata_t)); if( _findnext(dirp->d_handle, &data)==-1 ){ closedir(dirp); return NULL; } /* TODO: Remove this block to allow hidden and/or system files. */ if( is_filtered(data) ) goto next; } dirp->d_first.d_attributes = data.attrib; strncpy(dirp->d_first.d_name, data.name, NAME_MAX); dirp->d_first.d_name[NAME_MAX] = '\0'; return dirp; } /* ** Implementation of the POSIX readdir() function using the MSVCRT. */ LPDIRENT readdir( LPDIR dirp ){ struct _finddata_t data; if( dirp==NULL ) return NULL; if( dirp->d_first.d_ino==0 ){ dirp->d_first.d_ino++; dirp->d_next.d_ino++; return &dirp->d_first; } next: memset(&data, 0, sizeof(struct _finddata_t)); if( _findnext(dirp->d_handle, &data)==-1 ) return NULL; /* TODO: Remove this block to allow hidden and/or system files. */ if( is_filtered(data) ) goto next; dirp->d_next.d_ino++; dirp->d_next.d_attributes = data.attrib; strncpy(dirp->d_next.d_name, data.name, NAME_MAX); dirp->d_next.d_name[NAME_MAX] = '\0'; return &dirp->d_next; } /* ** Implementation of the POSIX readdir_r() function using the MSVCRT. */ INT readdir_r( LPDIR dirp, LPDIRENT entry, LPDIRENT *result ){ struct _finddata_t data; if( dirp==NULL ) return EBADF; if( dirp->d_first.d_ino==0 ){ dirp->d_first.d_ino++; dirp->d_next.d_ino++; entry->d_ino = dirp->d_first.d_ino; entry->d_attributes = dirp->d_first.d_attributes; strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX); entry->d_name[NAME_MAX] = '\0'; *result = entry; return 0; } next: memset(&data, 0, sizeof(struct _finddata_t)); if( _findnext(dirp->d_handle, &data)==-1 ){ *result = NULL; return ENOENT; } /* TODO: Remove this block to allow hidden and/or system files. */ if( is_filtered(data) ) goto next; entry->d_ino = (ino_t)-1; /* not available */ entry->d_attributes = data.attrib; strncpy(entry->d_name, data.name, NAME_MAX); entry->d_name[NAME_MAX] = '\0'; *result = entry; return 0; } /* ** Implementation of the POSIX closedir() function using the MSVCRT. */ INT closedir( LPDIR dirp ){ INT result = 0; if( dirp==NULL ) return EINVAL; if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){ result = _findclose(dirp->d_handle); } sqlite3_free(dirp); return result; } #endif /* defined(WIN32) && defined(_MSC_VER) */ /************************* End test_windirent.c ********************/ #define dirent DIRENT #endif /************************* Begin ../ext/misc/shathree.c ******************/ /* ** 2017-03-08 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This SQLite extension implements a functions that compute SHA1 hashes. ** Two SQL functions are implemented: ** ** sha3(X,SIZE) ** sha3_query(Y,SIZE) ** ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if ** X is NULL. ** ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y ** and returns a hash of their results. ** ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm ** is used. If SIZE is included it must be one of the integers 224, 256, ** 384, or 512, to determine SHA3 hash variant that is computed. */ SQLITE_EXTENSION_INIT1 #include <assert.h> #include <string.h> #include <stdarg.h> /* typedef sqlite3_uint64 u64; */ /****************************************************************************** ** The Hash Engine */ /* ** Macros to determine whether the machine is big or little endian, ** and whether or not that determination is run-time or compile-time. ** ** For best performance, an attempt is made to guess at the byte-order ** using C-preprocessor macros. If that is unsuccessful, or if ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined ** at run-time. */ #ifndef SHA3_BYTEORDER # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ defined(__arm__) # define SHA3_BYTEORDER 1234 # elif defined(sparc) || defined(__ppc__) # define SHA3_BYTEORDER 4321 # else # define SHA3_BYTEORDER 0 # endif #endif /* ** State structure for a SHA3 hash in progress */ typedef struct SHA3Context SHA3Context; struct SHA3Context { union { u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */ unsigned char x[1600]; /* ... or 1600 bytes */ } u; unsigned nRate; /* Bytes of input accepted per Keccak iteration */ unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */ unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */ }; /* ** A single step of the Keccak mixing function for a 1600-bit state */ static void KeccakF1600Step(SHA3Context *p){ int i; u64 b0, b1, b2, b3, b4; u64 c0, c1, c2, c3, c4; u64 d0, d1, d2, d3, d4; static const u64 RC[] = { 0x0000000000000001ULL, 0x0000000000008082ULL, 0x800000000000808aULL, 0x8000000080008000ULL, 0x000000000000808bULL, 0x0000000080000001ULL, 0x8000000080008081ULL, 0x8000000000008009ULL, 0x000000000000008aULL, 0x0000000000000088ULL, 0x0000000080008009ULL, 0x000000008000000aULL, 0x000000008000808bULL, 0x800000000000008bULL, 0x8000000000008089ULL, 0x8000000000008003ULL, 0x8000000000008002ULL, 0x8000000000000080ULL, 0x000000000000800aULL, 0x800000008000000aULL, 0x8000000080008081ULL, 0x8000000000008080ULL, 0x0000000080000001ULL, 0x8000000080008008ULL }; # define a00 (p->u.s[0]) # define a01 (p->u.s[1]) # define a02 (p->u.s[2]) # define a03 (p->u.s[3]) # define a04 (p->u.s[4]) # define a10 (p->u.s[5]) # define a11 (p->u.s[6]) # define a12 (p->u.s[7]) # define a13 (p->u.s[8]) # define a14 (p->u.s[9]) # define a20 (p->u.s[10]) # define a21 (p->u.s[11]) # define a22 (p->u.s[12]) # define a23 (p->u.s[13]) # define a24 (p->u.s[14]) # define a30 (p->u.s[15]) # define a31 (p->u.s[16]) # define a32 (p->u.s[17]) # define a33 (p->u.s[18]) # define a34 (p->u.s[19]) # define a40 (p->u.s[20]) # define a41 (p->u.s[21]) # define a42 (p->u.s[22]) # define a43 (p->u.s[23]) # define a44 (p->u.s[24]) # define ROL64(a,x) ((a<<x)|(a>>(64-x))) for(i=0; i<24; i+=4){ c0 = a00^a10^a20^a30^a40; c1 = a01^a11^a21^a31^a41; c2 = a02^a12^a22^a32^a42; c3 = a03^a13^a23^a33^a43; c4 = a04^a14^a24^a34^a44; d0 = c4^ROL64(c1, 1); d1 = c0^ROL64(c2, 1); d2 = c1^ROL64(c3, 1); d3 = c2^ROL64(c4, 1); d4 = c3^ROL64(c0, 1); b0 = (a00^d0); b1 = ROL64((a11^d1), 44); b2 = ROL64((a22^d2), 43); b3 = ROL64((a33^d3), 21); b4 = ROL64((a44^d4), 14); a00 = b0 ^((~b1)& b2 ); a00 ^= RC[i]; a11 = b1 ^((~b2)& b3 ); a22 = b2 ^((~b3)& b4 ); a33 = b3 ^((~b4)& b0 ); a44 = b4 ^((~b0)& b1 ); b2 = ROL64((a20^d0), 3); b3 = ROL64((a31^d1), 45); b4 = ROL64((a42^d2), 61); b0 = ROL64((a03^d3), 28); b1 = ROL64((a14^d4), 20); a20 = b0 ^((~b1)& b2 ); a31 = b1 ^((~b2)& b3 ); a42 = b2 ^((~b3)& b4 ); a03 = b3 ^((~b4)& b0 ); a14 = b4 ^((~b0)& b1 ); b4 = ROL64((a40^d0), 18); b0 = ROL64((a01^d1), 1); b1 = ROL64((a12^d2), 6); b2 = ROL64((a23^d3), 25); b3 = ROL64((a34^d4), 8); a40 = b0 ^((~b1)& b2 ); a01 = b1 ^((~b2)& b3 ); a12 = b2 ^((~b3)& b4 ); a23 = b3 ^((~b4)& b0 ); a34 = b4 ^((~b0)& b1 ); b1 = ROL64((a10^d0), 36); b2 = ROL64((a21^d1), 10); b3 = ROL64((a32^d2), 15); b4 = ROL64((a43^d3), 56); b0 = ROL64((a04^d4), 27); a10 = b0 ^((~b1)& b2 ); a21 = b1 ^((~b2)& b3 ); a32 = b2 ^((~b3)& b4 ); a43 = b3 ^((~b4)& b0 ); a04 = b4 ^((~b0)& b1 ); b3 = ROL64((a30^d0), 41); b4 = ROL64((a41^d1), 2); b0 = ROL64((a02^d2), 62); b1 = ROL64((a13^d3), 55); b2 = ROL64((a24^d4), 39); a30 = b0 ^((~b1)& b2 ); a41 = b1 ^((~b2)& b3 ); a02 = b2 ^((~b3)& b4 ); a13 = b3 ^((~b4)& b0 ); a24 = b4 ^((~b0)& b1 ); c0 = a00^a20^a40^a10^a30; c1 = a11^a31^a01^a21^a41; c2 = a22^a42^a12^a32^a02; c3 = a33^a03^a23^a43^a13; c4 = a44^a14^a34^a04^a24; d0 = c4^ROL64(c1, 1); d1 = c0^ROL64(c2, 1); d2 = c1^ROL64(c3, 1); d3 = c2^ROL64(c4, 1); d4 = c3^ROL64(c0, 1); b0 = (a00^d0); b1 = ROL64((a31^d1), 44); b2 = ROL64((a12^d2), 43); b3 = ROL64((a43^d3), 21); b4 = ROL64((a24^d4), 14); a00 = b0 ^((~b1)& b2 ); a00 ^= RC[i+1]; a31 = b1 ^((~b2)& b3 ); a12 = b2 ^((~b3)& b4 ); a43 = b3 ^((~b4)& b0 ); a24 = b4 ^((~b0)& b1 ); b2 = ROL64((a40^d0), 3); b3 = ROL64((a21^d1), 45); b4 = ROL64((a02^d2), 61); b0 = ROL64((a33^d3), 28); b1 = ROL64((a14^d4), 20); a40 = b0 ^((~b1)& b2 ); a21 = b1 ^((~b2)& b3 ); a02 = b2 ^((~b3)& b4 ); a33 = b3 ^((~b4)& b0 ); a14 = b4 ^((~b0)& b1 ); b4 = ROL64((a30^d0), 18); b0 = ROL64((a11^d1), 1); b1 = ROL64((a42^d2), 6); b2 = ROL64((a23^d3), 25); b3 = ROL64((a04^d4), 8); a30 = b0 ^((~b1)& b2 ); a11 = b1 ^((~b2)& b3 ); a42 = b2 ^((~b3)& b4 ); a23 = b3 ^((~b4)& b0 ); a04 = b4 ^((~b0)& b1 ); b1 = ROL64((a20^d0), 36); b2 = ROL64((a01^d1), 10); b3 = ROL64((a32^d2), 15); b4 = ROL64((a13^d3), 56); b0 = ROL64((a44^d4), 27); a20 = b0 ^((~b1)& b2 ); a01 = b1 ^((~b2)& b3 ); a32 = b2 ^((~b3)& b4 ); a13 = b3 ^((~b4)& b0 ); a44 = b4 ^((~b0)& b1 ); b3 = ROL64((a10^d0), 41); b4 = ROL64((a41^d1), 2); b0 = ROL64((a22^d2), 62); b1 = ROL64((a03^d3), 55); b2 = ROL64((a34^d4), 39); a10 = b0 ^((~b1)& b2 ); a41 = b1 ^((~b2)& b3 ); a22 = b2 ^((~b3)& b4 ); a03 = b3 ^((~b4)& b0 ); a34 = b4 ^((~b0)& b1 ); c0 = a00^a40^a30^a20^a10; c1 = a31^a21^a11^a01^a41; c2 = a12^a02^a42^a32^a22; c3 = a43^a33^a23^a13^a03; c4 = a24^a14^a04^a44^a34; d0 = c4^ROL64(c1, 1); d1 = c0^ROL64(c2, 1); d2 = c1^ROL64(c3, 1); d3 = c2^ROL64(c4, 1); d4 = c3^ROL64(c0, 1); b0 = (a00^d0); b1 = ROL64((a21^d1), 44); b2 = ROL64((a42^d2), 43); b3 = ROL64((a13^d3), 21); b4 = ROL64((a34^d4), 14); a00 = b0 ^((~b1)& b2 ); a00 ^= RC[i+2]; a21 = b1 ^((~b2)& b3 ); a42 = b2 ^((~b3)& b4 ); a13 = b3 ^((~b4)& b0 ); a34 = b4 ^((~b0)& b1 ); b2 = ROL64((a30^d0), 3); b3 = ROL64((a01^d1), 45); b4 = ROL64((a22^d2), 61); b0 = ROL64((a43^d3), 28); b1 = ROL64((a14^d4), 20); a30 = b0 ^((~b1)& b2 ); a01 = b1 ^((~b2)& b3 ); a22 = b2 ^((~b3)& b4 ); a43 = b3 ^((~b4)& b0 ); a14 = b4 ^((~b0)& b1 ); b4 = ROL64((a10^d0), 18); b0 = ROL64((a31^d1), 1); b1 = ROL64((a02^d2), 6); b2 = ROL64((a23^d3), 25); b3 = ROL64((a44^d4), 8); a10 = b0 ^((~b1)& b2 ); a31 = b1 ^((~b2)& b3 ); a02 = b2 ^((~b3)& b4 ); a23 = b3 ^((~b4)& b0 ); a44 = b4 ^((~b0)& b1 ); b1 = ROL64((a40^d0), 36); b2 = ROL64((a11^d1), 10); b3 = ROL64((a32^d2), 15); b4 = ROL64((a03^d3), 56); b0 = ROL64((a24^d4), 27); a40 = b0 ^((~b1)& b2 ); a11 = b1 ^((~b2)& b3 ); a32 = b2 ^((~b3)& b4 ); a03 = b3 ^((~b4)& b0 ); a24 = b4 ^((~b0)& b1 ); b3 = ROL64((a20^d0), 41); b4 = ROL64((a41^d1), 2); b0 = ROL64((a12^d2), 62); b1 = ROL64((a33^d3), 55); b2 = ROL64((a04^d4), 39); a20 = b0 ^((~b1)& b2 ); a41 = b1 ^((~b2)& b3 ); a12 = b2 ^((~b3)& b4 ); a33 = b3 ^((~b4)& b0 ); a04 = b4 ^((~b0)& b1 ); c0 = a00^a30^a10^a40^a20; c1 = a21^a01^a31^a11^a41; c2 = a42^a22^a02^a32^a12; c3 = a13^a43^a23^a03^a33; c4 = a34^a14^a44^a24^a04; d0 = c4^ROL64(c1, 1); d1 = c0^ROL64(c2, 1); d2 = c1^ROL64(c3, 1); d3 = c2^ROL64(c4, 1); d4 = c3^ROL64(c0, 1); b0 = (a00^d0); b1 = ROL64((a01^d1), 44); b2 = ROL64((a02^d2), 43); b3 = ROL64((a03^d3), 21); b4 = ROL64((a04^d4), 14); a00 = b0 ^((~b1)& b2 ); a00 ^= RC[i+3]; a01 = b1 ^((~b2)& b3 ); a02 = b2 ^((~b3)& b4 ); a03 = b3 ^((~b4)& b0 ); a04 = b4 ^((~b0)& b1 ); b2 = ROL64((a10^d0), 3); b3 = ROL64((a11^d1), 45); b4 = ROL64((a12^d2), 61); b0 = ROL64((a13^d3), 28); b1 = ROL64((a14^d4), 20); a10 = b0 ^((~b1)& b2 ); a11 = b1 ^((~b2)& b3 ); a12 = b2 ^((~b3)& b4 ); a13 = b3 ^((~b4)& b0 ); a14 = b4 ^((~b0)& b1 ); b4 = ROL64((a20^d0), 18); b0 = ROL64((a21^d1), 1); b1 = ROL64((a22^d2), 6); b2 = ROL64((a23^d3), 25); b3 = ROL64((a24^d4), 8); a20 = b0 ^((~b1)& b2 ); a21 = b1 ^((~b2)& b3 ); a22 = b2 ^((~b3)& b4 ); a23 = b3 ^((~b4)& b0 ); a24 = b4 ^((~b0)& b1 ); b1 = ROL64((a30^d0), 36); b2 = ROL64((a31^d1), 10); b3 = ROL64((a32^d2), 15); b4 = ROL64((a33^d3), 56); b0 = ROL64((a34^d4), 27); a30 = b0 ^((~b1)& b2 ); a31 = b1 ^((~b2)& b3 ); a32 = b2 ^((~b3)& b4 ); a33 = b3 ^((~b4)& b0 ); a34 = b4 ^((~b0)& b1 ); b3 = ROL64((a40^d0), 41); b4 = ROL64((a41^d1), 2); b0 = ROL64((a42^d2), 62); b1 = ROL64((a43^d3), 55); b2 = ROL64((a44^d4), 39); a40 = b0 ^((~b1)& b2 ); a41 = b1 ^((~b2)& b3 ); a42 = b2 ^((~b3)& b4 ); a43 = b3 ^((~b4)& b0 ); a44 = b4 ^((~b0)& b1 ); } } /* ** Initialize a new hash. iSize determines the size of the hash ** in bits and should be one of 224, 256, 384, or 512. Or iSize ** can be zero to use the default hash size of 256 bits. */ static void SHA3Init(SHA3Context *p, int iSize){ memset(p, 0, sizeof(*p)); if( iSize>=128 && iSize<=512 ){ p->nRate = (1600 - ((iSize + 31)&~31)*2)/8; }else{ p->nRate = (1600 - 2*256)/8; } #if SHA3_BYTEORDER==1234 /* Known to be little-endian at compile-time. No-op */ #elif SHA3_BYTEORDER==4321 p->ixMask = 7; /* Big-endian */ #else { static unsigned int one = 1; if( 1==*(unsigned char*)&one ){ /* Little endian. No byte swapping. */ p->ixMask = 0; }else{ /* Big endian. Byte swap. */ p->ixMask = 7; } } #endif } /* ** Make consecutive calls to the SHA3Update function to add new content ** to the hash */ static void SHA3Update( SHA3Context *p, const unsigned char *aData, unsigned int nData ){ unsigned int i = 0; #if SHA3_BYTEORDER==1234 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){ for(; i+7<nData; i+=8){ p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i]; p->nLoaded += 8; if( p->nLoaded>=p->nRate ){ KeccakF1600Step(p); p->nLoaded = 0; } } } #endif for(; i<nData; i++){ #if SHA3_BYTEORDER==1234 p->u.x[p->nLoaded] ^= aData[i]; #elif SHA3_BYTEORDER==4321 p->u.x[p->nLoaded^0x07] ^= aData[i]; #else p->u.x[p->nLoaded^p->ixMask] ^= aData[i]; #endif p->nLoaded++; if( p->nLoaded==p->nRate ){ KeccakF1600Step(p); p->nLoaded = 0; } } } /* ** After all content has been added, invoke SHA3Final() to compute ** the final hash. The function returns a pointer to the binary ** hash value. */ static unsigned char *SHA3Final(SHA3Context *p){ unsigned int i; if( p->nLoaded==p->nRate-1 ){ const unsigned char c1 = 0x86; SHA3Update(p, &c1, 1); }else{ const unsigned char c2 = 0x06; const unsigned char c3 = 0x80; SHA3Update(p, &c2, 1); p->nLoaded = p->nRate - 1; SHA3Update(p, &c3, 1); } for(i=0; i<p->nRate; i++){ p->u.x[i+p->nRate] = p->u.x[i^p->ixMask]; } return &p->u.x[p->nRate]; } /* End of the hashing logic *****************************************************************************/ /* ** Implementation of the sha3(X,SIZE) function. ** ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default ** size is 256. If X is a BLOB, it is hashed as is. ** For all other non-NULL types of input, X is converted into a UTF-8 string ** and the string is hashed without the trailing 0x00 terminator. The hash ** of a NULL value is NULL. */ static void sha3Func( sqlite3_context *context, int argc, sqlite3_value **argv ){ SHA3Context cx; int eType = sqlite3_value_type(argv[0]); int nByte = sqlite3_value_bytes(argv[0]); int iSize; if( argc==1 ){ iSize = 256; }else{ iSize = sqlite3_value_int(argv[1]); if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " "384 512", -1); return; } } if( eType==SQLITE_NULL ) return; SHA3Init(&cx, iSize); if( eType==SQLITE_BLOB ){ SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte); }else{ SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte); } sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT); } /* Compute a string using sqlite3_vsnprintf() with a maximum length ** of 50 bytes and add it to the hash. */ static void hash_step_vformat( SHA3Context *p, /* Add content to this context */ const char *zFormat, ... ){ va_list ap; int n; char zBuf[50]; va_start(ap, zFormat); sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap); va_end(ap); n = (int)strlen(zBuf); SHA3Update(p, (unsigned char*)zBuf, n); } /* ** Implementation of the sha3_query(SQL,SIZE) function. ** ** This function compiles and runs the SQL statement(s) given in the ** argument. The results are hashed using a SIZE-bit SHA3. The default ** size is 256. ** ** The format of the byte stream that is hashed is summarized as follows: ** ** S<n>:<sql> ** R ** N ** I<int> ** F<ieee-float> ** B<size>:<bytes> ** T<size>:<text> ** ** <sql> is the original SQL text for each statement run and <n> is ** the size of that text. The SQL text is UTF-8. A single R character ** occurs before the start of each row. N means a NULL value. ** I mean an 8-byte little-endian integer <int>. F is a floating point ** number with an 8-byte little-endian IEEE floating point value <ieee-float>. ** B means blobs of <size> bytes. T means text rendered as <size> ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII ** text integers. ** ** For each SQL statement in the X input, there is one S segment. Each ** S segment is followed by zero or more R segments, one for each row in the ** result set. After each R, there are one or more N, I, F, B, or T segments, ** one for each column in the result set. Segments are concatentated directly ** with no delimiters of any kind. */ static void sha3QueryFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ sqlite3 *db = sqlite3_context_db_handle(context); const char *zSql = (const char*)sqlite3_value_text(argv[0]); sqlite3_stmt *pStmt = 0; int nCol; /* Number of columns in the result set */ int i; /* Loop counter */ int rc; int n; const char *z; SHA3Context cx; int iSize; if( argc==1 ){ iSize = 256; }else{ iSize = sqlite3_value_int(argv[1]); if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " "384 512", -1); return; } } if( zSql==0 ) return; SHA3Init(&cx, iSize); while( zSql[0] ){ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); if( rc ){ char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s", zSql, sqlite3_errmsg(db)); sqlite3_finalize(pStmt); sqlite3_result_error(context, zMsg, -1); sqlite3_free(zMsg); return; } if( !sqlite3_stmt_readonly(pStmt) ){ char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); sqlite3_finalize(pStmt); sqlite3_result_error(context, zMsg, -1); sqlite3_free(zMsg); return; } nCol = sqlite3_column_count(pStmt); z = sqlite3_sql(pStmt); n = (int)strlen(z); hash_step_vformat(&cx,"S%d:",n); SHA3Update(&cx,(unsigned char*)z,n); /* Compute a hash over the result of the query */ while( SQLITE_ROW==sqlite3_step(pStmt) ){ SHA3Update(&cx,(const unsigned char*)"R",1); for(i=0; i<nCol; i++){ switch( sqlite3_column_type(pStmt,i) ){ case SQLITE_NULL: { SHA3Update(&cx, (const unsigned char*)"N",1); break; } case SQLITE_INTEGER: { sqlite3_uint64 u; int j; unsigned char x[9]; sqlite3_int64 v = sqlite3_column_int64(pStmt,i); memcpy(&u, &v, 8); for(j=8; j>=1; j--){ x[j] = u & 0xff; u >>= 8; } x[0] = 'I'; SHA3Update(&cx, x, 9); break; } case SQLITE_FLOAT: { sqlite3_uint64 u; int j; unsigned char x[9]; double r = sqlite3_column_double(pStmt,i); memcpy(&u, &r, 8); for(j=8; j>=1; j--){ x[j] = u & 0xff; u >>= 8; } x[0] = 'F'; SHA3Update(&cx,x,9); break; } case SQLITE_TEXT: { int n2 = sqlite3_column_bytes(pStmt, i); const unsigned char *z2 = sqlite3_column_text(pStmt, i); hash_step_vformat(&cx,"T%d:",n2); SHA3Update(&cx, z2, n2); break; } case SQLITE_BLOB: { int n2 = sqlite3_column_bytes(pStmt, i); const unsigned char *z2 = sqlite3_column_blob(pStmt, i); hash_step_vformat(&cx,"B%d:",n2); SHA3Update(&cx, z2, n2); break; } } } } sqlite3_finalize(pStmt); } sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT); } #ifdef _WIN32 #endif int sqlite3_shathree_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0, sha3Func, 0, 0); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0, sha3Func, 0, 0); } if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0, sha3QueryFunc, 0, 0); } if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0, sha3QueryFunc, 0, 0); } return rc; } /************************* End ../ext/misc/shathree.c ********************/ /************************* Begin ../ext/misc/fileio.c ******************/ /* ** 2014-06-13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This SQLite extension implements SQL functions readfile() and ** writefile(), and eponymous virtual type "fsdir". ** ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]): ** ** If neither of the optional arguments is present, then this UDF ** function writes blob DATA to file FILE. If successful, the number ** of bytes written is returned. If an error occurs, NULL is returned. ** ** If the first option argument - MODE - is present, then it must ** be passed an integer value that corresponds to a POSIX mode ** value (file type + permissions, as returned in the stat.st_mode ** field by the stat() system call). Three types of files may ** be written/created: ** ** regular files: (mode & 0170000)==0100000 ** symbolic links: (mode & 0170000)==0120000 ** directories: (mode & 0170000)==0040000 ** ** For a directory, the DATA is ignored. For a symbolic link, it is ** interpreted as text and used as the target of the link. For a ** regular file, it is interpreted as a blob and written into the ** named file. Regardless of the type of file, its permissions are ** set to (mode & 0777) before returning. ** ** If the optional MTIME argument is present, then it is interpreted ** as an integer - the number of seconds since the unix epoch. The ** modification-time of the target file is set to this value before ** returning. ** ** If three or more arguments are passed to this function and an ** error is encountered, an exception is raised. ** ** READFILE(FILE): ** ** Read and return the contents of file FILE (type blob) from disk. ** ** FSDIR: ** ** Used as follows: ** ** SELECT * FROM fsdir($path [, $dir]); ** ** Parameter $path is an absolute or relative pathname. If the file that it ** refers to does not exist, it is an error. If the path refers to a regular ** file or symbolic link, it returns a single row. Or, if the path refers ** to a directory, it returns one row for the directory, and one row for each ** file within the hierarchy rooted at $path. ** ** Each row has the following columns: ** ** name: Path to file or directory (text value). ** mode: Value of stat.st_mode for directory entry (an integer). ** mtime: Value of stat.st_mtime for directory entry (an integer). ** data: For a regular file, a blob containing the file data. For a ** symlink, a text value containing the text of the link. For a ** directory, NULL. ** ** If a non-NULL value is specified for the optional $dir parameter and ** $path is a relative path, then $path is interpreted relative to $dir. ** And the paths returned in the "name" column of the table are also ** relative to directory $dir. */ SQLITE_EXTENSION_INIT1 #include <stdio.h> #include <string.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #if !defined(_WIN32) && !defined(WIN32) # include <unistd.h> # include <dirent.h> # include <utime.h> # include <sys/time.h> #else # include "windows.h" # include <io.h> # include <direct.h> /* # include "test_windirent.h" */ # define dirent DIRENT # ifndef chmod # define chmod _chmod # endif # ifndef stat # define stat _stat # endif # define mkdir(path,mode) _mkdir(path) # define lstat(path,buf) stat(path,buf) #endif #include <time.h> #include <errno.h> #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)" /* ** Set the result stored by context ctx to a blob containing the ** contents of file zName. */ static void readFileContents(sqlite3_context *ctx, const char *zName){ FILE *in; long nIn; void *pBuf; in = fopen(zName, "rb"); if( in==0 ) return; fseek(in, 0, SEEK_END); nIn = ftell(in); rewind(in); pBuf = sqlite3_malloc( nIn ); if( pBuf && 1==fread(pBuf, nIn, 1, in) ){ sqlite3_result_blob(ctx, pBuf, nIn, sqlite3_free); }else{ sqlite3_free(pBuf); } fclose(in); } /* ** Implementation of the "readfile(X)" SQL function. The entire content ** of the file named X is read and returned as a BLOB. NULL is returned ** if the file does not exist or is unreadable. */ static void readfileFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *zName; (void)(argc); /* Unused parameter */ zName = (const char*)sqlite3_value_text(argv[0]); if( zName==0 ) return; readFileContents(context, zName); } /* ** Set the error message contained in context ctx to the results of ** vprintf(zFmt, ...). */ static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ char *zMsg = 0; va_list ap; va_start(ap, zFmt); zMsg = sqlite3_vmprintf(zFmt, ap); sqlite3_result_error(ctx, zMsg, -1); sqlite3_free(zMsg); va_end(ap); } #if defined(_WIN32) /* ** This function is designed to convert a Win32 FILETIME structure into the ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC). */ static sqlite3_uint64 fileTimeToUnixTime( LPFILETIME pFileTime ){ SYSTEMTIME epochSystemTime; ULARGE_INTEGER epochIntervals; FILETIME epochFileTime; ULARGE_INTEGER fileIntervals; memset(&epochSystemTime, 0, sizeof(SYSTEMTIME)); epochSystemTime.wYear = 1970; epochSystemTime.wMonth = 1; epochSystemTime.wDay = 1; SystemTimeToFileTime(&epochSystemTime, &epochFileTime); epochIntervals.LowPart = epochFileTime.dwLowDateTime; epochIntervals.HighPart = epochFileTime.dwHighDateTime; fileIntervals.LowPart = pFileTime->dwLowDateTime; fileIntervals.HighPart = pFileTime->dwHighDateTime; return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000; } /* ** This function attempts to normalize the time values found in the stat() ** buffer to UTC. This is necessary on Win32, where the runtime library ** appears to return these values as local times. */ static void statTimesToUtc( const char *zPath, struct stat *pStatBuf ){ HANDLE hFindFile; WIN32_FIND_DATAW fd; LPWSTR zUnicodeName; extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*); zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath); if( zUnicodeName ){ memset(&fd, 0, sizeof(WIN32_FIND_DATA)); hFindFile = FindFirstFileW(zUnicodeName, &fd); if( hFindFile!=NULL ){ pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime); pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime); pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime); FindClose(hFindFile); } sqlite3_free(zUnicodeName); } } #endif /* ** This function is used in place of stat(). On Windows, special handling ** is required in order for the included time to be returned as UTC. On all ** other systems, this function simply calls stat(). */ static int fileStat( const char *zPath, struct stat *pStatBuf ){ #if defined(_WIN32) int rc = stat(zPath, pStatBuf); if( rc==0 ) statTimesToUtc(zPath, pStatBuf); return rc; #else return stat(zPath, pStatBuf); #endif } /* ** This function is used in place of lstat(). On Windows, special handling ** is required in order for the included time to be returned as UTC. On all ** other systems, this function simply calls lstat(). */ static int fileLinkStat( const char *zPath, struct stat *pStatBuf ){ #if defined(_WIN32) int rc = lstat(zPath, pStatBuf); if( rc==0 ) statTimesToUtc(zPath, pStatBuf); return rc; #else return lstat(zPath, pStatBuf); #endif } /* ** Argument zFile is the name of a file that will be created and/or written ** by SQL function writefile(). This function ensures that the directory ** zFile will be written to exists, creating it if required. The permissions ** for any path components created by this function are set to (mode&0777). ** ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise, ** SQLITE_OK is returned if the directory is successfully created, or ** SQLITE_ERROR otherwise. */ static int makeDirectory( const char *zFile, mode_t mode ){ char *zCopy = sqlite3_mprintf("%s", zFile); int rc = SQLITE_OK; if( zCopy==0 ){ rc = SQLITE_NOMEM; }else{ int nCopy = (int)strlen(zCopy); int i = 1; while( rc==SQLITE_OK ){ struct stat sStat; int rc2; for(; zCopy[i]!='/' && i<nCopy; i++); if( i==nCopy ) break; zCopy[i] = '\0'; rc2 = fileStat(zCopy, &sStat); if( rc2!=0 ){ if( mkdir(zCopy, mode & 0777) ) rc = SQLITE_ERROR; }else{ if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR; } zCopy[i] = '/'; i++; } sqlite3_free(zCopy); } return rc; } /* ** This function does the work for the writefile() UDF. Refer to ** header comments at the top of this file for details. */ static int writeFile( sqlite3_context *pCtx, /* Context to return bytes written in */ const char *zFile, /* File to write */ sqlite3_value *pData, /* Data to write */ mode_t mode, /* MODE parameter passed to writefile() */ sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */ ){ #if !defined(_WIN32) && !defined(WIN32) if( S_ISLNK(mode) ){ const char *zTo = (const char*)sqlite3_value_text(pData); if( symlink(zTo, zFile)<0 ) return 1; }else #endif { if( S_ISDIR(mode) ){ if( mkdir(zFile, mode) ){ /* The mkdir() call to create the directory failed. This might not ** be an error though - if there is already a directory at the same ** path and either the permissions already match or can be changed ** to do so using chmod(), it is not an error. */ struct stat sStat; if( errno!=EEXIST || 0!=fileStat(zFile, &sStat) || !S_ISDIR(sStat.st_mode) || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777)) ){ return 1; } } }else{ sqlite3_int64 nWrite = 0; const char *z; int rc = 0; FILE *out = fopen(zFile, "wb"); if( out==0 ) return 1; z = (const char*)sqlite3_value_blob(pData); if( z ){ sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out); nWrite = sqlite3_value_bytes(pData); if( nWrite!=n ){ rc = 1; } } fclose(out); if( rc==0 && mode && chmod(zFile, mode & 0777) ){ rc = 1; } if( rc ) return 2; sqlite3_result_int64(pCtx, nWrite); } } if( mtime>=0 ){ #if defined(_WIN32) /* Windows */ FILETIME lastAccess; FILETIME lastWrite; SYSTEMTIME currentTime; LONGLONG intervals; HANDLE hFile; LPWSTR zUnicodeName; extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*); GetSystemTime(&currentTime); SystemTimeToFileTime(&currentTime, &lastAccess); intervals = Int32x32To64(mtime, 10000000) + 116444736000000000; lastWrite.dwLowDateTime = (DWORD)intervals; lastWrite.dwHighDateTime = intervals >> 32; zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile); if( zUnicodeName==0 ){ return 1; } hFile = CreateFileW( zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL ); sqlite3_free(zUnicodeName); if( hFile!=INVALID_HANDLE_VALUE ){ BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite); CloseHandle(hFile); return !bResult; }else{ return 1; } #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */ /* Recent unix */ struct timespec times[2]; times[0].tv_nsec = times[1].tv_nsec = 0; times[0].tv_sec = time(0); times[1].tv_sec = mtime; if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){ return 1; } #else /* Legacy unix */ struct timeval times[2]; times[0].tv_usec = times[1].tv_usec = 0; times[0].tv_sec = time(0); times[1].tv_sec = mtime; if( utimes(zFile, times) ){ return 1; } #endif } return 0; } /* ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function. ** Refer to header comments at the top of this file for details. */ static void writefileFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *zFile; mode_t mode = 0; int res; sqlite3_int64 mtime = -1; if( argc<2 || argc>4 ){ sqlite3_result_error(context, "wrong number of arguments to function writefile()", -1 ); return; } zFile = (const char*)sqlite3_value_text(argv[0]); if( zFile==0 ) return; if( argc>=3 ){ mode = (mode_t)sqlite3_value_int(argv[2]); } if( argc==4 ){ mtime = sqlite3_value_int64(argv[3]); } res = writeFile(context, zFile, argv[1], mode, mtime); if( res==1 && errno==ENOENT ){ if( makeDirectory(zFile, mode)==SQLITE_OK ){ res = writeFile(context, zFile, argv[1], mode, mtime); } } if( argc>2 && res!=0 ){ if( S_ISLNK(mode) ){ ctxErrorMsg(context, "failed to create symlink: %s", zFile); }else if( S_ISDIR(mode) ){ ctxErrorMsg(context, "failed to create directory: %s", zFile); }else{ ctxErrorMsg(context, "failed to write file: %s", zFile); } } } /* ** SQL function: lsmode(MODE) ** ** Given a numberic st_mode from stat(), convert it into a human-readable ** text string in the style of "ls -l". */ static void lsModeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int i; int iMode = sqlite3_value_int(argv[0]); char z[16]; (void)argc; if( S_ISLNK(iMode) ){ z[0] = 'l'; }else if( S_ISREG(iMode) ){ z[0] = '-'; }else if( S_ISDIR(iMode) ){ z[0] = 'd'; }else{ z[0] = '?'; } for(i=0; i<3; i++){ int m = (iMode >> ((2-i)*3)); char *a = &z[1 + i*3]; a[0] = (m & 0x4) ? 'r' : '-'; a[1] = (m & 0x2) ? 'w' : '-'; a[2] = (m & 0x1) ? 'x' : '-'; } z[10] = '\0'; sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT); } #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Cursor type for recursively iterating through a directory structure. */ typedef struct fsdir_cursor fsdir_cursor; typedef struct FsdirLevel FsdirLevel; struct FsdirLevel { DIR *pDir; /* From opendir() */ char *zDir; /* Name of directory (nul-terminated) */ }; struct fsdir_cursor { sqlite3_vtab_cursor base; /* Base class - must be first */ int nLvl; /* Number of entries in aLvl[] array */ int iLvl; /* Index of current entry */ FsdirLevel *aLvl; /* Hierarchy of directories being traversed */ const char *zBase; int nBase; struct stat sStat; /* Current lstat() results */ char *zPath; /* Path to current entry */ sqlite3_int64 iRowid; /* Current rowid */ }; typedef struct fsdir_tab fsdir_tab; struct fsdir_tab { sqlite3_vtab base; /* Base class - must be first */ }; /* ** Construct a new fsdir virtual table object. */ static int fsdirConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ fsdir_tab *pNew = 0; int rc; (void)pAux; (void)argc; (void)argv; (void)pzErr; rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA); if( rc==SQLITE_OK ){ pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) ); if( pNew==0 ) return SQLITE_NOMEM; memset(pNew, 0, sizeof(*pNew)); } *ppVtab = (sqlite3_vtab*)pNew; return rc; } /* ** This method is the destructor for fsdir vtab objects. */ static int fsdirDisconnect(sqlite3_vtab *pVtab){ sqlite3_free(pVtab); return SQLITE_OK; } /* ** Constructor for a new fsdir_cursor object. */ static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ fsdir_cursor *pCur; (void)p; pCur = sqlite3_malloc( sizeof(*pCur) ); if( pCur==0 ) return SQLITE_NOMEM; memset(pCur, 0, sizeof(*pCur)); pCur->iLvl = -1; *ppCursor = &pCur->base; return SQLITE_OK; } /* ** Reset a cursor back to the state it was in when first returned ** by fsdirOpen(). */ static void fsdirResetCursor(fsdir_cursor *pCur){ int i; for(i=0; i<=pCur->iLvl; i++){ FsdirLevel *pLvl = &pCur->aLvl[i]; if( pLvl->pDir ) closedir(pLvl->pDir); sqlite3_free(pLvl->zDir); } sqlite3_free(pCur->zPath); sqlite3_free(pCur->aLvl); pCur->aLvl = 0; pCur->zPath = 0; pCur->zBase = 0; pCur->nBase = 0; pCur->nLvl = 0; pCur->iLvl = -1; pCur->iRowid = 1; } /* ** Destructor for an fsdir_cursor. */ static int fsdirClose(sqlite3_vtab_cursor *cur){ fsdir_cursor *pCur = (fsdir_cursor*)cur; fsdirResetCursor(pCur); sqlite3_free(pCur); return SQLITE_OK; } /* ** Set the error message for the virtual table associated with cursor ** pCur to the results of vprintf(zFmt, ...). */ static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); va_end(ap); } /* ** Advance an fsdir_cursor to its next row of output. */ static int fsdirNext(sqlite3_vtab_cursor *cur){ fsdir_cursor *pCur = (fsdir_cursor*)cur; mode_t m = pCur->sStat.st_mode; pCur->iRowid++; if( S_ISDIR(m) ){ /* Descend into this directory */ int iNew = pCur->iLvl + 1; FsdirLevel *pLvl; if( iNew>=pCur->nLvl ){ int nNew = iNew+1; int nByte = nNew*sizeof(FsdirLevel); FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc(pCur->aLvl, nByte); if( aNew==0 ) return SQLITE_NOMEM; memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl)); pCur->aLvl = aNew; pCur->nLvl = nNew; } pCur->iLvl = iNew; pLvl = &pCur->aLvl[iNew]; pLvl->zDir = pCur->zPath; pCur->zPath = 0; pLvl->pDir = opendir(pLvl->zDir); if( pLvl->pDir==0 ){ fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath); return SQLITE_ERROR; } } while( pCur->iLvl>=0 ){ FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl]; struct dirent *pEntry = readdir(pLvl->pDir); if( pEntry ){ if( pEntry->d_name[0]=='.' ){ if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue; if( pEntry->d_name[1]=='\0' ) continue; } sqlite3_free(pCur->zPath); pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name); if( pCur->zPath==0 ) return SQLITE_NOMEM; if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); return SQLITE_ERROR; } return SQLITE_OK; } closedir(pLvl->pDir); sqlite3_free(pLvl->zDir); pLvl->pDir = 0; pLvl->zDir = 0; pCur->iLvl--; } /* EOF */ sqlite3_free(pCur->zPath); pCur->zPath = 0; return SQLITE_OK; } /* ** Return values of columns for the row at which the series_cursor ** is currently pointing. */ static int fsdirColumn( sqlite3_vtab_cursor *cur, /* The cursor */ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ int i /* Which column to return */ ){ fsdir_cursor *pCur = (fsdir_cursor*)cur; switch( i ){ case 0: { /* name */ sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT); break; } case 1: /* mode */ sqlite3_result_int64(ctx, pCur->sStat.st_mode); break; case 2: /* mtime */ sqlite3_result_int64(ctx, pCur->sStat.st_mtime); break; case 3: { /* data */ mode_t m = pCur->sStat.st_mode; if( S_ISDIR(m) ){ sqlite3_result_null(ctx); #if !defined(_WIN32) && !defined(WIN32) }else if( S_ISLNK(m) ){ char aStatic[64]; char *aBuf = aStatic; int nBuf = 64; int n; while( 1 ){ n = readlink(pCur->zPath, aBuf, nBuf); if( n<nBuf ) break; if( aBuf!=aStatic ) sqlite3_free(aBuf); nBuf = nBuf*2; aBuf = sqlite3_malloc(nBuf); if( aBuf==0 ){ sqlite3_result_error_nomem(ctx); return SQLITE_NOMEM; } } sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT); if( aBuf!=aStatic ) sqlite3_free(aBuf); #endif }else{ readFileContents(ctx, pCur->zPath); } } } return SQLITE_OK; } /* ** Return the rowid for the current row. In this implementation, the ** first row returned is assigned rowid value 1, and each subsequent ** row a value 1 more than that of the previous. */ static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ fsdir_cursor *pCur = (fsdir_cursor*)cur; *pRowid = pCur->iRowid; return SQLITE_OK; } /* ** Return TRUE if the cursor has been moved off of the last ** row of output. */ static int fsdirEof(sqlite3_vtab_cursor *cur){ fsdir_cursor *pCur = (fsdir_cursor*)cur; return (pCur->zPath==0); } /* ** xFilter callback. */ static int fsdirFilter( sqlite3_vtab_cursor *cur, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ const char *zDir = 0; fsdir_cursor *pCur = (fsdir_cursor*)cur; (void)idxStr; fsdirResetCursor(pCur); if( idxNum==0 ){ fsdirSetErrmsg(pCur, "table function fsdir requires an argument"); return SQLITE_ERROR; } assert( argc==idxNum && (argc==1 || argc==2) ); zDir = (const char*)sqlite3_value_text(argv[0]); if( zDir==0 ){ fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument"); return SQLITE_ERROR; } if( argc==2 ){ pCur->zBase = (const char*)sqlite3_value_text(argv[1]); } if( pCur->zBase ){ pCur->nBase = (int)strlen(pCur->zBase)+1; pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir); }else{ pCur->zPath = sqlite3_mprintf("%s", zDir); } if( pCur->zPath==0 ){ return SQLITE_NOMEM; } if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); return SQLITE_ERROR; } return SQLITE_OK; } /* ** SQLite will invoke this method one or more times while planning a query ** that uses the generate_series virtual table. This routine needs to create ** a query plan for each invocation and compute an estimated cost for that ** plan. ** ** In this implementation idxNum is used to represent the ** query plan. idxStr is unused. ** ** The query plan is represented by bits in idxNum: ** ** (1) start = $value -- constraint exists ** (2) stop = $value -- constraint exists ** (4) step = $value -- constraint exists ** (8) output in descending order */ static int fsdirBestIndex( sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo ){ int i; /* Loop over constraints */ int idx4 = -1; int idx5 = -1; const struct sqlite3_index_constraint *pConstraint; (void)tab; pConstraint = pIdxInfo->aConstraint; for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ if( pConstraint->usable==0 ) continue; if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; if( pConstraint->iColumn==4 ) idx4 = i; if( pConstraint->iColumn==5 ) idx5 = i; } if( idx4<0 ){ pIdxInfo->idxNum = 0; pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50); }else{ pIdxInfo->aConstraintUsage[idx4].omit = 1; pIdxInfo->aConstraintUsage[idx4].argvIndex = 1; if( idx5>=0 ){ pIdxInfo->aConstraintUsage[idx5].omit = 1; pIdxInfo->aConstraintUsage[idx5].argvIndex = 2; pIdxInfo->idxNum = 2; pIdxInfo->estimatedCost = 10.0; }else{ pIdxInfo->idxNum = 1; pIdxInfo->estimatedCost = 100.0; } } return SQLITE_OK; } /* ** Register the "fsdir" virtual table. */ static int fsdirRegister(sqlite3 *db){ static sqlite3_module fsdirModule = { 0, /* iVersion */ 0, /* xCreate */ fsdirConnect, /* xConnect */ fsdirBestIndex, /* xBestIndex */ fsdirDisconnect, /* xDisconnect */ 0, /* xDestroy */ fsdirOpen, /* xOpen - open a cursor */ fsdirClose, /* xClose - close a cursor */ fsdirFilter, /* xFilter - configure scan constraints */ fsdirNext, /* xNext - advance a cursor */ fsdirEof, /* xEof - check for end of scan */ fsdirColumn, /* xColumn - read data */ fsdirRowid, /* xRowid - read data */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindMethod */ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0); return rc; } #else /* SQLITE_OMIT_VIRTUALTABLE */ # define fsdirRegister(x) SQLITE_OK #endif #ifdef _WIN32 #endif int sqlite3_fileio_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0, readfileFunc, 0, 0); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "writefile", -1, SQLITE_UTF8, 0, writefileFunc, 0, 0); } if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0, lsModeFunc, 0, 0); } if( rc==SQLITE_OK ){ rc = fsdirRegister(db); } return rc; } /************************* End ../ext/misc/fileio.c ********************/ /************************* Begin ../ext/misc/completion.c ******************/ /* ** 2017-07-10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements an eponymous virtual table that returns suggested ** completions for a partial SQL input. ** ** Suggested usage: ** ** SELECT DISTINCT candidate COLLATE nocase ** FROM completion($prefix,$wholeline) ** ORDER BY 1; ** ** The two query parameters are optional. $prefix is the text of the ** current word being typed and that is to be completed. $wholeline is ** the complete input line, used for context. ** ** The raw completion() table might return the same candidate multiple ** times, for example if the same column name is used to two or more ** tables. And the candidates are returned in an arbitrary order. Hence, ** the DISTINCT and ORDER BY are recommended. ** ** This virtual table operates at the speed of human typing, and so there ** is no attempt to make it fast. Even a slow implementation will be much ** faster than any human can type. ** */ SQLITE_EXTENSION_INIT1 #include <assert.h> #include <string.h> #include <ctype.h> #ifndef SQLITE_OMIT_VIRTUALTABLE /* completion_vtab is a subclass of sqlite3_vtab which will ** serve as the underlying representation of a completion virtual table */ typedef struct completion_vtab completion_vtab; struct completion_vtab { sqlite3_vtab base; /* Base class - must be first */ sqlite3 *db; /* Database connection for this completion vtab */ }; /* completion_cursor is a subclass of sqlite3_vtab_cursor which will ** serve as the underlying representation of a cursor that scans ** over rows of the result */ typedef struct completion_cursor completion_cursor; struct completion_cursor { sqlite3_vtab_cursor base; /* Base class - must be first */ sqlite3 *db; /* Database connection for this cursor */ int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */ char *zPrefix; /* The prefix for the word we want to complete */ char *zLine; /* The whole that we want to complete */ const char *zCurrentRow; /* Current output row */ sqlite3_stmt *pStmt; /* Current statement */ sqlite3_int64 iRowid; /* The rowid */ int ePhase; /* Current phase */ int j; /* inter-phase counter */ }; /* Values for ePhase: */ #define COMPLETION_FIRST_PHASE 1 #define COMPLETION_KEYWORDS 1 #define COMPLETION_PRAGMAS 2 #define COMPLETION_FUNCTIONS 3 #define COMPLETION_COLLATIONS 4 #define COMPLETION_INDEXES 5 #define COMPLETION_TRIGGERS 6 #define COMPLETION_DATABASES 7 #define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */ #define COMPLETION_COLUMNS 9 #define COMPLETION_MODULES 10 #define COMPLETION_EOF 11 /* ** The completionConnect() method is invoked to create a new ** completion_vtab that describes the completion virtual table. ** ** Think of this routine as the constructor for completion_vtab objects. ** ** All this routine needs to do is: ** ** (1) Allocate the completion_vtab object and initialize all fields. ** ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the ** result set of queries against completion will look like. */ static int completionConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ completion_vtab *pNew; int rc; (void)(pAux); /* Unused parameter */ (void)(argc); /* Unused parameter */ (void)(argv); /* Unused parameter */ (void)(pzErr); /* Unused parameter */ /* Column numbers */ #define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */ #define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */ #define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */ #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */ rc = sqlite3_declare_vtab(db, "CREATE TABLE x(" " candidate TEXT," " prefix TEXT HIDDEN," " wholeline TEXT HIDDEN," " phase INT HIDDEN" /* Used for debugging only */ ")"); if( rc==SQLITE_OK ){ pNew = sqlite3_malloc( sizeof(*pNew) ); *ppVtab = (sqlite3_vtab*)pNew; if( pNew==0 ) return SQLITE_NOMEM; memset(pNew, 0, sizeof(*pNew)); pNew->db = db; } return rc; } /* ** This method is the destructor for completion_cursor objects. */ static int completionDisconnect(sqlite3_vtab *pVtab){ sqlite3_free(pVtab); return SQLITE_OK; } /* ** Constructor for a new completion_cursor object. */ static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ completion_cursor *pCur; pCur = sqlite3_malloc( sizeof(*pCur) ); if( pCur==0 ) return SQLITE_NOMEM; memset(pCur, 0, sizeof(*pCur)); pCur->db = ((completion_vtab*)p)->db; *ppCursor = &pCur->base; return SQLITE_OK; } /* ** Reset the completion_cursor. */ static void completionCursorReset(completion_cursor *pCur){ sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0; sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0; sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0; pCur->j = 0; } /* ** Destructor for a completion_cursor. */ static int completionClose(sqlite3_vtab_cursor *cur){ completionCursorReset((completion_cursor*)cur); sqlite3_free(cur); return SQLITE_OK; } /* ** All SQL keywords understood by SQLite */ static const char *completionKwrds[] = { "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY", "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT", "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH", "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN", "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF", "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER", "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY", "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL", "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA", "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP", "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT", "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP", "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE", "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE", "WITH", "WITHOUT", }; #define completionKwCount \ (int)(sizeof(completionKwrds)/sizeof(completionKwrds[0])) /* ** Advance a completion_cursor to its next row of output. ** ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object ** record the current state of the scan. This routine sets ->zCurrentRow ** to the current row of output and then returns. If no more rows remain, ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual ** table that has reached the end of its scan. ** ** The current implementation just lists potential identifiers and ** keywords and filters them by zPrefix. Future enhancements should ** take zLine into account to try to restrict the set of identifiers and ** keywords based on what would be legal at the current point of input. */ static int completionNext(sqlite3_vtab_cursor *cur){ completion_cursor *pCur = (completion_cursor*)cur; int eNextPhase = 0; /* Next phase to try if current phase reaches end */ int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */ pCur->iRowid++; while( pCur->ePhase!=COMPLETION_EOF ){ switch( pCur->ePhase ){ case COMPLETION_KEYWORDS: { if( pCur->j >= completionKwCount ){ pCur->zCurrentRow = 0; pCur->ePhase = COMPLETION_DATABASES; }else{ pCur->zCurrentRow = completionKwrds[pCur->j++]; } iCol = -1; break; } case COMPLETION_DATABASES: { if( pCur->pStmt==0 ){ sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pCur->pStmt, 0); } iCol = 1; eNextPhase = COMPLETION_TABLES; break; } case COMPLETION_TABLES: { if( pCur->pStmt==0 ){ sqlite3_stmt *pS2; char *zSql = 0; const char *zSep = ""; sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); while( sqlite3_step(pS2)==SQLITE_ROW ){ const char *zDb = (const char*)sqlite3_column_text(pS2, 1); zSql = sqlite3_mprintf( "%z%s" "SELECT name FROM \"%w\".sqlite_master", zSql, zSep, zDb ); if( zSql==0 ) return SQLITE_NOMEM; zSep = " UNION "; } sqlite3_finalize(pS2); sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); sqlite3_free(zSql); } iCol = 0; eNextPhase = COMPLETION_COLUMNS; break; } case COMPLETION_COLUMNS: { if( pCur->pStmt==0 ){ sqlite3_stmt *pS2; char *zSql = 0; const char *zSep = ""; sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); while( sqlite3_step(pS2)==SQLITE_ROW ){ const char *zDb = (const char*)sqlite3_column_text(pS2, 1); zSql = sqlite3_mprintf( "%z%s" "SELECT pti.name FROM \"%w\".sqlite_master AS sm" " JOIN pragma_table_info(sm.name,%Q) AS pti" " WHERE sm.type='table'", zSql, zSep, zDb, zDb ); if( zSql==0 ) return SQLITE_NOMEM; zSep = " UNION "; } sqlite3_finalize(pS2); sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); sqlite3_free(zSql); } iCol = 0; eNextPhase = COMPLETION_EOF; break; } } if( iCol<0 ){ /* This case is when the phase presets zCurrentRow */ if( pCur->zCurrentRow==0 ) continue; }else{ if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){ /* Extract the next row of content */ pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol); }else{ /* When all rows are finished, advance to the next phase */ sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0; pCur->ePhase = eNextPhase; continue; } } if( pCur->nPrefix==0 ) break; if( sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 ){ break; } } return SQLITE_OK; } /* ** Return values of columns for the row at which the completion_cursor ** is currently pointing. */ static int completionColumn( sqlite3_vtab_cursor *cur, /* The cursor */ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ int i /* Which column to return */ ){ completion_cursor *pCur = (completion_cursor*)cur; switch( i ){ case COMPLETION_COLUMN_CANDIDATE: { sqlite3_result_text(ctx, pCur->zCurrentRow, -1, SQLITE_TRANSIENT); break; } case COMPLETION_COLUMN_PREFIX: { sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT); break; } case COMPLETION_COLUMN_WHOLELINE: { sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT); break; } case COMPLETION_COLUMN_PHASE: { sqlite3_result_int(ctx, pCur->ePhase); break; } } return SQLITE_OK; } /* ** Return the rowid for the current row. In this implementation, the ** rowid is the same as the output value. */ static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ completion_cursor *pCur = (completion_cursor*)cur; *pRowid = pCur->iRowid; return SQLITE_OK; } /* ** Return TRUE if the cursor has been moved off of the last ** row of output. */ static int completionEof(sqlite3_vtab_cursor *cur){ completion_cursor *pCur = (completion_cursor*)cur; return pCur->ePhase >= COMPLETION_EOF; } /* ** This method is called to "rewind" the completion_cursor object back ** to the first row of output. This method is always called at least ** once prior to any call to completionColumn() or completionRowid() or ** completionEof(). */ static int completionFilter( sqlite3_vtab_cursor *pVtabCursor, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ completion_cursor *pCur = (completion_cursor *)pVtabCursor; int iArg = 0; (void)(idxStr); /* Unused parameter */ (void)(argc); /* Unused parameter */ completionCursorReset(pCur); if( idxNum & 1 ){ pCur->nPrefix = sqlite3_value_bytes(argv[iArg]); if( pCur->nPrefix>0 ){ pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); if( pCur->zPrefix==0 ) return SQLITE_NOMEM; } iArg++; } if( idxNum & 2 ){ pCur->nLine = sqlite3_value_bytes(argv[iArg]); if( pCur->nLine>0 ){ pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); if( pCur->zLine==0 ) return SQLITE_NOMEM; } iArg++; } if( pCur->zLine!=0 && pCur->zPrefix==0 ){ int i = pCur->nLine; while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){ i--; } pCur->nPrefix = pCur->nLine - i; if( pCur->nPrefix>0 ){ pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i); if( pCur->zPrefix==0 ) return SQLITE_NOMEM; } } pCur->iRowid = 0; pCur->ePhase = COMPLETION_FIRST_PHASE; return completionNext(pVtabCursor); } /* ** SQLite will invoke this method one or more times while planning a query ** that uses the completion virtual table. This routine needs to create ** a query plan for each invocation and compute an estimated cost for that ** plan. ** ** There are two hidden parameters that act as arguments to the table-valued ** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix" ** is available and bit 1 is set if "wholeline" is available. */ static int completionBestIndex( sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo ){ int i; /* Loop over constraints */ int idxNum = 0; /* The query plan bitmask */ int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */ int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */ int nArg = 0; /* Number of arguments that completeFilter() expects */ const struct sqlite3_index_constraint *pConstraint; (void)(tab); /* Unused parameter */ pConstraint = pIdxInfo->aConstraint; for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ if( pConstraint->usable==0 ) continue; if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; switch( pConstraint->iColumn ){ case COMPLETION_COLUMN_PREFIX: prefixIdx = i; idxNum |= 1; break; case COMPLETION_COLUMN_WHOLELINE: wholelineIdx = i; idxNum |= 2; break; } } if( prefixIdx>=0 ){ pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg; pIdxInfo->aConstraintUsage[prefixIdx].omit = 1; } if( wholelineIdx>=0 ){ pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg; pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1; } pIdxInfo->idxNum = idxNum; pIdxInfo->estimatedCost = (double)5000 - 1000*nArg; pIdxInfo->estimatedRows = 500 - 100*nArg; return SQLITE_OK; } /* ** This following structure defines all the methods for the ** completion virtual table. */ static sqlite3_module completionModule = { 0, /* iVersion */ 0, /* xCreate */ completionConnect, /* xConnect */ completionBestIndex, /* xBestIndex */ completionDisconnect, /* xDisconnect */ 0, /* xDestroy */ completionOpen, /* xOpen - open a cursor */ completionClose, /* xClose - close a cursor */ completionFilter, /* xFilter - configure scan constraints */ completionNext, /* xNext - advance a cursor */ completionEof, /* xEof - check for end of scan */ completionColumn, /* xColumn - read data */ completionRowid, /* xRowid - read data */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindMethod */ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; #endif /* SQLITE_OMIT_VIRTUALTABLE */ int sqlite3CompletionVtabInit(sqlite3 *db){ int rc = SQLITE_OK; #ifndef SQLITE_OMIT_VIRTUALTABLE rc = sqlite3_create_module(db, "completion", &completionModule, 0); #endif return rc; } #ifdef _WIN32 #endif int sqlite3_completion_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); (void)(pzErrMsg); /* Unused parameter */ #ifndef SQLITE_OMIT_VIRTUALTABLE rc = sqlite3CompletionVtabInit(db); #endif return rc; } /************************* End ../ext/misc/completion.c ********************/ /************************* Begin ../ext/misc/appendvfs.c ******************/ /* ** 2017-10-20 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file implements a VFS shim that allows an SQLite database to be ** appended onto the end of some other file, such as an executable. ** ** A special record must appear at the end of the file that identifies the ** file as an appended database and provides an offset to page 1. For ** best performance page 1 should be located at a disk page boundary, though ** that is not required. ** ** When opening a database using this VFS, the connection might treat ** the file as an ordinary SQLite database, or it might treat is as a ** database appended onto some other file. Here are the rules: ** ** (1) When opening a new empty file, that file is treated as an ordinary ** database. ** ** (2) When opening a file that begins with the standard SQLite prefix ** string "SQLite format 3", that file is treated as an ordinary ** database. ** ** (3) When opening a file that ends with the appendvfs trailer string ** "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended ** database. ** ** (4) If none of the above apply and the SQLITE_OPEN_CREATE flag is ** set, then a new database is appended to the already existing file. ** ** (5) Otherwise, SQLITE_CANTOPEN is returned. ** ** To avoid unnecessary complications with the PENDING_BYTE, the size of ** the file containing the database is limited to 1GB. This VFS will refuse ** to read or write past the 1GB mark. This restriction might be lifted in ** future versions. For now, if you need a large database, then keep the ** database in a separate file. ** ** If the file being opened is not an appended database, then this shim is ** a pass-through into the default underlying VFS. **/ SQLITE_EXTENSION_INIT1 #include <string.h> #include <assert.h> /* The append mark at the end of the database is: ** ** Start-Of-SQLite3-NNNNNNNN ** 123456789 123456789 12345 ** ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is ** the offset to page 1. */ #define APND_MARK_PREFIX "Start-Of-SQLite3-" #define APND_MARK_PREFIX_SZ 17 #define APND_MARK_SIZE 25 /* ** Maximum size of the combined prefix + database + append-mark. This ** must be less than 0x40000000 to avoid locking issues on Windows. */ #define APND_MAX_SIZE (65536*15259) /* ** Forward declaration of objects used by this utility */ typedef struct sqlite3_vfs ApndVfs; typedef struct ApndFile ApndFile; /* Access to a lower-level VFS that (might) implement dynamic loading, ** access to randomness, etc. */ #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData)) #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1)) /* An open file */ struct ApndFile { sqlite3_file base; /* IO methods */ sqlite3_int64 iPgOne; /* File offset to page 1 */ sqlite3_int64 iMark; /* Start of the append-mark */ }; /* ** Methods for ApndFile */ static int apndClose(sqlite3_file*); static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); static int apndTruncate(sqlite3_file*, sqlite3_int64 size); static int apndSync(sqlite3_file*, int flags); static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize); static int apndLock(sqlite3_file*, int); static int apndUnlock(sqlite3_file*, int); static int apndCheckReservedLock(sqlite3_file*, int *pResOut); static int apndFileControl(sqlite3_file*, int op, void *pArg); static int apndSectorSize(sqlite3_file*); static int apndDeviceCharacteristics(sqlite3_file*); static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**); static int apndShmLock(sqlite3_file*, int offset, int n, int flags); static void apndShmBarrier(sqlite3_file*); static int apndShmUnmap(sqlite3_file*, int deleteFlag); static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p); /* ** Methods for ApndVfs */ static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir); static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *); static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); static void *apndDlOpen(sqlite3_vfs*, const char *zFilename); static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg); static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void); static void apndDlClose(sqlite3_vfs*, void*); static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut); static int apndSleep(sqlite3_vfs*, int microseconds); static int apndCurrentTime(sqlite3_vfs*, double*); static int apndGetLastError(sqlite3_vfs*, int, char *); static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr); static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z); static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName); static sqlite3_vfs apnd_vfs = { 3, /* iVersion (set when registered) */ 0, /* szOsFile (set when registered) */ 1024, /* mxPathname */ 0, /* pNext */ "apndvfs", /* zName */ 0, /* pAppData (set when registered) */ apndOpen, /* xOpen */ apndDelete, /* xDelete */ apndAccess, /* xAccess */ apndFullPathname, /* xFullPathname */ apndDlOpen, /* xDlOpen */ apndDlError, /* xDlError */ apndDlSym, /* xDlSym */ apndDlClose, /* xDlClose */ apndRandomness, /* xRandomness */ apndSleep, /* xSleep */ apndCurrentTime, /* xCurrentTime */ apndGetLastError, /* xGetLastError */ apndCurrentTimeInt64, /* xCurrentTimeInt64 */ apndSetSystemCall, /* xSetSystemCall */ apndGetSystemCall, /* xGetSystemCall */ apndNextSystemCall /* xNextSystemCall */ }; static const sqlite3_io_methods apnd_io_methods = { 3, /* iVersion */ apndClose, /* xClose */ apndRead, /* xRead */ apndWrite, /* xWrite */ apndTruncate, /* xTruncate */ apndSync, /* xSync */ apndFileSize, /* xFileSize */ apndLock, /* xLock */ apndUnlock, /* xUnlock */ apndCheckReservedLock, /* xCheckReservedLock */ apndFileControl, /* xFileControl */ apndSectorSize, /* xSectorSize */ apndDeviceCharacteristics, /* xDeviceCharacteristics */ apndShmMap, /* xShmMap */ apndShmLock, /* xShmLock */ apndShmBarrier, /* xShmBarrier */ apndShmUnmap, /* xShmUnmap */ apndFetch, /* xFetch */ apndUnfetch /* xUnfetch */ }; /* ** Close an apnd-file. */ static int apndClose(sqlite3_file *pFile){ pFile = ORIGFILE(pFile); return pFile->pMethods->xClose(pFile); } /* ** Read data from an apnd-file. */ static int apndRead( sqlite3_file *pFile, void *zBuf, int iAmt, sqlite_int64 iOfst ){ ApndFile *p = (ApndFile *)pFile; pFile = ORIGFILE(pFile); return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne); } /* ** Add the append-mark onto the end of the file. */ static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){ int i; unsigned char a[APND_MARK_SIZE]; memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ); for(i=0; i<8; i++){ a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff; } return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark); } /* ** Write data to an apnd-file. */ static int apndWrite( sqlite3_file *pFile, const void *zBuf, int iAmt, sqlite_int64 iOfst ){ int rc; ApndFile *p = (ApndFile *)pFile; pFile = ORIGFILE(pFile); if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL; rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne); if( rc==SQLITE_OK && iOfst + iAmt + p->iPgOne > p->iMark ){ sqlite3_int64 sz = 0; rc = pFile->pMethods->xFileSize(pFile, &sz); if( rc==SQLITE_OK ){ p->iMark = sz - APND_MARK_SIZE; if( iOfst + iAmt + p->iPgOne > p->iMark ){ p->iMark = p->iPgOne + iOfst + iAmt; rc = apndWriteMark(p, pFile); } } } return rc; } /* ** Truncate an apnd-file. */ static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){ int rc; ApndFile *p = (ApndFile *)pFile; pFile = ORIGFILE(pFile); rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE); if( rc==SQLITE_OK ){ p->iMark = p->iPgOne+size; rc = apndWriteMark(p, pFile); } return rc; } /* ** Sync an apnd-file. */ static int apndSync(sqlite3_file *pFile, int flags){ pFile = ORIGFILE(pFile); return pFile->pMethods->xSync(pFile, flags); } /* ** Return the current file-size of an apnd-file. */ static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ ApndFile *p = (ApndFile *)pFile; int rc; pFile = ORIGFILE(p); rc = pFile->pMethods->xFileSize(pFile, pSize); if( rc==SQLITE_OK && p->iPgOne ){ *pSize -= p->iPgOne + APND_MARK_SIZE; } return rc; } /* ** Lock an apnd-file. */ static int apndLock(sqlite3_file *pFile, int eLock){ pFile = ORIGFILE(pFile); return pFile->pMethods->xLock(pFile, eLock); } /* ** Unlock an apnd-file. */ static int apndUnlock(sqlite3_file *pFile, int eLock){ pFile = ORIGFILE(pFile); return pFile->pMethods->xUnlock(pFile, eLock); } /* ** Check if another file-handle holds a RESERVED lock on an apnd-file. */ static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){ pFile = ORIGFILE(pFile); return pFile->pMethods->xCheckReservedLock(pFile, pResOut); } /* ** File control method. For custom operations on an apnd-file. */ static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){ ApndFile *p = (ApndFile *)pFile; int rc; pFile = ORIGFILE(pFile); rc = pFile->pMethods->xFileControl(pFile, op, pArg); if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){ *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg); } return rc; } /* ** Return the sector-size in bytes for an apnd-file. */ static int apndSectorSize(sqlite3_file *pFile){ pFile = ORIGFILE(pFile); return pFile->pMethods->xSectorSize(pFile); } /* ** Return the device characteristic flags supported by an apnd-file. */ static int apndDeviceCharacteristics(sqlite3_file *pFile){ pFile = ORIGFILE(pFile); return pFile->pMethods->xDeviceCharacteristics(pFile); } /* Create a shared memory file mapping */ static int apndShmMap( sqlite3_file *pFile, int iPg, int pgsz, int bExtend, void volatile **pp ){ pFile = ORIGFILE(pFile); return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp); } /* Perform locking on a shared-memory segment */ static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){ pFile = ORIGFILE(pFile); return pFile->pMethods->xShmLock(pFile,offset,n,flags); } /* Memory barrier operation on shared memory */ static void apndShmBarrier(sqlite3_file *pFile){ pFile = ORIGFILE(pFile); pFile->pMethods->xShmBarrier(pFile); } /* Unmap a shared memory segment */ static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){ pFile = ORIGFILE(pFile); return pFile->pMethods->xShmUnmap(pFile,deleteFlag); } /* Fetch a page of a memory-mapped file */ static int apndFetch( sqlite3_file *pFile, sqlite3_int64 iOfst, int iAmt, void **pp ){ ApndFile *p = (ApndFile *)pFile; pFile = ORIGFILE(pFile); return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp); } /* Release a memory-mapped page */ static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){ ApndFile *p = (ApndFile *)pFile; pFile = ORIGFILE(pFile); return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage); } /* ** Check to see if the file is an ordinary SQLite database file. */ static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){ int rc; char zHdr[16]; static const char aSqliteHdr[] = "SQLite format 3"; if( sz<512 ) return 0; rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0); if( rc ) return 0; return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0; } /* ** Try to read the append-mark off the end of a file. Return the ** start of the appended database if the append-mark is present. If ** there is no append-mark, return -1; */ static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){ int rc, i; sqlite3_int64 iMark; unsigned char a[APND_MARK_SIZE]; if( sz<=APND_MARK_SIZE ) return -1; rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE); if( rc ) return -1; if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1; iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56; for(i=1; i<8; i++){ iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i); } return iMark; } /* ** Open an apnd file handle. */ static int apndOpen( sqlite3_vfs *pVfs, const char *zName, sqlite3_file *pFile, int flags, int *pOutFlags ){ ApndFile *p; sqlite3_file *pSubFile; sqlite3_vfs *pSubVfs; int rc; sqlite3_int64 sz; pSubVfs = ORIGVFS(pVfs); if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){ return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags); } p = (ApndFile*)pFile; memset(p, 0, sizeof(*p)); pSubFile = ORIGFILE(pFile); p->base.pMethods = &apnd_io_methods; rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags); if( rc ) goto apnd_open_done; rc = pSubFile->pMethods->xFileSize(pSubFile, &sz); if( rc ){ pSubFile->pMethods->xClose(pSubFile); goto apnd_open_done; } if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){ memmove(pFile, pSubFile, pSubVfs->szOsFile); return SQLITE_OK; } p->iMark = 0; p->iPgOne = apndReadMark(sz, pFile); if( p->iPgOne>0 ){ return SQLITE_OK; } if( (flags & SQLITE_OPEN_CREATE)==0 ){ pSubFile->pMethods->xClose(pSubFile); rc = SQLITE_CANTOPEN; } p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff; apnd_open_done: if( rc ) pFile->pMethods = 0; return rc; } /* ** All other VFS methods are pass-thrus. */ static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync); } static int apndAccess( sqlite3_vfs *pVfs, const char *zPath, int flags, int *pResOut ){ return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut); } static int apndFullPathname( sqlite3_vfs *pVfs, const char *zPath, int nOut, char *zOut ){ return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut); } static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){ return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath); } static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg); } static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym); } static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){ ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle); } static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut); } static int apndSleep(sqlite3_vfs *pVfs, int nMicro){ return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro); } static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut); } static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){ return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b); } static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){ return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p); } static int apndSetSystemCall( sqlite3_vfs *pVfs, const char *zName, sqlite3_syscall_ptr pCall ){ return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall); } static sqlite3_syscall_ptr apndGetSystemCall( sqlite3_vfs *pVfs, const char *zName ){ return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName); } static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){ return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName); } #ifdef _WIN32 #endif /* ** This routine is called when the extension is loaded. ** Register the new VFS. */ int sqlite3_appendvfs_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; sqlite3_vfs *pOrig; SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; (void)db; pOrig = sqlite3_vfs_find(0); apnd_vfs.iVersion = pOrig->iVersion; apnd_vfs.pAppData = pOrig; apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile); rc = sqlite3_vfs_register(&apnd_vfs, 0); #ifdef APPENDVFS_TEST if( rc==SQLITE_OK ){ rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister); } #endif if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY; return rc; } /************************* End ../ext/misc/appendvfs.c ********************/ #ifdef SQLITE_HAVE_ZLIB /************************* Begin ../ext/misc/zipfile.c ******************/ /* ** 2017-12-26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file implements a virtual table for reading and writing ZIP archive ** files. ** ** Usage example: ** ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename); ** ** Current limitations: ** ** * No support for encryption ** * No support for ZIP archives spanning multiple files ** * No support for zip64 extensions ** * Only the "inflate/deflate" (zlib) compression method is supported */ SQLITE_EXTENSION_INIT1 #include <stdio.h> #include <string.h> #include <assert.h> #include <zlib.h> #ifndef SQLITE_OMIT_VIRTUALTABLE #ifndef SQLITE_AMALGAMATION /* typedef sqlite3_int64 i64; */ /* typedef unsigned char u8; */ typedef unsigned short u16; typedef unsigned long u32; #define MIN(a,b) ((a)<(b) ? (a) : (b)) #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) # define ALWAYS(X) (1) # define NEVER(X) (0) #elif !defined(NDEBUG) # define ALWAYS(X) ((X)?1:(assert(0),0)) # define NEVER(X) ((X)?(assert(0),1):0) #else # define ALWAYS(X) (X) # define NEVER(X) (X) #endif #endif /* SQLITE_AMALGAMATION */ /* ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK. ** ** In some ways it would be better to obtain these values from system ** header files. But, the dependency is undesirable and (a) these ** have been stable for decades, (b) the values are part of POSIX and ** are also made explicit in [man stat], and (c) are part of the ** file format for zip archives. */ #ifndef S_IFDIR # define S_IFDIR 0040000 #endif #ifndef S_IFREG # define S_IFREG 0100000 #endif #ifndef S_IFLNK # define S_IFLNK 0120000 #endif static const char ZIPFILE_SCHEMA[] = "CREATE TABLE y(" "name PRIMARY KEY," /* 0: Name of file in zip archive */ "mode," /* 1: POSIX mode for file */ "mtime," /* 2: Last modification time (secs since 1970)*/ "sz," /* 3: Size of object */ "rawdata," /* 4: Raw data */ "data," /* 5: Uncompressed data */ "method," /* 6: Compression method (integer) */ "z HIDDEN" /* 7: Name of zip file */ ") WITHOUT ROWID;"; #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */ #define ZIPFILE_BUFFER_SIZE (64*1024) /* ** Magic numbers used to read and write zip files. ** ** ZIPFILE_NEWENTRY_MADEBY: ** Use this value for the "version-made-by" field in new zip file ** entries. The upper byte indicates "unix", and the lower byte ** indicates that the zip file matches pkzip specification 3.0. ** This is what info-zip seems to do. ** ** ZIPFILE_NEWENTRY_REQUIRED: ** Value for "version-required-to-extract" field of new entries. ** Version 2.0 is required to support folders and deflate compression. ** ** ZIPFILE_NEWENTRY_FLAGS: ** Value for "general-purpose-bit-flags" field of new entries. Bit ** 11 means "utf-8 filename and comment". ** ** ZIPFILE_SIGNATURE_CDS: ** First 4 bytes of a valid CDS record. ** ** ZIPFILE_SIGNATURE_LFH: ** First 4 bytes of a valid LFH record. ** ** ZIPFILE_SIGNATURE_EOCD ** First 4 bytes of a valid EOCD record. */ #define ZIPFILE_EXTRA_TIMESTAMP 0x5455 #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30) #define ZIPFILE_NEWENTRY_REQUIRED 20 #define ZIPFILE_NEWENTRY_FLAGS 0x800 #define ZIPFILE_SIGNATURE_CDS 0x02014b50 #define ZIPFILE_SIGNATURE_LFH 0x04034b50 #define ZIPFILE_SIGNATURE_EOCD 0x06054b50 /* ** The sizes of the fixed-size part of each of the three main data ** structures in a zip archive. */ #define ZIPFILE_LFH_FIXED_SZ 30 #define ZIPFILE_EOCD_FIXED_SZ 22 #define ZIPFILE_CDS_FIXED_SZ 46 /* *** 4.3.16 End of central directory record: *** *** end of central dir signature 4 bytes (0x06054b50) *** number of this disk 2 bytes *** number of the disk with the *** start of the central directory 2 bytes *** total number of entries in the *** central directory on this disk 2 bytes *** total number of entries in *** the central directory 2 bytes *** size of the central directory 4 bytes *** offset of start of central *** directory with respect to *** the starting disk number 4 bytes *** .ZIP file comment length 2 bytes *** .ZIP file comment (variable size) */ typedef struct ZipfileEOCD ZipfileEOCD; struct ZipfileEOCD { u16 iDisk; u16 iFirstDisk; u16 nEntry; u16 nEntryTotal; u32 nSize; u32 iOffset; }; /* *** 4.3.12 Central directory structure: *** *** ... *** *** central file header signature 4 bytes (0x02014b50) *** version made by 2 bytes *** version needed to extract 2 bytes *** general purpose bit flag 2 bytes *** compression method 2 bytes *** last mod file time 2 bytes *** last mod file date 2 bytes *** crc-32 4 bytes *** compressed size 4 bytes *** uncompressed size 4 bytes *** file name length 2 bytes *** extra field length 2 bytes *** file comment length 2 bytes *** disk number start 2 bytes *** internal file attributes 2 bytes *** external file attributes 4 bytes *** relative offset of local header 4 bytes */ typedef struct ZipfileCDS ZipfileCDS; struct ZipfileCDS { u16 iVersionMadeBy; u16 iVersionExtract; u16 flags; u16 iCompression; u16 mTime; u16 mDate; u32 crc32; u32 szCompressed; u32 szUncompressed; u16 nFile; u16 nExtra; u16 nComment; u16 iDiskStart; u16 iInternalAttr; u32 iExternalAttr; u32 iOffset; char *zFile; /* Filename (sqlite3_malloc()) */ }; /* *** 4.3.7 Local file header: *** *** local file header signature 4 bytes (0x04034b50) *** version needed to extract 2 bytes *** general purpose bit flag 2 bytes *** compression method 2 bytes *** last mod file time 2 bytes *** last mod file date 2 bytes *** crc-32 4 bytes *** compressed size 4 bytes *** uncompressed size 4 bytes *** file name length 2 bytes *** extra field length 2 bytes *** */ typedef struct ZipfileLFH ZipfileLFH; struct ZipfileLFH { u16 iVersionExtract; u16 flags; u16 iCompression; u16 mTime; u16 mDate; u32 crc32; u32 szCompressed; u32 szUncompressed; u16 nFile; u16 nExtra; }; typedef struct ZipfileEntry ZipfileEntry; struct ZipfileEntry { ZipfileCDS cds; /* Parsed CDS record */ u32 mUnixTime; /* Modification time, in UNIX format */ u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */ i64 iDataOff; /* Offset to data in file (if aData==0) */ u8 *aData; /* cds.szCompressed bytes of compressed data */ ZipfileEntry *pNext; /* Next element in in-memory CDS */ }; /* ** Cursor type for zipfile tables. */ typedef struct ZipfileCsr ZipfileCsr; struct ZipfileCsr { sqlite3_vtab_cursor base; /* Base class - must be first */ i64 iId; /* Cursor ID */ u8 bEof; /* True when at EOF */ u8 bNoop; /* If next xNext() call is no-op */ /* Used outside of write transactions */ FILE *pFile; /* Zip file */ i64 iNextOff; /* Offset of next record in central directory */ ZipfileEOCD eocd; /* Parse of central directory record */ ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */ ZipfileEntry *pCurrent; /* Current entry */ ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */ }; typedef struct ZipfileTab ZipfileTab; struct ZipfileTab { sqlite3_vtab base; /* Base class - must be first */ char *zFile; /* Zip file this table accesses (may be NULL) */ sqlite3 *db; /* Host database connection */ u8 *aBuffer; /* Temporary buffer used for various tasks */ ZipfileCsr *pCsrList; /* List of cursors */ i64 iNextCsrid; /* The following are used by write transactions only */ ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */ ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */ FILE *pWriteFd; /* File handle open on zip archive */ i64 szCurrent; /* Current size of zip archive */ i64 szOrig; /* Size of archive at start of transaction */ }; /* ** Set the error message contained in context ctx to the results of ** vprintf(zFmt, ...). */ static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ char *zMsg = 0; va_list ap; va_start(ap, zFmt); zMsg = sqlite3_vmprintf(zFmt, ap); sqlite3_result_error(ctx, zMsg, -1); sqlite3_free(zMsg); va_end(ap); } /* ** If string zIn is quoted, dequote it in place. Otherwise, if the string ** is not quoted, do nothing. */ static void zipfileDequote(char *zIn){ char q = zIn[0]; if( q=='"' || q=='\'' || q=='`' || q=='[' ){ int iIn = 1; int iOut = 0; if( q=='[' ) q = ']'; while( ALWAYS(zIn[iIn]) ){ char c = zIn[iIn++]; if( c==q && zIn[iIn++]!=q ) break; zIn[iOut++] = c; } zIn[iOut] = '\0'; } } /* ** Construct a new ZipfileTab virtual table object. ** ** argv[0] -> module name ("zipfile") ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> "column name" and other module argument fields. */ static int zipfileConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE; int nFile = 0; const char *zFile = 0; ZipfileTab *pNew = 0; int rc; /* If the table name is not "zipfile", require that the argument be ** specified. This stops zipfile tables from being created as: ** ** CREATE VIRTUAL TABLE zzz USING zipfile(); ** ** It does not prevent: ** ** CREATE VIRTUAL TABLE zipfile USING zipfile(); */ assert( 0==sqlite3_stricmp(argv[0], "zipfile") ); if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){ *pzErr = sqlite3_mprintf("zipfile constructor requires one argument"); return SQLITE_ERROR; } if( argc>3 ){ zFile = argv[3]; nFile = (int)strlen(zFile)+1; } rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA); if( rc==SQLITE_OK ){ pNew = (ZipfileTab*)sqlite3_malloc(nByte+nFile); if( pNew==0 ) return SQLITE_NOMEM; memset(pNew, 0, nByte+nFile); pNew->db = db; pNew->aBuffer = (u8*)&pNew[1]; if( zFile ){ pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; memcpy(pNew->zFile, zFile, nFile); zipfileDequote(pNew->zFile); } } *ppVtab = (sqlite3_vtab*)pNew; return rc; } /* ** Free the ZipfileEntry structure indicated by the only argument. */ static void zipfileEntryFree(ZipfileEntry *p){ if( p ){ sqlite3_free(p->cds.zFile); sqlite3_free(p); } } /* ** Release resources that should be freed at the end of a write ** transaction. */ static void zipfileCleanupTransaction(ZipfileTab *pTab){ ZipfileEntry *pEntry; ZipfileEntry *pNext; if( pTab->pWriteFd ){ fclose(pTab->pWriteFd); pTab->pWriteFd = 0; } for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ pNext = pEntry->pNext; zipfileEntryFree(pEntry); } pTab->pFirstEntry = 0; pTab->pLastEntry = 0; pTab->szCurrent = 0; pTab->szOrig = 0; } /* ** This method is the destructor for zipfile vtab objects. */ static int zipfileDisconnect(sqlite3_vtab *pVtab){ zipfileCleanupTransaction((ZipfileTab*)pVtab); sqlite3_free(pVtab); return SQLITE_OK; } /* ** Constructor for a new ZipfileCsr object. */ static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){ ZipfileTab *pTab = (ZipfileTab*)p; ZipfileCsr *pCsr; pCsr = sqlite3_malloc(sizeof(*pCsr)); *ppCsr = (sqlite3_vtab_cursor*)pCsr; if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(*pCsr)); pCsr->iId = ++pTab->iNextCsrid; pCsr->pCsrNext = pTab->pCsrList; pTab->pCsrList = pCsr; return SQLITE_OK; } /* ** Reset a cursor back to the state it was in when first returned ** by zipfileOpen(). */ static void zipfileResetCursor(ZipfileCsr *pCsr){ ZipfileEntry *p; ZipfileEntry *pNext; pCsr->bEof = 0; if( pCsr->pFile ){ fclose(pCsr->pFile); pCsr->pFile = 0; zipfileEntryFree(pCsr->pCurrent); pCsr->pCurrent = 0; } for(p=pCsr->pFreeEntry; p; p=pNext){ pNext = p->pNext; zipfileEntryFree(p); } } /* ** Destructor for an ZipfileCsr. */ static int zipfileClose(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); ZipfileCsr **pp; zipfileResetCursor(pCsr); /* Remove this cursor from the ZipfileTab.pCsrList list. */ for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); *pp = pCsr->pCsrNext; sqlite3_free(pCsr); return SQLITE_OK; } /* ** Set the error message for the virtual table associated with cursor ** pCsr to the results of vprintf(zFmt, ...). */ static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); sqlite3_free(pTab->base.zErrMsg); pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); va_end(ap); } static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); sqlite3_free(pCsr->base.pVtab->zErrMsg); pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); va_end(ap); } /* ** Read nRead bytes of data from offset iOff of file pFile into buffer ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code ** otherwise. ** ** If an error does occur, output variable (*pzErrmsg) may be set to point ** to an English language error message. It is the responsibility of the ** caller to eventually free this buffer using ** sqlite3_free(). */ static int zipfileReadData( FILE *pFile, /* Read from this file */ u8 *aRead, /* Read into this buffer */ int nRead, /* Number of bytes to read */ i64 iOff, /* Offset to read from */ char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */ ){ size_t n; fseek(pFile, (long)iOff, SEEK_SET); n = fread(aRead, 1, nRead, pFile); if( (int)n!=nRead ){ *pzErrmsg = sqlite3_mprintf("error in fread()"); return SQLITE_ERROR; } return SQLITE_OK; } static int zipfileAppendData( ZipfileTab *pTab, const u8 *aWrite, int nWrite ){ size_t n; fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); if( (int)n!=nWrite ){ pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); return SQLITE_ERROR; } pTab->szCurrent += nWrite; return SQLITE_OK; } /* ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf. */ static u16 zipfileGetU16(const u8 *aBuf){ return (aBuf[1] << 8) + aBuf[0]; } /* ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf. */ static u32 zipfileGetU32(const u8 *aBuf){ return ((u32)(aBuf[3]) << 24) + ((u32)(aBuf[2]) << 16) + ((u32)(aBuf[1]) << 8) + ((u32)(aBuf[0]) << 0); } /* ** Write a 16-bit little endiate integer into buffer aBuf. */ static void zipfilePutU16(u8 *aBuf, u16 val){ aBuf[0] = val & 0xFF; aBuf[1] = (val>>8) & 0xFF; } /* ** Write a 32-bit little endiate integer into buffer aBuf. */ static void zipfilePutU32(u8 *aBuf, u32 val){ aBuf[0] = val & 0xFF; aBuf[1] = (val>>8) & 0xFF; aBuf[2] = (val>>16) & 0xFF; aBuf[3] = (val>>24) & 0xFF; } #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) ) #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) ) #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; } #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; } /* ** Magic numbers used to read CDS records. */ #define ZIPFILE_CDS_NFILE_OFF 28 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20 /* ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR ** if the record is not well-formed, or SQLITE_OK otherwise. */ static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){ u8 *aRead = aBuf; u32 sig = zipfileRead32(aRead); int rc = SQLITE_OK; if( sig!=ZIPFILE_SIGNATURE_CDS ){ rc = SQLITE_ERROR; }else{ pCDS->iVersionMadeBy = zipfileRead16(aRead); pCDS->iVersionExtract = zipfileRead16(aRead); pCDS->flags = zipfileRead16(aRead); pCDS->iCompression = zipfileRead16(aRead); pCDS->mTime = zipfileRead16(aRead); pCDS->mDate = zipfileRead16(aRead); pCDS->crc32 = zipfileRead32(aRead); pCDS->szCompressed = zipfileRead32(aRead); pCDS->szUncompressed = zipfileRead32(aRead); assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); pCDS->nFile = zipfileRead16(aRead); pCDS->nExtra = zipfileRead16(aRead); pCDS->nComment = zipfileRead16(aRead); pCDS->iDiskStart = zipfileRead16(aRead); pCDS->iInternalAttr = zipfileRead16(aRead); pCDS->iExternalAttr = zipfileRead32(aRead); pCDS->iOffset = zipfileRead32(aRead); assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] ); } return rc; } /* ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR ** if the record is not well-formed, or SQLITE_OK otherwise. */ static int zipfileReadLFH( u8 *aBuffer, ZipfileLFH *pLFH ){ u8 *aRead = aBuffer; int rc = SQLITE_OK; u32 sig = zipfileRead32(aRead); if( sig!=ZIPFILE_SIGNATURE_LFH ){ rc = SQLITE_ERROR; }else{ pLFH->iVersionExtract = zipfileRead16(aRead); pLFH->flags = zipfileRead16(aRead); pLFH->iCompression = zipfileRead16(aRead); pLFH->mTime = zipfileRead16(aRead); pLFH->mDate = zipfileRead16(aRead); pLFH->crc32 = zipfileRead32(aRead); pLFH->szCompressed = zipfileRead32(aRead); pLFH->szUncompressed = zipfileRead32(aRead); pLFH->nFile = zipfileRead16(aRead); pLFH->nExtra = zipfileRead16(aRead); } return rc; } /* ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields. ** Scan through this buffer to find an "extra-timestamp" field. If one ** exists, extract the 32-bit modification-timestamp from it and store ** the value in output parameter *pmTime. ** ** Zero is returned if no extra-timestamp record could be found (and so ** *pmTime is left unchanged), or non-zero otherwise. ** ** The general format of an extra field is: ** ** Header ID 2 bytes ** Data Size 2 bytes ** Data N bytes */ static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){ int ret = 0; u8 *p = aExtra; u8 *pEnd = &aExtra[nExtra]; while( p<pEnd ){ u16 id = zipfileRead16(p); u16 nByte = zipfileRead16(p); switch( id ){ case ZIPFILE_EXTRA_TIMESTAMP: { u8 b = p[0]; if( b & 0x01 ){ /* 0x01 -> modtime is present */ *pmTime = zipfileGetU32(&p[1]); ret = 1; } break; } } p += nByte; } return ret; } /* ** Convert the standard MS-DOS timestamp stored in the mTime and mDate ** fields of the CDS structure passed as the only argument to a 32-bit ** UNIX seconds-since-the-epoch timestamp. Return the result. ** ** "Standard" MS-DOS time format: ** ** File modification time: ** Bits 00-04: seconds divided by 2 ** Bits 05-10: minute ** Bits 11-15: hour ** File modification date: ** Bits 00-04: day ** Bits 05-08: month (1-12) ** Bits 09-15: years from 1980 ** ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx */ static u32 zipfileMtime(ZipfileCDS *pCDS){ int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); int M = ((pCDS->mDate >> 5) & 0x0F); int D = (pCDS->mDate & 0x1F); int B = -13; int sec = (pCDS->mTime & 0x1F)*2; int min = (pCDS->mTime >> 5) & 0x3F; int hr = (pCDS->mTime >> 11) & 0x1F; i64 JD; /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */ /* Calculate the JD in seconds for noon on the day in question */ if( M<3 ){ Y = Y-1; M = M+12; } JD = (i64)(24*60*60) * ( (int)(365.25 * (Y + 4716)) + (int)(30.6001 * (M + 1)) + D + B - 1524 ); /* Correct the JD for the time within the day */ JD += (hr-12) * 3600 + min * 60 + sec; /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */ return (u32)(JD - (i64)(24405875) * 24*60*6); } /* ** The opposite of zipfileMtime(). This function populates the mTime and ** mDate fields of the CDS structure passed as the first argument according ** to the UNIX timestamp value passed as the second. */ static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){ /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */ i64 JD = (i64)2440588 + mUnixTime / (24*60*60); int A, B, C, D, E; int yr, mon, day; int hr, min, sec; A = (int)((JD - 1867216.25)/36524.25); A = (int)(JD + 1 + A - (A/4)); B = A + 1524; C = (int)((B - 122.1)/365.25); D = (36525*(C&32767))/100; E = (int)((B-D)/30.6001); day = B - D - (int)(30.6001*E); mon = (E<14 ? E-1 : E-13); yr = mon>2 ? C-4716 : C-4715; hr = (mUnixTime % (24*60*60)) / (60*60); min = (mUnixTime % (60*60)) / 60; sec = (mUnixTime % 60); if( yr>=1980 ){ pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); }else{ pCds->mDate = pCds->mTime = 0; } assert( mUnixTime<315507600 || mUnixTime==zipfileMtime(pCds) || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) /* || (mUnixTime % 2) */ ); } /* ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in ** size) containing an entire zip archive image. Or, if aBlob is NULL, ** then pFile is a file-handle open on a zip file. In either case, this ** function creates a ZipfileEntry object based on the zip archive entry ** for which the CDS record is at offset iOff. ** ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to ** the new object. Otherwise, an SQLite error code is returned and the ** final value of (*ppEntry) undefined. */ static int zipfileGetEntry( ZipfileTab *pTab, /* Store any error message here */ const u8 *aBlob, /* Pointer to in-memory file image */ int nBlob, /* Size of aBlob[] in bytes */ FILE *pFile, /* If aBlob==0, read from this file */ i64 iOff, /* Offset of CDS record */ ZipfileEntry **ppEntry /* OUT: Pointer to new object */ ){ u8 *aRead; char **pzErr = &pTab->base.zErrMsg; int rc = SQLITE_OK; if( aBlob==0 ){ aRead = pTab->aBuffer; rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr); }else{ aRead = (u8*)&aBlob[iOff]; } if( rc==SQLITE_OK ){ int nAlloc; ZipfileEntry *pNew; int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]); int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]); nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]); nAlloc = sizeof(ZipfileEntry) + nExtra; if( aBlob ){ nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]); } pNew = (ZipfileEntry*)sqlite3_malloc(nAlloc); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ memset(pNew, 0, sizeof(ZipfileEntry)); rc = zipfileReadCDS(aRead, &pNew->cds); if( rc!=SQLITE_OK ){ *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff); }else if( aBlob==0 ){ rc = zipfileReadData( pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr ); }else{ aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ]; } } if( rc==SQLITE_OK ){ u32 *pt = &pNew->mUnixTime; pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); pNew->aExtra = (u8*)&pNew[1]; memcpy(pNew->aExtra, &aRead[nFile], nExtra); if( pNew->cds.zFile==0 ){ rc = SQLITE_NOMEM; }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ pNew->mUnixTime = zipfileMtime(&pNew->cds); } } if( rc==SQLITE_OK ){ static const int szFix = ZIPFILE_LFH_FIXED_SZ; ZipfileLFH lfh; if( pFile ){ rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); }else{ aRead = (u8*)&aBlob[pNew->cds.iOffset]; } rc = zipfileReadLFH(aRead, &lfh); if( rc==SQLITE_OK ){ pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; pNew->iDataOff += lfh.nFile + lfh.nExtra; if( aBlob && pNew->cds.szCompressed ){ pNew->aData = &pNew->aExtra[nExtra]; memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); } }else{ *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", (int)pNew->cds.iOffset ); } } if( rc!=SQLITE_OK ){ zipfileEntryFree(pNew); }else{ *ppEntry = pNew; } } return rc; } /* ** Advance an ZipfileCsr to its next row of output. */ static int zipfileNext(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; int rc = SQLITE_OK; if( pCsr->pFile ){ i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; zipfileEntryFree(pCsr->pCurrent); pCsr->pCurrent = 0; if( pCsr->iNextOff>=iEof ){ pCsr->bEof = 1; }else{ ZipfileEntry *p = 0; ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); if( rc==SQLITE_OK ){ pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; } pCsr->pCurrent = p; } }else{ if( !pCsr->bNoop ){ pCsr->pCurrent = pCsr->pCurrent->pNext; } if( pCsr->pCurrent==0 ){ pCsr->bEof = 1; } } pCsr->bNoop = 0; return rc; } static void zipfileFree(void *p) { sqlite3_free(p); } /* ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the ** size is nOut bytes. This function uncompresses the data and sets the ** return value in context pCtx to the result (a blob). ** ** If an error occurs, an error code is left in pCtx instead. */ static void zipfileInflate( sqlite3_context *pCtx, /* Store result here */ const u8 *aIn, /* Compressed data */ int nIn, /* Size of buffer aIn[] in bytes */ int nOut /* Expected output size */ ){ u8 *aRes = sqlite3_malloc(nOut); if( aRes==0 ){ sqlite3_result_error_nomem(pCtx); }else{ int err; z_stream str; memset(&str, 0, sizeof(str)); str.next_in = (Byte*)aIn; str.avail_in = nIn; str.next_out = (Byte*)aRes; str.avail_out = nOut; err = inflateInit2(&str, -15); if( err!=Z_OK ){ zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err); }else{ err = inflate(&str, Z_NO_FLUSH); if( err!=Z_STREAM_END ){ zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err); }else{ sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree); aRes = 0; } } sqlite3_free(aRes); inflateEnd(&str); } } /* ** Buffer aIn (size nIn bytes) contains uncompressed data. This function ** compresses it and sets (*ppOut) to point to a buffer containing the ** compressed data. The caller is responsible for eventually calling ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) ** is set to the size of buffer (*ppOut) in bytes. ** ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error ** code is returned and an error message left in virtual-table handle ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this ** case. */ static int zipfileDeflate( const u8 *aIn, int nIn, /* Input */ u8 **ppOut, int *pnOut, /* Output */ char **pzErr /* OUT: Error message */ ){ int nAlloc = (int)compressBound(nIn); u8 *aOut; int rc = SQLITE_OK; aOut = (u8*)sqlite3_malloc(nAlloc); if( aOut==0 ){ rc = SQLITE_NOMEM; }else{ int res; z_stream str; memset(&str, 0, sizeof(str)); str.next_in = (Bytef*)aIn; str.avail_in = nIn; str.next_out = aOut; str.avail_out = nAlloc; deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); res = deflate(&str, Z_FINISH); if( res==Z_STREAM_END ){ *ppOut = aOut; *pnOut = (int)str.total_out; }else{ sqlite3_free(aOut); *pzErr = sqlite3_mprintf("zipfile: deflate() error"); rc = SQLITE_ERROR; } deflateEnd(&str); } return rc; } /* ** Return values of columns for the row at which the series_cursor ** is currently pointing. */ static int zipfileColumn( sqlite3_vtab_cursor *cur, /* The cursor */ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ int i /* Which column to return */ ){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; ZipfileCDS *pCDS = &pCsr->pCurrent->cds; int rc = SQLITE_OK; switch( i ){ case 0: /* name */ sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); break; case 1: /* mode */ /* TODO: Whether or not the following is correct surely depends on ** the platform on which the archive was created. */ sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); break; case 2: { /* mtime */ sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); break; } case 3: { /* sz */ if( sqlite3_vtab_nochange(ctx)==0 ){ sqlite3_result_int64(ctx, pCDS->szUncompressed); } break; } case 4: /* rawdata */ if( sqlite3_vtab_nochange(ctx) ) break; case 5: { /* data */ if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ int sz = pCDS->szCompressed; int szFinal = pCDS->szUncompressed; if( szFinal>0 ){ u8 *aBuf; u8 *aFree = 0; if( pCsr->pCurrent->aData ){ aBuf = pCsr->pCurrent->aData; }else{ aBuf = aFree = sqlite3_malloc(sz); if( aBuf==0 ){ rc = SQLITE_NOMEM; }else{ FILE *pFile = pCsr->pFile; if( pFile==0 ){ pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; } rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, &pCsr->base.pVtab->zErrMsg ); } } if( rc==SQLITE_OK ){ if( i==5 && pCDS->iCompression ){ zipfileInflate(ctx, aBuf, sz, szFinal); }else{ sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT); } } sqlite3_free(aFree); }else{ /* Figure out if this is a directory or a zero-sized file. Consider ** it to be a directory either if the mode suggests so, or if ** the final character in the name is '/'. */ u32 mode = pCDS->iExternalAttr >> 16; if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){ sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC); } } } break; } case 6: /* method */ sqlite3_result_int(ctx, pCDS->iCompression); break; default: /* z */ assert( i==7 ); sqlite3_result_int64(ctx, pCsr->iId); break; } return rc; } /* ** Return TRUE if the cursor is at EOF. */ static int zipfileEof(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; return pCsr->bEof; } /* ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile ** is guaranteed to be a file-handle open on a zip file. ** ** This function attempts to locate the EOCD record within the zip archive ** and populate *pEOCD with the results of decoding it. SQLITE_OK is ** returned if successful. Otherwise, an SQLite error code is returned and ** an English language error message may be left in virtual-table pTab. */ static int zipfileReadEOCD( ZipfileTab *pTab, /* Return errors here */ const u8 *aBlob, /* Pointer to in-memory file image */ int nBlob, /* Size of aBlob[] in bytes */ FILE *pFile, /* Read from this file if aBlob==0 */ ZipfileEOCD *pEOCD /* Object to populate */ ){ u8 *aRead = pTab->aBuffer; /* Temporary buffer */ int nRead; /* Bytes to read from file */ int rc = SQLITE_OK; if( aBlob==0 ){ i64 iOff; /* Offset to read from */ i64 szFile; /* Total size of file in bytes */ fseek(pFile, 0, SEEK_END); szFile = (i64)ftell(pFile); if( szFile==0 ){ memset(pEOCD, 0, sizeof(ZipfileEOCD)); return SQLITE_OK; } nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE)); iOff = szFile - nRead; rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); }else{ nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE)); aRead = (u8*)&aBlob[nBlob-nRead]; } if( rc==SQLITE_OK ){ int i; /* Scan backwards looking for the signature bytes */ for(i=nRead-20; i>=0; i--){ if( aRead[i]==0x50 && aRead[i+1]==0x4b && aRead[i+2]==0x05 && aRead[i+3]==0x06 ){ break; } } if( i<0 ){ pTab->base.zErrMsg = sqlite3_mprintf( "cannot find end of central directory record" ); return SQLITE_ERROR; } aRead += i+4; pEOCD->iDisk = zipfileRead16(aRead); pEOCD->iFirstDisk = zipfileRead16(aRead); pEOCD->nEntry = zipfileRead16(aRead); pEOCD->nEntryTotal = zipfileRead16(aRead); pEOCD->nSize = zipfileRead32(aRead); pEOCD->iOffset = zipfileRead32(aRead); } return rc; } /* ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added ** to the end of the list. Otherwise, it is added to the list immediately ** before pBefore (which is guaranteed to be a part of said list). */ static void zipfileAddEntry( ZipfileTab *pTab, ZipfileEntry *pBefore, ZipfileEntry *pNew ){ assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); assert( pNew->pNext==0 ); if( pBefore==0 ){ if( pTab->pFirstEntry==0 ){ pTab->pFirstEntry = pTab->pLastEntry = pNew; }else{ assert( pTab->pLastEntry->pNext==0 ); pTab->pLastEntry->pNext = pNew; pTab->pLastEntry = pNew; } }else{ ZipfileEntry **pp; for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); pNew->pNext = pBefore; *pp = pNew; } } static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){ ZipfileEOCD eocd; int rc; int i; i64 iOff; rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); iOff = eocd.iOffset; for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){ ZipfileEntry *pNew = 0; rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew); if( rc==SQLITE_OK ){ zipfileAddEntry(pTab, 0, pNew); iOff += ZIPFILE_CDS_FIXED_SZ; iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; } } return rc; } /* ** xFilter callback. */ static int zipfileFilter( sqlite3_vtab_cursor *cur, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; ZipfileCsr *pCsr = (ZipfileCsr*)cur; const char *zFile = 0; /* Zip file to scan */ int rc = SQLITE_OK; /* Return Code */ int bInMemory = 0; /* True for an in-memory zipfile */ zipfileResetCursor(pCsr); if( pTab->zFile ){ zFile = pTab->zFile; }else if( idxNum==0 ){ zipfileCursorErr(pCsr, "zipfile() function requires an argument"); return SQLITE_ERROR; }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]); int nBlob = sqlite3_value_bytes(argv[0]); assert( pTab->pFirstEntry==0 ); rc = zipfileLoadDirectory(pTab, aBlob, nBlob); pCsr->pFreeEntry = pTab->pFirstEntry; pTab->pFirstEntry = pTab->pLastEntry = 0; if( rc!=SQLITE_OK ) return rc; bInMemory = 1; }else{ zFile = (const char*)sqlite3_value_text(argv[0]); } if( 0==pTab->pWriteFd && 0==bInMemory ){ pCsr->pFile = fopen(zFile, "rb"); if( pCsr->pFile==0 ){ zipfileCursorErr(pCsr, "cannot open file: %s", zFile); rc = SQLITE_ERROR; }else{ rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); if( rc==SQLITE_OK ){ if( pCsr->eocd.nEntry==0 ){ pCsr->bEof = 1; }else{ pCsr->iNextOff = pCsr->eocd.iOffset; rc = zipfileNext(cur); } } } }else{ pCsr->bNoop = 1; pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; rc = zipfileNext(cur); } return rc; } /* ** xBestIndex callback. */ static int zipfileBestIndex( sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo ){ int i; for(i=0; i<pIdxInfo->nConstraint; i++){ const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; if( pCons->usable==0 ) continue; if( pCons->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; break; } if( i<pIdxInfo->nConstraint ){ pIdxInfo->aConstraintUsage[i].argvIndex = 1; pIdxInfo->aConstraintUsage[i].omit = 1; pIdxInfo->estimatedCost = 1000.0; pIdxInfo->idxNum = 1; }else{ pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50); pIdxInfo->idxNum = 0; } return SQLITE_OK; } static ZipfileEntry *zipfileNewEntry(const char *zPath){ ZipfileEntry *pNew; pNew = sqlite3_malloc(sizeof(ZipfileEntry)); if( pNew ){ memset(pNew, 0, sizeof(ZipfileEntry)); pNew->cds.zFile = sqlite3_mprintf("%s", zPath); if( pNew->cds.zFile==0 ){ sqlite3_free(pNew); pNew = 0; } } return pNew; } static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){ ZipfileCDS *pCds = &pEntry->cds; u8 *a = aBuf; pCds->nExtra = 9; /* Write the LFH itself */ zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH); zipfileWrite16(a, pCds->iVersionExtract); zipfileWrite16(a, pCds->flags); zipfileWrite16(a, pCds->iCompression); zipfileWrite16(a, pCds->mTime); zipfileWrite16(a, pCds->mDate); zipfileWrite32(a, pCds->crc32); zipfileWrite32(a, pCds->szCompressed); zipfileWrite32(a, pCds->szUncompressed); zipfileWrite16(a, (u16)pCds->nFile); zipfileWrite16(a, pCds->nExtra); assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] ); /* Add the file name */ memcpy(a, pCds->zFile, (int)pCds->nFile); a += (int)pCds->nFile; /* The "extra" data */ zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); zipfileWrite16(a, 5); *a++ = 0x01; zipfileWrite32(a, pEntry->mUnixTime); return a-aBuf; } static int zipfileAppendEntry( ZipfileTab *pTab, ZipfileEntry *pEntry, const u8 *pData, int nData ){ u8 *aBuf = pTab->aBuffer; int nBuf; int rc; nBuf = zipfileSerializeLFH(pEntry, aBuf); rc = zipfileAppendData(pTab, aBuf, nBuf); if( rc==SQLITE_OK ){ pEntry->iDataOff = pTab->szCurrent; rc = zipfileAppendData(pTab, pData, nData); } return rc; } static int zipfileGetMode( sqlite3_value *pVal, int bIsDir, /* If true, default to directory */ u32 *pMode, /* OUT: Mode value */ char **pzErr /* OUT: Error message */ ){ const char *z = (const char*)sqlite3_value_text(pVal); u32 mode = 0; if( z==0 ){ mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644)); }else if( z[0]>='0' && z[0]<='9' ){ mode = (unsigned int)sqlite3_value_int(pVal); }else{ const char zTemplate[11] = "-rwxrwxrwx"; int i; if( strlen(z)!=10 ) goto parse_error; switch( z[0] ){ case '-': mode |= S_IFREG; break; case 'd': mode |= S_IFDIR; break; case 'l': mode |= S_IFLNK; break; default: goto parse_error; } for(i=1; i<10; i++){ if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); else if( z[i]!='-' ) goto parse_error; } } if( ((mode & S_IFDIR)==0)==bIsDir ){ /* The "mode" attribute is a directory, but data has been specified. ** Or vice-versa - no data but "mode" is a file or symlink. */ *pzErr = sqlite3_mprintf("zipfile: mode does not match data"); return SQLITE_CONSTRAINT; } *pMode = mode; return SQLITE_OK; parse_error: *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z); return SQLITE_ERROR; } /* ** Both (const char*) arguments point to nul-terminated strings. Argument ** nB is the value of strlen(zB). This function returns 0 if the strings are ** identical, ignoring any trailing '/' character in either path. */ static int zipfileComparePath(const char *zA, const char *zB, int nB){ int nA = (int)strlen(zA); if( zA[nA-1]=='/' ) nA--; if( zB[nB-1]=='/' ) nB--; if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0; return 1; } static int zipfileBegin(sqlite3_vtab *pVtab){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; assert( pTab->pWriteFd==0 ); /* Open a write fd on the file. Also load the entire central directory ** structure into memory. During the transaction any new file data is ** appended to the archive file, but the central directory is accumulated ** in main-memory until the transaction is committed. */ pTab->pWriteFd = fopen(pTab->zFile, "ab+"); if( pTab->pWriteFd==0 ){ pTab->base.zErrMsg = sqlite3_mprintf( "zipfile: failed to open file %s for writing", pTab->zFile ); rc = SQLITE_ERROR; }else{ fseek(pTab->pWriteFd, 0, SEEK_END); pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); rc = zipfileLoadDirectory(pTab, 0, 0); } if( rc!=SQLITE_OK ){ zipfileCleanupTransaction(pTab); } return rc; } /* ** Return the current time as a 32-bit timestamp in UNIX epoch format (like ** time(2)). */ static u32 zipfileTime(void){ sqlite3_vfs *pVfs = sqlite3_vfs_find(0); u32 ret; if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ i64 ms; pVfs->xCurrentTimeInt64(pVfs, &ms); ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); }else{ double day; pVfs->xCurrentTime(pVfs, &day); ret = (u32)((day - 2440587.5) * 86400); } return ret; } /* ** Return a 32-bit timestamp in UNIX epoch format. ** ** If the value passed as the only argument is either NULL or an SQL NULL, ** return the current time. Otherwise, return the value stored in (*pVal) ** cast to a 32-bit unsigned integer. */ static u32 zipfileGetTime(sqlite3_value *pVal){ if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){ return zipfileTime(); } return (u32)sqlite3_value_int64(pVal); } /* ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry ** linked list. Remove it from the list and free the object. */ static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){ if( pOld ){ ZipfileEntry **pp; for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext)); *pp = (*pp)->pNext; zipfileEntryFree(pOld); } } /* ** xUpdate method. */ static int zipfileUpdate( sqlite3_vtab *pVtab, int nVal, sqlite3_value **apVal, sqlite_int64 *pRowid ){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; /* Return Code */ ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ u32 mode = 0; /* Mode for new entry */ u32 mTime = 0; /* Modification time for new entry */ i64 sz = 0; /* Uncompressed size */ const char *zPath = 0; /* Path for new entry */ int nPath = 0; /* strlen(zPath) */ const u8 *pData = 0; /* Pointer to buffer containing content */ int nData = 0; /* Size of pData buffer in bytes */ int iMethod = 0; /* Compression method for new entry */ u8 *pFree = 0; /* Free this */ char *zFree = 0; /* Also free this */ ZipfileEntry *pOld = 0; ZipfileEntry *pOld2 = 0; int bUpdate = 0; /* True for an update that modifies "name" */ int bIsDir = 0; u32 iCrc32 = 0; if( pTab->pWriteFd==0 ){ rc = zipfileBegin(pVtab); if( rc!=SQLITE_OK ) return rc; } /* If this is a DELETE or UPDATE, find the archive entry to delete. */ if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); int nDelete = (int)strlen(zDelete); if( nVal>1 ){ const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ bUpdate = 1; } } for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ break; } assert( pOld->pNext ); } } if( nVal>1 ){ /* Check that "sz" and "rawdata" are both NULL: */ if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ zipfileTableErr(pTab, "sz must be NULL"); rc = SQLITE_CONSTRAINT; } if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ zipfileTableErr(pTab, "rawdata must be NULL"); rc = SQLITE_CONSTRAINT; } if( rc==SQLITE_OK ){ if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ /* data=NULL. A directory */ bIsDir = 1; }else{ /* Value specified for "data", and possibly "method". This must be ** a regular file or a symlink. */ const u8 *aIn = sqlite3_value_blob(apVal[7]); int nIn = sqlite3_value_bytes(apVal[7]); int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; iMethod = sqlite3_value_int(apVal[8]); sz = nIn; pData = aIn; nData = nIn; if( iMethod!=0 && iMethod!=8 ){ zipfileTableErr(pTab, "unknown compression method: %d", iMethod); rc = SQLITE_CONSTRAINT; }else{ if( bAuto || iMethod ){ int nCmp; rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); if( rc==SQLITE_OK ){ if( iMethod || nCmp<nIn ){ iMethod = 8; pData = pFree; nData = nCmp; } } } iCrc32 = crc32(0, aIn, nIn); } } } if( rc==SQLITE_OK ){ rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg); } if( rc==SQLITE_OK ){ zPath = (const char*)sqlite3_value_text(apVal[2]); nPath = (int)strlen(zPath); mTime = zipfileGetTime(apVal[4]); } if( rc==SQLITE_OK && bIsDir ){ /* For a directory, check that the last character in the path is a ** '/'. This appears to be required for compatibility with info-zip ** (the unzip command on unix). It does not create directories ** otherwise. */ if( zPath[nPath-1]!='/' ){ zFree = sqlite3_mprintf("%s/", zPath); if( zFree==0 ){ rc = SQLITE_NOMEM; } zPath = (const char*)zFree; nPath++; } } /* Check that we're not inserting a duplicate entry -OR- updating an ** entry with a path, thereby making it into a duplicate. */ if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ ZipfileEntry *p; for(p=pTab->pFirstEntry; p; p=p->pNext){ if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ switch( sqlite3_vtab_on_conflict(pTab->db) ){ case SQLITE_IGNORE: { goto zipfile_update_done; } case SQLITE_REPLACE: { pOld2 = p; break; } default: { zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath); rc = SQLITE_CONSTRAINT; break; } } break; } } } if( rc==SQLITE_OK ){ /* Create the new CDS record. */ pNew = zipfileNewEntry(zPath); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; pNew->cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&pNew->cds, mTime); pNew->cds.crc32 = iCrc32; pNew->cds.szCompressed = nData; pNew->cds.szUncompressed = (u32)sz; pNew->cds.iExternalAttr = (mode<<16); pNew->cds.iOffset = (u32)pTab->szCurrent; pNew->cds.nFile = (u16)nPath; pNew->mUnixTime = (u32)mTime; rc = zipfileAppendEntry(pTab, pNew, pData, nData); zipfileAddEntry(pTab, pOld, pNew); } } } if( rc==SQLITE_OK && (pOld || pOld2) ){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ pCsr->pCurrent = pCsr->pCurrent->pNext; pCsr->bNoop = 1; } } zipfileRemoveEntryFromList(pTab, pOld); zipfileRemoveEntryFromList(pTab, pOld2); } zipfile_update_done: sqlite3_free(pFree); sqlite3_free(zFree); return rc; } static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){ u8 *a = aBuf; zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD); zipfileWrite16(a, p->iDisk); zipfileWrite16(a, p->iFirstDisk); zipfileWrite16(a, p->nEntry); zipfileWrite16(a, p->nEntryTotal); zipfileWrite32(a, p->nSize); zipfileWrite32(a, p->iOffset); zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/ return a-aBuf; } static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){ int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); assert( nBuf==ZIPFILE_EOCD_FIXED_SZ ); return zipfileAppendData(pTab, pTab->aBuffer, nBuf); } /* ** Serialize the CDS structure into buffer aBuf[]. Return the number ** of bytes written. */ static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){ u8 *a = aBuf; ZipfileCDS *pCDS = &pEntry->cds; if( pEntry->aExtra==0 ){ pCDS->nExtra = 9; } zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS); zipfileWrite16(a, pCDS->iVersionMadeBy); zipfileWrite16(a, pCDS->iVersionExtract); zipfileWrite16(a, pCDS->flags); zipfileWrite16(a, pCDS->iCompression); zipfileWrite16(a, pCDS->mTime); zipfileWrite16(a, pCDS->mDate); zipfileWrite32(a, pCDS->crc32); zipfileWrite32(a, pCDS->szCompressed); zipfileWrite32(a, pCDS->szUncompressed); assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); zipfileWrite16(a, pCDS->nFile); zipfileWrite16(a, pCDS->nExtra); zipfileWrite16(a, pCDS->nComment); zipfileWrite16(a, pCDS->iDiskStart); zipfileWrite16(a, pCDS->iInternalAttr); zipfileWrite32(a, pCDS->iExternalAttr); zipfileWrite32(a, pCDS->iOffset); memcpy(a, pCDS->zFile, pCDS->nFile); a += pCDS->nFile; if( pEntry->aExtra ){ int n = (int)pCDS->nExtra + (int)pCDS->nComment; memcpy(a, pEntry->aExtra, n); a += n; }else{ assert( pCDS->nExtra==9 ); zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); zipfileWrite16(a, 5); *a++ = 0x01; zipfileWrite32(a, pEntry->mUnixTime); } return a-aBuf; } static int zipfileCommit(sqlite3_vtab *pVtab){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; if( pTab->pWriteFd ){ i64 iOffset = pTab->szCurrent; ZipfileEntry *p; ZipfileEOCD eocd; int nEntry = 0; /* Write out all entries */ for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ int n = zipfileSerializeCDS(p, pTab->aBuffer); rc = zipfileAppendData(pTab, pTab->aBuffer, n); nEntry++; } /* Write out the EOCD record */ eocd.iDisk = 0; eocd.iFirstDisk = 0; eocd.nEntry = (u16)nEntry; eocd.nEntryTotal = (u16)nEntry; eocd.nSize = (u32)(pTab->szCurrent - iOffset); eocd.iOffset = (u32)iOffset; rc = zipfileAppendEOCD(pTab, &eocd); zipfileCleanupTransaction(pTab); } return rc; } static int zipfileRollback(sqlite3_vtab *pVtab){ return zipfileCommit(pVtab); } static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( iId==pCsr->iId ) break; } return pCsr; } static void zipfileFunctionCds( sqlite3_context *context, int argc, sqlite3_value **argv ){ ZipfileCsr *pCsr; ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context); assert( argc>0 ); pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0])); if( pCsr ){ ZipfileCDS *p = &pCsr->pCurrent->cds; char *zRes = sqlite3_mprintf("{" "\"version-made-by\" : %u, " "\"version-to-extract\" : %u, " "\"flags\" : %u, " "\"compression\" : %u, " "\"time\" : %u, " "\"date\" : %u, " "\"crc32\" : %u, " "\"compressed-size\" : %u, " "\"uncompressed-size\" : %u, " "\"file-name-length\" : %u, " "\"extra-field-length\" : %u, " "\"file-comment-length\" : %u, " "\"disk-number-start\" : %u, " "\"internal-attr\" : %u, " "\"external-attr\" : %u, " "\"offset\" : %u }", (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, (u32)p->flags, (u32)p->iCompression, (u32)p->mTime, (u32)p->mDate, (u32)p->crc32, (u32)p->szCompressed, (u32)p->szUncompressed, (u32)p->nFile, (u32)p->nExtra, (u32)p->nComment, (u32)p->iDiskStart, (u32)p->iInternalAttr, (u32)p->iExternalAttr, (u32)p->iOffset ); if( zRes==0 ){ sqlite3_result_error_nomem(context); }else{ sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); sqlite3_free(zRes); } } } /* ** xFindFunction method. */ static int zipfileFindFunction( sqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Number of SQL function arguments */ const char *zName, /* Name of SQL function */ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ void **ppArg /* OUT: User data for *pxFunc */ ){ if( sqlite3_stricmp("zipfile_cds", zName)==0 ){ *pxFunc = zipfileFunctionCds; *ppArg = (void*)pVtab; return 1; } return 0; } typedef struct ZipfileBuffer ZipfileBuffer; struct ZipfileBuffer { u8 *a; /* Pointer to buffer */ int n; /* Size of buffer in bytes */ int nAlloc; /* Byte allocated at a[] */ }; typedef struct ZipfileCtx ZipfileCtx; struct ZipfileCtx { int nEntry; ZipfileBuffer body; ZipfileBuffer cds; }; static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){ if( pBuf->n+nByte>pBuf->nAlloc ){ u8 *aNew; int nNew = pBuf->n ? pBuf->n*2 : 512; int nReq = pBuf->n + nByte; while( nNew<nReq ) nNew = nNew*2; aNew = sqlite3_realloc(pBuf->a, nNew); if( aNew==0 ) return SQLITE_NOMEM; pBuf->a = aNew; pBuf->nAlloc = nNew; } return SQLITE_OK; } /* ** xStep() callback for the zipfile() aggregate. This can be called in ** any of the following ways: ** ** SELECT zipfile(name,data) ... ** SELECT zipfile(name,mode,mtime,data) ... ** SELECT zipfile(name,mode,mtime,data,method) ... */ void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){ ZipfileCtx *p; /* Aggregate function context */ ZipfileEntry e; /* New entry to add to zip archive */ sqlite3_value *pName = 0; sqlite3_value *pMode = 0; sqlite3_value *pMtime = 0; sqlite3_value *pData = 0; sqlite3_value *pMethod = 0; int bIsDir = 0; u32 mode; int rc = SQLITE_OK; char *zErr = 0; int iMethod = -1; /* Compression method to use (0 or 8) */ const u8 *aData = 0; /* Possibly compressed data for new entry */ int nData = 0; /* Size of aData[] in bytes */ int szUncompressed = 0; /* Size of data before compression */ u8 *aFree = 0; /* Free this before returning */ u32 iCrc32 = 0; /* crc32 of uncompressed data */ char *zName = 0; /* Path (name) of new entry */ int nName = 0; /* Size of zName in bytes */ char *zFree = 0; /* Free this before returning */ int nByte; memset(&e, 0, sizeof(e)); p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); if( p==0 ) return; /* Martial the arguments into stack variables */ if( nVal!=2 && nVal!=4 && nVal!=5 ){ zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()"); rc = SQLITE_ERROR; goto zipfile_step_out; } pName = apVal[0]; if( nVal==2 ){ pData = apVal[1]; }else{ pMode = apVal[1]; pMtime = apVal[2]; pData = apVal[3]; if( nVal==5 ){ pMethod = apVal[4]; } } /* Check that the 'name' parameter looks ok. */ zName = (char*)sqlite3_value_text(pName); nName = sqlite3_value_bytes(pName); if( zName==0 ){ zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); rc = SQLITE_ERROR; goto zipfile_step_out; } /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use ** deflate compression) or NULL (choose automatically). */ if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){ iMethod = (int)sqlite3_value_int64(pMethod); if( iMethod!=0 && iMethod!=8 ){ zErr = sqlite3_mprintf("illegal method value: %d", iMethod); rc = SQLITE_ERROR; goto zipfile_step_out; } } /* Now inspect the data. If this is NULL, then the new entry must be a ** directory. Otherwise, figure out whether or not the data should ** be deflated or simply stored in the zip archive. */ if( sqlite3_value_type(pData)==SQLITE_NULL ){ bIsDir = 1; iMethod = 0; }else{ aData = sqlite3_value_blob(pData); szUncompressed = nData = sqlite3_value_bytes(pData); iCrc32 = crc32(0, aData, nData); if( iMethod<0 || iMethod==8 ){ int nOut = 0; rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr); if( rc!=SQLITE_OK ){ goto zipfile_step_out; } if( iMethod==8 || nOut<nData ){ aData = aFree; nData = nOut; iMethod = 8; }else{ iMethod = 0; } } } /* Decode the "mode" argument. */ rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr); if( rc ) goto zipfile_step_out; /* Decode the "mtime" argument. */ e.mUnixTime = zipfileGetTime(pMtime); /* If this is a directory entry, ensure that there is exactly one '/' ** at the end of the path. Or, if this is not a directory and the path ** ends in '/' it is an error. */ if( bIsDir==0 ){ if( zName[nName-1]=='/' ){ zErr = sqlite3_mprintf("non-directory name must not end with /"); rc = SQLITE_ERROR; goto zipfile_step_out; } }else{ if( zName[nName-1]!='/' ){ zName = zFree = sqlite3_mprintf("%s/", zName); nName++; if( zName==0 ){ rc = SQLITE_NOMEM; goto zipfile_step_out; } }else{ while( nName>1 && zName[nName-2]=='/' ) nName--; } } /* Assemble the ZipfileEntry object for the new zip archive entry */ e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; e.cds.flags = ZIPFILE_NEWENTRY_FLAGS; e.cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime); e.cds.crc32 = iCrc32; e.cds.szCompressed = nData; e.cds.szUncompressed = szUncompressed; e.cds.iExternalAttr = (mode<<16); e.cds.iOffset = p->body.n; e.cds.nFile = (u16)nName; e.cds.zFile = zName; /* Append the LFH to the body of the new archive */ nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9; if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); /* Append the data to the body of the new archive */ if( nData>0 ){ if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; memcpy(&p->body.a[p->body.n], aData, nData); p->body.n += nData; } /* Append the CDS record to the directory of the new archive */ nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9; if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); /* Increment the count of entries in the archive */ p->nEntry++; zipfile_step_out: sqlite3_free(aFree); sqlite3_free(zFree); if( rc ){ if( zErr ){ sqlite3_result_error(pCtx, zErr, -1); }else{ sqlite3_result_error_code(pCtx, rc); } } sqlite3_free(zErr); } /* ** xFinalize() callback for zipfile aggregate function. */ void zipfileFinal(sqlite3_context *pCtx){ ZipfileCtx *p; ZipfileEOCD eocd; int nZip; u8 *aZip; p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); if( p==0 ) return; if( p->nEntry>0 ){ memset(&eocd, 0, sizeof(eocd)); eocd.nEntry = (u16)p->nEntry; eocd.nEntryTotal = (u16)p->nEntry; eocd.nSize = p->cds.n; eocd.iOffset = p->body.n; nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; aZip = (u8*)sqlite3_malloc(nZip); if( aZip==0 ){ sqlite3_result_error_nomem(pCtx); }else{ memcpy(aZip, p->body.a, p->body.n); memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); sqlite3_result_blob(pCtx, aZip, nZip, zipfileFree); } } sqlite3_free(p->body.a); sqlite3_free(p->cds.a); } /* ** Register the "zipfile" virtual table. */ static int zipfileRegister(sqlite3 *db){ static sqlite3_module zipfileModule = { 1, /* iVersion */ zipfileConnect, /* xCreate */ zipfileConnect, /* xConnect */ zipfileBestIndex, /* xBestIndex */ zipfileDisconnect, /* xDisconnect */ zipfileDisconnect, /* xDestroy */ zipfileOpen, /* xOpen - open a cursor */ zipfileClose, /* xClose - close a cursor */ zipfileFilter, /* xFilter - configure scan constraints */ zipfileNext, /* xNext - advance a cursor */ zipfileEof, /* xEof - check for end of scan */ zipfileColumn, /* xColumn - read data */ 0, /* xRowid - read data */ zipfileUpdate, /* xUpdate */ zipfileBegin, /* xBegin */ 0, /* xSync */ zipfileCommit, /* xCommit */ zipfileRollback, /* xRollback */ zipfileFindFunction, /* xFindMethod */ 0, /* xRename */ }; int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0); if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, zipfileStep, zipfileFinal ); } return rc; } #else /* SQLITE_OMIT_VIRTUALTABLE */ # define zipfileRegister(x) SQLITE_OK #endif #ifdef _WIN32 #endif int sqlite3_zipfile_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ return zipfileRegister(db); } /************************* End ../ext/misc/zipfile.c ********************/ /************************* Begin ../ext/misc/sqlar.c ******************/ /* ** 2017-12-17 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful ** for working with sqlar archives and used by the shell tool's built-in ** sqlar support. */ SQLITE_EXTENSION_INIT1 #include <zlib.h> /* ** Implementation of the "sqlar_compress(X)" SQL function. ** ** If the type of X is SQLITE_BLOB, and compressing that blob using ** zlib utility function compress() yields a smaller blob, return the ** compressed blob. Otherwise, return a copy of X. ** ** SQLar uses the "zlib format" for compressed content. The zlib format ** contains a two-byte identification header and a four-byte checksum at ** the end. This is different from ZIP which uses the raw deflate format. ** ** Future enhancements to SQLar might add support for new compression formats. ** If so, those new formats will be identified by alternative headers in the ** compressed data. */ static void sqlarCompressFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ assert( argc==1 ); if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ const Bytef *pData = sqlite3_value_blob(argv[0]); uLong nData = sqlite3_value_bytes(argv[0]); uLongf nOut = compressBound(nData); Bytef *pOut; pOut = (Bytef*)sqlite3_malloc(nOut); if( pOut==0 ){ sqlite3_result_error_nomem(context); return; }else{ if( Z_OK!=compress(pOut, &nOut, pData, nData) ){ sqlite3_result_error(context, "error in compress()", -1); }else if( nOut<nData ){ sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT); }else{ sqlite3_result_value(context, argv[0]); } sqlite3_free(pOut); } }else{ sqlite3_result_value(context, argv[0]); } } /* ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function ** ** Parameter SZ is interpreted as an integer. If it is less than or ** equal to zero, then this function returns a copy of X. Or, if ** SZ is equal to the size of X when interpreted as a blob, also ** return a copy of X. Otherwise, decompress blob X using zlib ** utility function uncompress() and return the results (another ** blob). */ static void sqlarUncompressFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ uLong nData; uLongf sz; assert( argc==2 ); sz = sqlite3_value_int(argv[1]); if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){ sqlite3_result_value(context, argv[0]); }else{ const Bytef *pData= sqlite3_value_blob(argv[0]); Bytef *pOut = sqlite3_malloc(sz); if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){ sqlite3_result_error(context, "error in uncompress()", -1); }else{ sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT); } sqlite3_free(pOut); } } #ifdef _WIN32 #endif int sqlite3_sqlar_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ rc = sqlite3_create_function(db, "sqlar_compress", 1, SQLITE_UTF8, 0, sqlarCompressFunc, 0, 0); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "sqlar_uncompress", 2, SQLITE_UTF8, 0, sqlarUncompressFunc, 0, 0); } return rc; } /************************* End ../ext/misc/sqlar.c ********************/ #endif /************************* Begin ../ext/expert/sqlite3expert.h ******************/ /* ** 2017 April 07 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* */ typedef struct sqlite3expert sqlite3expert; /* ** Create a new sqlite3expert object. ** ** If successful, a pointer to the new object is returned and (*pzErr) set ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to ** an English-language error message. In this case it is the responsibility ** of the caller to eventually free the error message buffer using ** sqlite3_free(). */ sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr); /* ** Configure an sqlite3expert object. ** ** EXPERT_CONFIG_SAMPLE: ** By default, sqlite3_expert_analyze() generates sqlite_stat1 data for ** each candidate index. This involves scanning and sorting the entire ** contents of each user database table once for each candidate index ** associated with the table. For large databases, this can be ** prohibitively slow. This option allows the sqlite3expert object to ** be configured so that sqlite_stat1 data is instead generated based on a ** subset of each table, or so that no sqlite_stat1 data is used at all. ** ** A single integer argument is passed to this option. If the value is less ** than or equal to zero, then no sqlite_stat1 data is generated or used by ** the analysis - indexes are recommended based on the database schema only. ** Or, if the value is 100 or greater, complete sqlite_stat1 data is ** generated for each candidate index (this is the default). Finally, if the ** value falls between 0 and 100, then it represents the percentage of user ** table rows that should be considered when generating sqlite_stat1 data. ** ** Examples: ** ** // Do not generate any sqlite_stat1 data ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0); ** ** // Generate sqlite_stat1 data based on 10% of the rows in each table. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10); */ int sqlite3_expert_config(sqlite3expert *p, int op, ...); #define EXPERT_CONFIG_SAMPLE 1 /* int */ /* ** Specify zero or more SQL statements to be included in the analysis. ** ** Buffer zSql must contain zero or more complete SQL statements. This ** function parses all statements contained in the buffer and adds them ** to the internal list of statements to analyze. If successful, SQLITE_OK ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example ** due to a error in the SQL - an SQLite error code is returned and (*pzErr) ** may be set to point to an English language error message. In this case ** the caller is responsible for eventually freeing the error message buffer ** using sqlite3_free(). ** ** If an error does occur while processing one of the statements in the ** buffer passed as the second argument, none of the statements in the ** buffer are added to the analysis. ** ** This function must be called before sqlite3_expert_analyze(). If a call ** to this function is made on an sqlite3expert object that has already ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned ** immediately and no statements are added to the analysis. */ int sqlite3_expert_sql( sqlite3expert *p, /* From a successful sqlite3_expert_new() */ const char *zSql, /* SQL statement(s) to add */ char **pzErr /* OUT: Error message (if any) */ ); /* ** This function is called after the sqlite3expert object has been configured ** with all SQL statements using sqlite3_expert_sql() to actually perform ** the analysis. Once this function has been called, it is not possible to ** add further SQL statements to the analysis. ** ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if ** an error occurs, an SQLite error code is returned and (*pzErr) set to ** point to a buffer containing an English language error message. In this ** case it is the responsibility of the caller to eventually free the buffer ** using sqlite3_free(). ** ** If an error does occur within this function, the sqlite3expert object ** is no longer useful for any purpose. At that point it is no longer ** possible to add further SQL statements to the object or to re-attempt ** the analysis. The sqlite3expert object must still be freed using a call ** sqlite3_expert_destroy(). */ int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr); /* ** Return the total number of statements loaded using sqlite3_expert_sql(). ** The total number of SQL statements may be different from the total number ** to calls to sqlite3_expert_sql(). */ int sqlite3_expert_count(sqlite3expert*); /* ** Return a component of the report. ** ** This function is called after sqlite3_expert_analyze() to extract the ** results of the analysis. Each call to this function returns either a ** NULL pointer or a pointer to a buffer containing a nul-terminated string. ** The value passed as the third argument must be one of the EXPERT_REPORT_* ** #define constants defined below. ** ** For some EXPERT_REPORT_* parameters, the buffer returned contains ** information relating to a specific SQL statement. In these cases that ** SQL statement is identified by the value passed as the second argument. ** SQL statements are numbered from 0 in the order in which they are parsed. ** If an out-of-range value (less than zero or equal to or greater than the ** value returned by sqlite3_expert_count()) is passed as the second argument ** along with such an EXPERT_REPORT_* parameter, NULL is always returned. ** ** EXPERT_REPORT_SQL: ** Return the text of SQL statement iStmt. ** ** EXPERT_REPORT_INDEXES: ** Return a buffer containing the CREATE INDEX statements for all recommended ** indexes for statement iStmt. If there are no new recommeded indexes, NULL ** is returned. ** ** EXPERT_REPORT_PLAN: ** Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query ** iStmt after the proposed indexes have been added to the database schema. ** ** EXPERT_REPORT_CANDIDATES: ** Return a pointer to a buffer containing the CREATE INDEX statements ** for all indexes that were tested (for all SQL statements). The iStmt ** parameter is ignored for EXPERT_REPORT_CANDIDATES calls. */ const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport); /* ** Values for the third argument passed to sqlite3_expert_report(). */ #define EXPERT_REPORT_SQL 1 #define EXPERT_REPORT_INDEXES 2 #define EXPERT_REPORT_PLAN 3 #define EXPERT_REPORT_CANDIDATES 4 /* ** Free an (sqlite3expert*) handle and all associated resources. There ** should be one call to this function for each successful call to ** sqlite3-expert_new(). */ void sqlite3_expert_destroy(sqlite3expert*); /************************* End ../ext/expert/sqlite3expert.h ********************/ /************************* Begin ../ext/expert/sqlite3expert.c ******************/ /* ** 2017 April 09 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* */ #include <assert.h> #include <string.h> #include <stdio.h> #ifndef SQLITE_OMIT_VIRTUALTABLE /* typedef sqlite3_int64 i64; */ /* typedef sqlite3_uint64 u64; */ typedef struct IdxColumn IdxColumn; typedef struct IdxConstraint IdxConstraint; typedef struct IdxScan IdxScan; typedef struct IdxStatement IdxStatement; typedef struct IdxTable IdxTable; typedef struct IdxWrite IdxWrite; #define STRLEN (int)strlen /* ** A temp table name that we assume no user database will actually use. ** If this assumption proves incorrect triggers on the table with the ** conflicting name will be ignored. */ #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776" /* ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or ** any other type of single-ended range constraint on a column). ** ** pLink: ** Used to temporarily link IdxConstraint objects into lists while ** creating candidate indexes. */ struct IdxConstraint { char *zColl; /* Collation sequence */ int bRange; /* True for range, false for eq */ int iCol; /* Constrained table column */ int bFlag; /* Used by idxFindCompatible() */ int bDesc; /* True if ORDER BY <expr> DESC */ IdxConstraint *pNext; /* Next constraint in pEq or pRange list */ IdxConstraint *pLink; /* See above */ }; /* ** A single scan of a single table. */ struct IdxScan { IdxTable *pTab; /* Associated table object */ int iDb; /* Database containing table zTable */ i64 covering; /* Mask of columns required for cov. index */ IdxConstraint *pOrder; /* ORDER BY columns */ IdxConstraint *pEq; /* List of == constraints */ IdxConstraint *pRange; /* List of < constraints */ IdxScan *pNextScan; /* Next IdxScan object for same analysis */ }; /* ** Information regarding a single database table. Extracted from ** "PRAGMA table_info" by function idxGetTableInfo(). */ struct IdxColumn { char *zName; char *zColl; int iPk; }; struct IdxTable { int nCol; char *zName; /* Table name */ IdxColumn *aCol; IdxTable *pNext; /* Next table in linked list of all tables */ }; /* ** An object of the following type is created for each unique table/write-op ** seen. The objects are stored in a singly-linked list beginning at ** sqlite3expert.pWrite. */ struct IdxWrite { IdxTable *pTab; int eOp; /* SQLITE_UPDATE, DELETE or INSERT */ IdxWrite *pNext; }; /* ** Each statement being analyzed is represented by an instance of this ** structure. */ struct IdxStatement { int iId; /* Statement number */ char *zSql; /* SQL statement */ char *zIdx; /* Indexes */ char *zEQP; /* Plan */ IdxStatement *pNext; }; /* ** A hash table for storing strings. With space for a payload string ** with each entry. Methods are: ** ** idxHashInit() ** idxHashClear() ** idxHashAdd() ** idxHashSearch() */ #define IDX_HASH_SIZE 1023 typedef struct IdxHashEntry IdxHashEntry; typedef struct IdxHash IdxHash; struct IdxHashEntry { char *zKey; /* nul-terminated key */ char *zVal; /* nul-terminated value string */ char *zVal2; /* nul-terminated value string 2 */ IdxHashEntry *pHashNext; /* Next entry in same hash bucket */ IdxHashEntry *pNext; /* Next entry in hash */ }; struct IdxHash { IdxHashEntry *pFirst; IdxHashEntry *aHash[IDX_HASH_SIZE]; }; /* ** sqlite3expert object. */ struct sqlite3expert { int iSample; /* Percentage of tables to sample for stat1 */ sqlite3 *db; /* User database */ sqlite3 *dbm; /* In-memory db for this analysis */ sqlite3 *dbv; /* Vtab schema for this analysis */ IdxTable *pTable; /* List of all IdxTable objects */ IdxScan *pScan; /* List of scan objects */ IdxWrite *pWrite; /* List of write objects */ IdxStatement *pStatement; /* List of IdxStatement objects */ int bRun; /* True once analysis has run */ char **pzErrmsg; int rc; /* Error code from whereinfo hook */ IdxHash hIdx; /* Hash containing all candidate indexes */ char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */ }; /* ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL. */ static void *idxMalloc(int *pRc, int nByte){ void *pRet; assert( *pRc==SQLITE_OK ); assert( nByte>0 ); pRet = sqlite3_malloc(nByte); if( pRet ){ memset(pRet, 0, nByte); }else{ *pRc = SQLITE_NOMEM; } return pRet; } /* ** Initialize an IdxHash hash table. */ static void idxHashInit(IdxHash *pHash){ memset(pHash, 0, sizeof(IdxHash)); } /* ** Reset an IdxHash hash table. */ static void idxHashClear(IdxHash *pHash){ int i; for(i=0; i<IDX_HASH_SIZE; i++){ IdxHashEntry *pEntry; IdxHashEntry *pNext; for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){ pNext = pEntry->pHashNext; sqlite3_free(pEntry->zVal2); sqlite3_free(pEntry); } } memset(pHash, 0, sizeof(IdxHash)); } /* ** Return the index of the hash bucket that the string specified by the ** arguments to this function belongs. */ static int idxHashString(const char *z, int n){ unsigned int ret = 0; int i; for(i=0; i<n; i++){ ret += (ret<<3) + (unsigned char)(z[i]); } return (int)(ret % IDX_HASH_SIZE); } /* ** If zKey is already present in the hash table, return non-zero and do ** nothing. Otherwise, add an entry with key zKey and payload string zVal to ** the hash table passed as the second argument. */ static int idxHashAdd( int *pRc, IdxHash *pHash, const char *zKey, const char *zVal ){ int nKey = STRLEN(zKey); int iHash = idxHashString(zKey, nKey); int nVal = (zVal ? STRLEN(zVal) : 0); IdxHashEntry *pEntry; assert( iHash>=0 ); for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ return 1; } } pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1); if( pEntry ){ pEntry->zKey = (char*)&pEntry[1]; memcpy(pEntry->zKey, zKey, nKey); if( zVal ){ pEntry->zVal = &pEntry->zKey[nKey+1]; memcpy(pEntry->zVal, zVal, nVal); } pEntry->pHashNext = pHash->aHash[iHash]; pHash->aHash[iHash] = pEntry; pEntry->pNext = pHash->pFirst; pHash->pFirst = pEntry; } return 0; } /* ** If zKey/nKey is present in the hash table, return a pointer to the ** hash-entry object. */ static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){ int iHash; IdxHashEntry *pEntry; if( nKey<0 ) nKey = STRLEN(zKey); iHash = idxHashString(zKey, nKey); assert( iHash>=0 ); for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ return pEntry; } } return 0; } /* ** If the hash table contains an entry with a key equal to the string ** passed as the final two arguments to this function, return a pointer ** to the payload string. Otherwise, if zKey/nKey is not present in the ** hash table, return NULL. */ static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){ IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey); if( pEntry ) return pEntry->zVal; return 0; } /* ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl ** variable to point to a copy of nul-terminated string zColl. */ static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){ IdxConstraint *pNew; int nColl = STRLEN(zColl); assert( *pRc==SQLITE_OK ); pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1); if( pNew ){ pNew->zColl = (char*)&pNew[1]; memcpy(pNew->zColl, zColl, nColl+1); } return pNew; } /* ** An error associated with database handle db has just occurred. Pass ** the error message to callback function xOut. */ static void idxDatabaseError( sqlite3 *db, /* Database handle */ char **pzErrmsg /* Write error here */ ){ *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); } /* ** Prepare an SQL statement. */ static int idxPrepareStmt( sqlite3 *db, /* Database handle to compile against */ sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */ char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */ const char *zSql /* SQL statement to compile */ ){ int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); if( rc!=SQLITE_OK ){ *ppStmt = 0; idxDatabaseError(db, pzErrmsg); } return rc; } /* ** Prepare an SQL statement using the results of a printf() formatting. */ static int idxPrintfPrepareStmt( sqlite3 *db, /* Database handle to compile against */ sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */ char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */ const char *zFmt, /* printf() format of SQL statement */ ... /* Trailing printf() arguments */ ){ va_list ap; int rc; char *zSql; va_start(ap, zFmt); zSql = sqlite3_vmprintf(zFmt, ap); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql); sqlite3_free(zSql); } va_end(ap); return rc; } /************************************************************************* ** Beginning of virtual table implementation. */ typedef struct ExpertVtab ExpertVtab; struct ExpertVtab { sqlite3_vtab base; IdxTable *pTab; sqlite3expert *pExpert; }; typedef struct ExpertCsr ExpertCsr; struct ExpertCsr { sqlite3_vtab_cursor base; sqlite3_stmt *pData; }; static char *expertDequote(const char *zIn){ int n = STRLEN(zIn); char *zRet = sqlite3_malloc(n); assert( zIn[0]=='\'' ); assert( zIn[n-1]=='\'' ); if( zRet ){ int iOut = 0; int iIn = 0; for(iIn=1; iIn<(n-1); iIn++){ if( zIn[iIn]=='\'' ){ assert( zIn[iIn+1]=='\'' ); iIn++; } zRet[iOut++] = zIn[iIn]; } zRet[iOut] = '\0'; } return zRet; } /* ** This function is the implementation of both the xConnect and xCreate ** methods of the r-tree virtual table. ** ** argv[0] -> module name ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> column names... */ static int expertConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ sqlite3expert *pExpert = (sqlite3expert*)pAux; ExpertVtab *p = 0; int rc; if( argc!=4 ){ *pzErr = sqlite3_mprintf("internal error!"); rc = SQLITE_ERROR; }else{ char *zCreateTable = expertDequote(argv[3]); if( zCreateTable ){ rc = sqlite3_declare_vtab(db, zCreateTable); if( rc==SQLITE_OK ){ p = idxMalloc(&rc, sizeof(ExpertVtab)); } if( rc==SQLITE_OK ){ p->pExpert = pExpert; p->pTab = pExpert->pTable; assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 ); } sqlite3_free(zCreateTable); }else{ rc = SQLITE_NOMEM; } } *ppVtab = (sqlite3_vtab*)p; return rc; } static int expertDisconnect(sqlite3_vtab *pVtab){ ExpertVtab *p = (ExpertVtab*)pVtab; sqlite3_free(p); return SQLITE_OK; } static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){ ExpertVtab *p = (ExpertVtab*)pVtab; int rc = SQLITE_OK; int n = 0; IdxScan *pScan; const int opmask = SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT | SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE | SQLITE_INDEX_CONSTRAINT_LE; pScan = idxMalloc(&rc, sizeof(IdxScan)); if( pScan ){ int i; /* Link the new scan object into the list */ pScan->pTab = p->pTab; pScan->pNextScan = p->pExpert->pScan; p->pExpert->pScan = pScan; /* Add the constraints to the IdxScan object */ for(i=0; i<pIdxInfo->nConstraint; i++){ struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; if( pCons->usable && pCons->iColumn>=0 && p->pTab->aCol[pCons->iColumn].iPk==0 && (pCons->op & opmask) ){ IdxConstraint *pNew; const char *zColl = sqlite3_vtab_collation(pIdxInfo, i); pNew = idxNewConstraint(&rc, zColl); if( pNew ){ pNew->iCol = pCons->iColumn; if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ pNew->pNext = pScan->pEq; pScan->pEq = pNew; }else{ pNew->bRange = 1; pNew->pNext = pScan->pRange; pScan->pRange = pNew; } } n++; pIdxInfo->aConstraintUsage[i].argvIndex = n; } } /* Add the ORDER BY to the IdxScan object */ for(i=pIdxInfo->nOrderBy-1; i>=0; i--){ int iCol = pIdxInfo->aOrderBy[i].iColumn; if( iCol>=0 ){ IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl); if( pNew ){ pNew->iCol = iCol; pNew->bDesc = pIdxInfo->aOrderBy[i].desc; pNew->pNext = pScan->pOrder; pNew->pLink = pScan->pOrder; pScan->pOrder = pNew; n++; } } } } pIdxInfo->estimatedCost = 1000000.0 / (n+1); return rc; } static int expertUpdate( sqlite3_vtab *pVtab, int nData, sqlite3_value **azData, sqlite_int64 *pRowid ){ (void)pVtab; (void)nData; (void)azData; (void)pRowid; return SQLITE_OK; } /* ** Virtual table module xOpen method. */ static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ int rc = SQLITE_OK; ExpertCsr *pCsr; (void)pVTab; pCsr = idxMalloc(&rc, sizeof(ExpertCsr)); *ppCursor = (sqlite3_vtab_cursor*)pCsr; return rc; } /* ** Virtual table module xClose method. */ static int expertClose(sqlite3_vtab_cursor *cur){ ExpertCsr *pCsr = (ExpertCsr*)cur; sqlite3_finalize(pCsr->pData); sqlite3_free(pCsr); return SQLITE_OK; } /* ** Virtual table module xEof method. ** ** Return non-zero if the cursor does not currently point to a valid ** record (i.e if the scan has finished), or zero otherwise. */ static int expertEof(sqlite3_vtab_cursor *cur){ ExpertCsr *pCsr = (ExpertCsr*)cur; return pCsr->pData==0; } /* ** Virtual table module xNext method. */ static int expertNext(sqlite3_vtab_cursor *cur){ ExpertCsr *pCsr = (ExpertCsr*)cur; int rc = SQLITE_OK; assert( pCsr->pData ); rc = sqlite3_step(pCsr->pData); if( rc!=SQLITE_ROW ){ rc = sqlite3_finalize(pCsr->pData); pCsr->pData = 0; }else{ rc = SQLITE_OK; } return rc; } /* ** Virtual table module xRowid method. */ static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ (void)cur; *pRowid = 0; return SQLITE_OK; } /* ** Virtual table module xColumn method. */ static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ ExpertCsr *pCsr = (ExpertCsr*)cur; sqlite3_value *pVal; pVal = sqlite3_column_value(pCsr->pData, i); if( pVal ){ sqlite3_result_value(ctx, pVal); } return SQLITE_OK; } /* ** Virtual table module xFilter method. */ static int expertFilter( sqlite3_vtab_cursor *cur, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ ExpertCsr *pCsr = (ExpertCsr*)cur; ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab); sqlite3expert *pExpert = pVtab->pExpert; int rc; (void)idxNum; (void)idxStr; (void)argc; (void)argv; rc = sqlite3_finalize(pCsr->pData); pCsr->pData = 0; if( rc==SQLITE_OK ){ rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg, "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName ); } if( rc==SQLITE_OK ){ rc = expertNext(cur); } return rc; } static int idxRegisterVtab(sqlite3expert *p){ static sqlite3_module expertModule = { 2, /* iVersion */ expertConnect, /* xCreate - create a table */ expertConnect, /* xConnect - connect to an existing table */ expertBestIndex, /* xBestIndex - Determine search strategy */ expertDisconnect, /* xDisconnect - Disconnect from a table */ expertDisconnect, /* xDestroy - Drop a table */ expertOpen, /* xOpen - open a cursor */ expertClose, /* xClose - close a cursor */ expertFilter, /* xFilter - configure scan constraints */ expertNext, /* xNext - advance a cursor */ expertEof, /* xEof */ expertColumn, /* xColumn - read data */ expertRowid, /* xRowid - read data */ expertUpdate, /* xUpdate - write data */ 0, /* xBegin - begin transaction */ 0, /* xSync - sync transaction */ 0, /* xCommit - commit transaction */ 0, /* xRollback - rollback transaction */ 0, /* xFindFunction - function overloading */ 0, /* xRename - rename the table */ 0, /* xSavepoint */ 0, /* xRelease */ 0, /* xRollbackTo */ }; return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p); } /* ** End of virtual table implementation. *************************************************************************/ /* ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function ** is called, set it to the return value of sqlite3_finalize() before ** returning. Otherwise, discard the sqlite3_finalize() return value. */ static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){ int rc = sqlite3_finalize(pStmt); if( *pRc==SQLITE_OK ) *pRc = rc; } /* ** Attempt to allocate an IdxTable structure corresponding to table zTab ** in the main database of connection db. If successful, set (*ppOut) to ** point to the new object and return SQLITE_OK. Otherwise, return an ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be ** set to point to an error string. ** ** It is the responsibility of the caller to eventually free either the ** IdxTable object or error message using sqlite3_free(). */ static int idxGetTableInfo( sqlite3 *db, /* Database connection to read details from */ const char *zTab, /* Table name */ IdxTable **ppOut, /* OUT: New object (if successful) */ char **pzErrmsg /* OUT: Error message (if not) */ ){ sqlite3_stmt *p1 = 0; int nCol = 0; int nTab = STRLEN(zTab); int nByte = sizeof(IdxTable) + nTab + 1; IdxTable *pNew = 0; int rc, rc2; char *pCsr = 0; rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab); while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){ const char *zCol = (const char*)sqlite3_column_text(p1, 1); nByte += 1 + STRLEN(zCol); rc = sqlite3_table_column_metadata( db, "main", zTab, zCol, 0, &zCol, 0, 0, 0 ); nByte += 1 + STRLEN(zCol); nCol++; } rc2 = sqlite3_reset(p1); if( rc==SQLITE_OK ) rc = rc2; nByte += sizeof(IdxColumn) * nCol; if( rc==SQLITE_OK ){ pNew = idxMalloc(&rc, nByte); } if( rc==SQLITE_OK ){ pNew->aCol = (IdxColumn*)&pNew[1]; pNew->nCol = nCol; pCsr = (char*)&pNew->aCol[nCol]; } nCol = 0; while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){ const char *zCol = (const char*)sqlite3_column_text(p1, 1); int nCopy = STRLEN(zCol) + 1; pNew->aCol[nCol].zName = pCsr; pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5); memcpy(pCsr, zCol, nCopy); pCsr += nCopy; rc = sqlite3_table_column_metadata( db, "main", zTab, zCol, 0, &zCol, 0, 0, 0 ); if( rc==SQLITE_OK ){ nCopy = STRLEN(zCol) + 1; pNew->aCol[nCol].zColl = pCsr; memcpy(pCsr, zCol, nCopy); pCsr += nCopy; } nCol++; } idxFinalize(&rc, p1); if( rc!=SQLITE_OK ){ sqlite3_free(pNew); pNew = 0; }else{ pNew->zName = pCsr; memcpy(pNew->zName, zTab, nTab+1); } *ppOut = pNew; return rc; } /* ** This function is a no-op if *pRc is set to anything other than ** SQLITE_OK when it is called. ** ** If *pRc is initially set to SQLITE_OK, then the text specified by ** the printf() style arguments is appended to zIn and the result returned ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on ** zIn before returning. */ static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){ va_list ap; char *zAppend = 0; char *zRet = 0; int nIn = zIn ? STRLEN(zIn) : 0; int nAppend = 0; va_start(ap, zFmt); if( *pRc==SQLITE_OK ){ zAppend = sqlite3_vmprintf(zFmt, ap); if( zAppend ){ nAppend = STRLEN(zAppend); zRet = (char*)sqlite3_malloc(nIn + nAppend + 1); } if( zAppend && zRet ){ if( nIn ) memcpy(zRet, zIn, nIn); memcpy(&zRet[nIn], zAppend, nAppend+1); }else{ sqlite3_free(zRet); zRet = 0; *pRc = SQLITE_NOMEM; } sqlite3_free(zAppend); sqlite3_free(zIn); } va_end(ap); return zRet; } /* ** Return true if zId must be quoted in order to use it as an SQL ** identifier, or false otherwise. */ static int idxIdentifierRequiresQuotes(const char *zId){ int i; for(i=0; zId[i]; i++){ if( !(zId[i]=='_') && !(zId[i]>='0' && zId[i]<='9') && !(zId[i]>='a' && zId[i]<='z') && !(zId[i]>='A' && zId[i]<='Z') ){ return 1; } } return 0; } /* ** This function appends an index column definition suitable for constraint ** pCons to the string passed as zIn and returns the result. */ static char *idxAppendColDefn( int *pRc, /* IN/OUT: Error code */ char *zIn, /* Column defn accumulated so far */ IdxTable *pTab, /* Table index will be created on */ IdxConstraint *pCons ){ char *zRet = zIn; IdxColumn *p = &pTab->aCol[pCons->iCol]; if( zRet ) zRet = idxAppendText(pRc, zRet, ", "); if( idxIdentifierRequiresQuotes(p->zName) ){ zRet = idxAppendText(pRc, zRet, "%Q", p->zName); }else{ zRet = idxAppendText(pRc, zRet, "%s", p->zName); } if( sqlite3_stricmp(p->zColl, pCons->zColl) ){ if( idxIdentifierRequiresQuotes(pCons->zColl) ){ zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl); }else{ zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl); } } if( pCons->bDesc ){ zRet = idxAppendText(pRc, zRet, " DESC"); } return zRet; } /* ** Search database dbm for an index compatible with the one idxCreateFromCons() ** would create from arguments pScan, pEq and pTail. If no error occurs and ** such an index is found, return non-zero. Or, if no such index is found, ** return zero. ** ** If an error occurs, set *pRc to an SQLite error code and return zero. */ static int idxFindCompatible( int *pRc, /* OUT: Error code */ sqlite3* dbm, /* Database to search */ IdxScan *pScan, /* Scan for table to search for index on */ IdxConstraint *pEq, /* List of == constraints */ IdxConstraint *pTail /* List of range constraints */ ){ const char *zTbl = pScan->pTab->zName; sqlite3_stmt *pIdxList = 0; IdxConstraint *pIter; int nEq = 0; /* Number of elements in pEq */ int rc; /* Count the elements in list pEq */ for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++; rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl); while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){ int bMatch = 1; IdxConstraint *pT = pTail; sqlite3_stmt *pInfo = 0; const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1); /* Zero the IdxConstraint.bFlag values in the pEq list */ for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0; rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx); while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){ int iIdx = sqlite3_column_int(pInfo, 0); int iCol = sqlite3_column_int(pInfo, 1); const char *zColl = (const char*)sqlite3_column_text(pInfo, 4); if( iIdx<nEq ){ for(pIter=pEq; pIter; pIter=pIter->pLink){ if( pIter->bFlag ) continue; if( pIter->iCol!=iCol ) continue; if( sqlite3_stricmp(pIter->zColl, zColl) ) continue; pIter->bFlag = 1; break; } if( pIter==0 ){ bMatch = 0; break; } }else{ if( pT ){ if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){ bMatch = 0; break; } pT = pT->pLink; } } } idxFinalize(&rc, pInfo); if( rc==SQLITE_OK && bMatch ){ sqlite3_finalize(pIdxList); return 1; } } idxFinalize(&rc, pIdxList); *pRc = rc; return 0; } static int idxCreateFromCons( sqlite3expert *p, IdxScan *pScan, IdxConstraint *pEq, IdxConstraint *pTail ){ sqlite3 *dbm = p->dbm; int rc = SQLITE_OK; if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){ IdxTable *pTab = pScan->pTab; char *zCols = 0; char *zIdx = 0; IdxConstraint *pCons; unsigned int h = 0; const char *zFmt; for(pCons=pEq; pCons; pCons=pCons->pLink){ zCols = idxAppendColDefn(&rc, zCols, pTab, pCons); } for(pCons=pTail; pCons; pCons=pCons->pLink){ zCols = idxAppendColDefn(&rc, zCols, pTab, pCons); } if( rc==SQLITE_OK ){ /* Hash the list of columns to come up with a name for the index */ const char *zTable = pScan->pTab->zName; char *zName; /* Index name */ int i; for(i=0; zCols[i]; i++){ h += ((h<<3) + zCols[i]); } zName = sqlite3_mprintf("%s_idx_%08x", zTable, h); if( zName==0 ){ rc = SQLITE_NOMEM; }else{ if( idxIdentifierRequiresQuotes(zTable) ){ zFmt = "CREATE INDEX '%q' ON %Q(%s)"; }else{ zFmt = "CREATE INDEX %s ON %s(%s)"; } zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols); if( !zIdx ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg); idxHashAdd(&rc, &p->hIdx, zName, zIdx); } sqlite3_free(zName); sqlite3_free(zIdx); } } sqlite3_free(zCols); } return rc; } /* ** Return true if list pList (linked by IdxConstraint.pLink) contains ** a constraint compatible with *p. Otherwise return false. */ static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){ IdxConstraint *pCmp; for(pCmp=pList; pCmp; pCmp=pCmp->pLink){ if( p->iCol==pCmp->iCol ) return 1; } return 0; } static int idxCreateFromWhere( sqlite3expert *p, IdxScan *pScan, /* Create indexes for this scan */ IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */ ){ IdxConstraint *p1 = 0; IdxConstraint *pCon; int rc; /* Gather up all the == constraints. */ for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){ if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){ pCon->pLink = p1; p1 = pCon; } } /* Create an index using the == constraints collected above. And the ** range constraint/ORDER BY terms passed in by the caller, if any. */ rc = idxCreateFromCons(p, pScan, p1, pTail); /* If no range/ORDER BY passed by the caller, create a version of the ** index for each range constraint. */ if( pTail==0 ){ for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){ assert( pCon->pLink==0 ); if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){ rc = idxCreateFromCons(p, pScan, p1, pCon); } } } return rc; } /* ** Create candidate indexes in database [dbm] based on the data in ** linked-list pScan. */ static int idxCreateCandidates(sqlite3expert *p){ int rc = SQLITE_OK; IdxScan *pIter; for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){ rc = idxCreateFromWhere(p, pIter, 0); if( rc==SQLITE_OK && pIter->pOrder ){ rc = idxCreateFromWhere(p, pIter, pIter->pOrder); } } return rc; } /* ** Free all elements of the linked list starting at pConstraint. */ static void idxConstraintFree(IdxConstraint *pConstraint){ IdxConstraint *pNext; IdxConstraint *p; for(p=pConstraint; p; p=pNext){ pNext = p->pNext; sqlite3_free(p); } } /* ** Free all elements of the linked list starting from pScan up until pLast ** (pLast is not freed). */ static void idxScanFree(IdxScan *pScan, IdxScan *pLast){ IdxScan *p; IdxScan *pNext; for(p=pScan; p!=pLast; p=pNext){ pNext = p->pNextScan; idxConstraintFree(p->pOrder); idxConstraintFree(p->pEq); idxConstraintFree(p->pRange); sqlite3_free(p); } } /* ** Free all elements of the linked list starting from pStatement up ** until pLast (pLast is not freed). */ static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){ IdxStatement *p; IdxStatement *pNext; for(p=pStatement; p!=pLast; p=pNext){ pNext = p->pNext; sqlite3_free(p->zEQP); sqlite3_free(p->zIdx); sqlite3_free(p); } } /* ** Free the linked list of IdxTable objects starting at pTab. */ static void idxTableFree(IdxTable *pTab){ IdxTable *pIter; IdxTable *pNext; for(pIter=pTab; pIter; pIter=pNext){ pNext = pIter->pNext; sqlite3_free(pIter); } } /* ** Free the linked list of IdxWrite objects starting at pTab. */ static void idxWriteFree(IdxWrite *pTab){ IdxWrite *pIter; IdxWrite *pNext; for(pIter=pTab; pIter; pIter=pNext){ pNext = pIter->pNext; sqlite3_free(pIter); } } /* ** This function is called after candidate indexes have been created. It ** runs all the queries to see which indexes they prefer, and populates ** IdxStatement.zIdx and IdxStatement.zEQP with the results. */ int idxFindIndexes( sqlite3expert *p, char **pzErr /* OUT: Error message (sqlite3_malloc) */ ){ IdxStatement *pStmt; sqlite3 *dbm = p->dbm; int rc = SQLITE_OK; IdxHash hIdx; idxHashInit(&hIdx); for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){ IdxHashEntry *pEntry; sqlite3_stmt *pExplain = 0; idxHashClear(&hIdx); rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr, "EXPLAIN QUERY PLAN %s", pStmt->zSql ); while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){ int iSelectid = sqlite3_column_int(pExplain, 0); int iOrder = sqlite3_column_int(pExplain, 1); int iFrom = sqlite3_column_int(pExplain, 2); const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3); int nDetail = STRLEN(zDetail); int i; for(i=0; i<nDetail; i++){ const char *zIdx = 0; if( memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){ zIdx = &zDetail[i+13]; }else if( memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 ){ zIdx = &zDetail[i+22]; } if( zIdx ){ const char *zSql; int nIdx = 0; while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){ nIdx++; } zSql = idxHashSearch(&p->hIdx, zIdx, nIdx); if( zSql ){ idxHashAdd(&rc, &hIdx, zSql, 0); if( rc ) goto find_indexes_out; } break; } } pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%d|%d|%d|%s\n", iSelectid, iOrder, iFrom, zDetail ); } for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey); } idxFinalize(&rc, pExplain); } find_indexes_out: idxHashClear(&hIdx); return rc; } static int idxAuthCallback( void *pCtx, int eOp, const char *z3, const char *z4, const char *zDb, const char *zTrigger ){ int rc = SQLITE_OK; (void)z4; (void)zTrigger; if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){ if( sqlite3_stricmp(zDb, "main")==0 ){ sqlite3expert *p = (sqlite3expert*)pCtx; IdxTable *pTab; for(pTab=p->pTable; pTab; pTab=pTab->pNext){ if( 0==sqlite3_stricmp(z3, pTab->zName) ) break; } if( pTab ){ IdxWrite *pWrite; for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){ if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break; } if( pWrite==0 ){ pWrite = idxMalloc(&rc, sizeof(IdxWrite)); if( rc==SQLITE_OK ){ pWrite->pTab = pTab; pWrite->eOp = eOp; pWrite->pNext = p->pWrite; p->pWrite = pWrite; } } } } } return rc; } static int idxProcessOneTrigger( sqlite3expert *p, IdxWrite *pWrite, char **pzErr ){ static const char *zInt = UNIQUE_TABLE_NAME; static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME; IdxTable *pTab = pWrite->pTab; const char *zTab = pTab->zName; const char *zSql = "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master " "WHERE tbl_name = %Q AND type IN ('table', 'trigger') " "ORDER BY type;"; sqlite3_stmt *pSelect = 0; int rc = SQLITE_OK; char *zWrite = 0; /* Create the table and its triggers in the temp schema */ rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab); while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){ const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0); rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr); } idxFinalize(&rc, pSelect); /* Rename the table in the temp schema to zInt */ if( rc==SQLITE_OK ){ char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt); if( z==0 ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr); sqlite3_free(z); } } switch( pWrite->eOp ){ case SQLITE_INSERT: { int i; zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt); for(i=0; i<pTab->nCol; i++){ zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", "); } zWrite = idxAppendText(&rc, zWrite, ")"); break; } case SQLITE_UPDATE: { int i; zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt); for(i=0; i<pTab->nCol; i++){ zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ", pTab->aCol[i].zName ); } break; } default: { assert( pWrite->eOp==SQLITE_DELETE ); if( rc==SQLITE_OK ){ zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt); if( zWrite==0 ) rc = SQLITE_NOMEM; } } } if( rc==SQLITE_OK ){ sqlite3_stmt *pX = 0; rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0); idxFinalize(&rc, pX); if( rc!=SQLITE_OK ){ idxDatabaseError(p->dbv, pzErr); } } sqlite3_free(zWrite); if( rc==SQLITE_OK ){ rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr); } return rc; } static int idxProcessTriggers(sqlite3expert *p, char **pzErr){ int rc = SQLITE_OK; IdxWrite *pEnd = 0; IdxWrite *pFirst = p->pWrite; while( rc==SQLITE_OK && pFirst!=pEnd ){ IdxWrite *pIter; for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){ rc = idxProcessOneTrigger(p, pIter, pzErr); } pEnd = pFirst; pFirst = p->pWrite; } return rc; } static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){ int rc = idxRegisterVtab(p); sqlite3_stmt *pSchema = 0; /* For each table in the main db schema: ** ** 1) Add an entry to the p->pTable list, and ** 2) Create the equivalent virtual table in dbv. */ rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg, "SELECT type, name, sql, 1 FROM sqlite_master " "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' " " UNION ALL " "SELECT type, name, sql, 2 FROM sqlite_master " "WHERE type = 'trigger'" " AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') " "ORDER BY 4, 1" ); while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){ const char *zType = (const char*)sqlite3_column_text(pSchema, 0); const char *zName = (const char*)sqlite3_column_text(pSchema, 1); const char *zSql = (const char*)sqlite3_column_text(pSchema, 2); if( zType[0]=='v' || zType[1]=='r' ){ rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg); }else{ IdxTable *pTab; rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg); if( rc==SQLITE_OK ){ int i; char *zInner = 0; char *zOuter = 0; pTab->pNext = p->pTable; p->pTable = pTab; /* The statement the vtab will pass to sqlite3_declare_vtab() */ zInner = idxAppendText(&rc, 0, "CREATE TABLE x("); for(i=0; i<pTab->nCol; i++){ zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s", (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl ); } zInner = idxAppendText(&rc, zInner, ")"); /* The CVT statement to create the vtab */ zOuter = idxAppendText(&rc, 0, "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner ); if( rc==SQLITE_OK ){ rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg); } sqlite3_free(zInner); sqlite3_free(zOuter); } } } idxFinalize(&rc, pSchema); return rc; } struct IdxSampleCtx { int iTarget; double target; /* Target nRet/nRow value */ double nRow; /* Number of rows seen */ double nRet; /* Number of rows returned */ }; static void idxSampleFunc( sqlite3_context *pCtx, int argc, sqlite3_value **argv ){ struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx); int bRet; (void)argv; assert( argc==0 ); if( p->nRow==0.0 ){ bRet = 1; }else{ bRet = (p->nRet / p->nRow) <= p->target; if( bRet==0 ){ unsigned short rnd; sqlite3_randomness(2, (void*)&rnd); bRet = ((int)rnd % 100) <= p->iTarget; } } sqlite3_result_int(pCtx, bRet); p->nRow += 1.0; p->nRet += (double)bRet; } struct IdxRemCtx { int nSlot; struct IdxRemSlot { int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */ i64 iVal; /* SQLITE_INTEGER value */ double rVal; /* SQLITE_FLOAT value */ int nByte; /* Bytes of space allocated at z */ int n; /* Size of buffer z */ char *z; /* SQLITE_TEXT/BLOB value */ } aSlot[1]; }; /* ** Implementation of scalar function rem(). */ static void idxRemFunc( sqlite3_context *pCtx, int argc, sqlite3_value **argv ){ struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx); struct IdxRemSlot *pSlot; int iSlot; assert( argc==2 ); iSlot = sqlite3_value_int(argv[0]); assert( iSlot<=p->nSlot ); pSlot = &p->aSlot[iSlot]; switch( pSlot->eType ){ case SQLITE_NULL: /* no-op */ break; case SQLITE_INTEGER: sqlite3_result_int64(pCtx, pSlot->iVal); break; case SQLITE_FLOAT: sqlite3_result_double(pCtx, pSlot->rVal); break; case SQLITE_BLOB: sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); break; case SQLITE_TEXT: sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); break; } pSlot->eType = sqlite3_value_type(argv[1]); switch( pSlot->eType ){ case SQLITE_NULL: /* no-op */ break; case SQLITE_INTEGER: pSlot->iVal = sqlite3_value_int64(argv[1]); break; case SQLITE_FLOAT: pSlot->rVal = sqlite3_value_double(argv[1]); break; case SQLITE_BLOB: case SQLITE_TEXT: { int nByte = sqlite3_value_bytes(argv[1]); if( nByte>pSlot->nByte ){ char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2); if( zNew==0 ){ sqlite3_result_error_nomem(pCtx); return; } pSlot->nByte = nByte*2; pSlot->z = zNew; } pSlot->n = nByte; if( pSlot->eType==SQLITE_BLOB ){ memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte); }else{ memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte); } break; } } } static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){ int rc = SQLITE_OK; const char *zMax = "SELECT max(i.seqno) FROM " " sqlite_master AS s, " " pragma_index_list(s.name) AS l, " " pragma_index_info(l.name) AS i " "WHERE s.type = 'table'"; sqlite3_stmt *pMax = 0; *pnMax = 0; rc = idxPrepareStmt(db, &pMax, pzErr, zMax); if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){ *pnMax = sqlite3_column_int(pMax, 0) + 1; } idxFinalize(&rc, pMax); return rc; } static int idxPopulateOneStat1( sqlite3expert *p, sqlite3_stmt *pIndexXInfo, sqlite3_stmt *pWriteStat, const char *zTab, const char *zIdx, char **pzErr ){ char *zCols = 0; char *zOrder = 0; char *zQuery = 0; int nCol = 0; int i; sqlite3_stmt *pQuery = 0; int *aStat = 0; int rc = SQLITE_OK; assert( p->iSample>0 ); /* Formulate the query text */ sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC); while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){ const char *zComma = zCols==0 ? "" : ", "; const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0); const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1); zCols = idxAppendText(&rc, zCols, "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl ); zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol); } sqlite3_reset(pIndexXInfo); if( rc==SQLITE_OK ){ if( p->iSample==100 ){ zQuery = sqlite3_mprintf( "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder ); }else{ zQuery = sqlite3_mprintf( "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder ); } } sqlite3_free(zCols); sqlite3_free(zOrder); /* Formulate the query text */ if( rc==SQLITE_OK ){ sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery); } sqlite3_free(zQuery); if( rc==SQLITE_OK ){ aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1)); } if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){ IdxHashEntry *pEntry; char *zStat = 0; for(i=0; i<=nCol; i++) aStat[i] = 1; while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){ aStat[0]++; for(i=0; i<nCol; i++){ if( sqlite3_column_int(pQuery, i)==0 ) break; } for(/*no-op*/; i<nCol; i++){ aStat[i+1]++; } } if( rc==SQLITE_OK ){ int s0 = aStat[0]; zStat = sqlite3_mprintf("%d", s0); if( zStat==0 ) rc = SQLITE_NOMEM; for(i=1; rc==SQLITE_OK && i<=nCol; i++){ zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]); } } if( rc==SQLITE_OK ){ sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC); sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC); sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC); sqlite3_step(pWriteStat); rc = sqlite3_reset(pWriteStat); } pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx)); if( pEntry ){ assert( pEntry->zVal2==0 ); pEntry->zVal2 = zStat; }else{ sqlite3_free(zStat); } } sqlite3_free(aStat); idxFinalize(&rc, pQuery); return rc; } static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){ int rc; char *zSql; rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); if( rc!=SQLITE_OK ) return rc; zSql = sqlite3_mprintf( "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab ); if( zSql==0 ) return SQLITE_NOMEM; rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0); sqlite3_free(zSql); return rc; } /* ** This function is called as part of sqlite3_expert_analyze(). Candidate ** indexes have already been created in database sqlite3expert.dbm, this ** function populates sqlite_stat1 table in the same database. ** ** The stat1 data is generated by querying the */ static int idxPopulateStat1(sqlite3expert *p, char **pzErr){ int rc = SQLITE_OK; int nMax =0; struct IdxRemCtx *pCtx = 0; struct IdxSampleCtx samplectx; int i; i64 iPrev = -100000; sqlite3_stmt *pAllIndex = 0; sqlite3_stmt *pIndexXInfo = 0; sqlite3_stmt *pWrite = 0; const char *zAllIndex = "SELECT s.rowid, s.name, l.name FROM " " sqlite_master AS s, " " pragma_index_list(s.name) AS l " "WHERE s.type = 'table'"; const char *zIndexXInfo = "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key"; const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)"; /* If iSample==0, no sqlite_stat1 data is required. */ if( p->iSample==0 ) return SQLITE_OK; rc = idxLargestIndex(p->dbm, &nMax, pzErr); if( nMax<=0 || rc!=SQLITE_OK ) return rc; rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0); if( rc==SQLITE_OK ){ int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax); pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte); } if( rc==SQLITE_OK ){ sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); rc = sqlite3_create_function( dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0 ); } if( rc==SQLITE_OK ){ rc = sqlite3_create_function( p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0 ); } if( rc==SQLITE_OK ){ pCtx->nSlot = nMax+1; rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex); } if( rc==SQLITE_OK ){ rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo); } if( rc==SQLITE_OK ){ rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite); } while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){ i64 iRowid = sqlite3_column_int64(pAllIndex, 0); const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1); const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2); if( p->iSample<100 && iPrev!=iRowid ){ samplectx.target = (double)p->iSample / 100.0; samplectx.iTarget = p->iSample; samplectx.nRow = 0.0; samplectx.nRet = 0.0; rc = idxBuildSampleTable(p, zTab); if( rc!=SQLITE_OK ) break; } rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr); iPrev = iRowid; } if( rc==SQLITE_OK && p->iSample<100 ){ rc = sqlite3_exec(p->dbv, "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0 ); } idxFinalize(&rc, pAllIndex); idxFinalize(&rc, pIndexXInfo); idxFinalize(&rc, pWrite); for(i=0; i<pCtx->nSlot; i++){ sqlite3_free(pCtx->aSlot[i].z); } sqlite3_free(pCtx); if( rc==SQLITE_OK ){ rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_master", 0, 0, 0); } sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); return rc; } /* ** Allocate a new sqlite3expert object. */ sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){ int rc = SQLITE_OK; sqlite3expert *pNew; pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert)); /* Open two in-memory databases to work with. The "vtab database" (dbv) ** will contain a virtual table corresponding to each real table in ** the user database schema, and a copy of each view. It is used to ** collect information regarding the WHERE, ORDER BY and other clauses ** of the user's query. */ if( rc==SQLITE_OK ){ pNew->db = db; pNew->iSample = 100; rc = sqlite3_open(":memory:", &pNew->dbv); } if( rc==SQLITE_OK ){ rc = sqlite3_open(":memory:", &pNew->dbm); if( rc==SQLITE_OK ){ sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0); } } /* Copy the entire schema of database [db] into [dbm]. */ if( rc==SQLITE_OK ){ sqlite3_stmt *pSql; rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'" " AND sql NOT LIKE 'CREATE VIRTUAL %%'" ); while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ const char *zSql = (const char*)sqlite3_column_text(pSql, 0); rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg); } idxFinalize(&rc, pSql); } /* Create the vtab schema */ if( rc==SQLITE_OK ){ rc = idxCreateVtabSchema(pNew, pzErrmsg); } /* Register the auth callback with dbv */ if( rc==SQLITE_OK ){ sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew); } /* If an error has occurred, free the new object and reutrn NULL. Otherwise, ** return the new sqlite3expert handle. */ if( rc!=SQLITE_OK ){ sqlite3_expert_destroy(pNew); pNew = 0; } return pNew; } /* ** Configure an sqlite3expert object. */ int sqlite3_expert_config(sqlite3expert *p, int op, ...){ int rc = SQLITE_OK; va_list ap; va_start(ap, op); switch( op ){ case EXPERT_CONFIG_SAMPLE: { int iVal = va_arg(ap, int); if( iVal<0 ) iVal = 0; if( iVal>100 ) iVal = 100; p->iSample = iVal; break; } default: rc = SQLITE_NOTFOUND; break; } va_end(ap); return rc; } /* ** Add an SQL statement to the analysis. */ int sqlite3_expert_sql( sqlite3expert *p, /* From sqlite3_expert_new() */ const char *zSql, /* SQL statement to add */ char **pzErr /* OUT: Error message (if any) */ ){ IdxScan *pScanOrig = p->pScan; IdxStatement *pStmtOrig = p->pStatement; int rc = SQLITE_OK; const char *zStmt = zSql; if( p->bRun ) return SQLITE_MISUSE; while( rc==SQLITE_OK && zStmt && zStmt[0] ){ sqlite3_stmt *pStmt = 0; rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt); if( rc==SQLITE_OK ){ if( pStmt ){ IdxStatement *pNew; const char *z = sqlite3_sql(pStmt); int n = STRLEN(z); pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1); if( rc==SQLITE_OK ){ pNew->zSql = (char*)&pNew[1]; memcpy(pNew->zSql, z, n+1); pNew->pNext = p->pStatement; if( p->pStatement ) pNew->iId = p->pStatement->iId+1; p->pStatement = pNew; } sqlite3_finalize(pStmt); } }else{ idxDatabaseError(p->dbv, pzErr); } } if( rc!=SQLITE_OK ){ idxScanFree(p->pScan, pScanOrig); idxStatementFree(p->pStatement, pStmtOrig); p->pScan = pScanOrig; p->pStatement = pStmtOrig; } return rc; } int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){ int rc; IdxHashEntry *pEntry; /* Do trigger processing to collect any extra IdxScan structures */ rc = idxProcessTriggers(p, pzErr); /* Create candidate indexes within the in-memory database file */ if( rc==SQLITE_OK ){ rc = idxCreateCandidates(p); } /* Generate the stat1 data */ if( rc==SQLITE_OK ){ rc = idxPopulateStat1(p, pzErr); } /* Formulate the EXPERT_REPORT_CANDIDATES text */ for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ p->zCandidates = idxAppendText(&rc, p->zCandidates, "%s;%s%s\n", pEntry->zVal, pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2 ); } /* Figure out which of the candidate indexes are preferred by the query ** planner and report the results to the user. */ if( rc==SQLITE_OK ){ rc = idxFindIndexes(p, pzErr); } if( rc==SQLITE_OK ){ p->bRun = 1; } return rc; } /* ** Return the total number of statements that have been added to this ** sqlite3expert using sqlite3_expert_sql(). */ int sqlite3_expert_count(sqlite3expert *p){ int nRet = 0; if( p->pStatement ) nRet = p->pStatement->iId+1; return nRet; } /* ** Return a component of the report. */ const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){ const char *zRet = 0; IdxStatement *pStmt; if( p->bRun==0 ) return 0; for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext); switch( eReport ){ case EXPERT_REPORT_SQL: if( pStmt ) zRet = pStmt->zSql; break; case EXPERT_REPORT_INDEXES: if( pStmt ) zRet = pStmt->zIdx; break; case EXPERT_REPORT_PLAN: if( pStmt ) zRet = pStmt->zEQP; break; case EXPERT_REPORT_CANDIDATES: zRet = p->zCandidates; break; } return zRet; } /* ** Free an sqlite3expert object. */ void sqlite3_expert_destroy(sqlite3expert *p){ if( p ){ sqlite3_close(p->dbm); sqlite3_close(p->dbv); idxScanFree(p->pScan, 0); idxStatementFree(p->pStatement, 0); idxTableFree(p->pTable); idxWriteFree(p->pWrite); idxHashClear(&p->hIdx); sqlite3_free(p->zCandidates); sqlite3_free(p); } } #endif /* ifndef SQLITE_OMIT_VIRTUAL_TABLE */ /************************* End ../ext/expert/sqlite3expert.c ********************/ #if defined(SQLITE_ENABLE_SESSION) /* ** State information for a single open session */ typedef struct OpenSession OpenSession; struct OpenSession { char *zName; /* Symbolic name for this session */ int nFilter; /* Number of xFilter rejection GLOB patterns */ char **azFilter; /* Array of xFilter rejection GLOB patterns */ sqlite3_session *p; /* The open session */ }; #endif /* ** Shell output mode information from before ".explain on", ** saved so that it can be restored by ".explain off" */ typedef struct SavedModeInfo SavedModeInfo; struct SavedModeInfo { int valid; /* Is there legit data in here? */ int mode; /* Mode prior to ".explain on" */ int showHeader; /* The ".header" setting prior to ".explain on" */ int colWidth[100]; /* Column widths prior to ".explain on" */ }; typedef struct ExpertInfo ExpertInfo; struct ExpertInfo { sqlite3expert *pExpert; int bVerbose; }; /* ** State information about the database connection is contained in an ** instance of the following structure. */ typedef struct ShellState ShellState; struct ShellState { sqlite3 *db; /* The database */ u8 autoExplain; /* Automatically turn on .explain mode */ u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ u8 statsOn; /* True to display memory stats before each finalize */ u8 scanstatsOn; /* True to display scan stats before each finalize */ u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ int outCount; /* Revert to stdout when reaching zero */ int cnt; /* Number of records displayed so far */ FILE *out; /* Write results here */ FILE *traceOut; /* Output for sqlite3_trace() */ int nErr; /* Number of errors seen */ int mode; /* An output mode setting */ int modePrior; /* Saved mode */ int cMode; /* temporary output mode for the current query */ int normalMode; /* Output mode before ".explain on" */ int writableSchema; /* True if PRAGMA writable_schema=ON */ int showHeader; /* True to show column names in List or Column mode */ int nCheck; /* Number of ".check" commands run */ unsigned shellFlgs; /* Various flags */ char *zDestTable; /* Name of destination table when MODE_Insert */ char *zTempFile; /* Temporary file that might need deleting */ char zTestcase[30]; /* Name of current test case */ char colSeparator[20]; /* Column separator character for several modes */ char rowSeparator[20]; /* Row separator character for MODE_Ascii */ char colSepPrior[20]; /* Saved column separator */ char rowSepPrior[20]; /* Saved row separator */ int colWidth[100]; /* Requested width of each column when in column mode*/ int actualWidth[100]; /* Actual width of each column */ char nullValue[20]; /* The text to print when a NULL comes back from ** the database */ char outfile[FILENAME_MAX]; /* Filename for *out */ const char *zDbFilename; /* name of the database file */ char *zFreeOnClose; /* Filename to free when closing */ const char *zVfs; /* Name of VFS to use */ sqlite3_stmt *pStmt; /* Current statement if any. */ FILE *pLog; /* Write log output here */ int *aiIndent; /* Array of indents used in MODE_Explain */ int nIndent; /* Size of array aiIndent[] */ int iIndent; /* Index of current op in aiIndent[] */ #if defined(SQLITE_ENABLE_SESSION) int nSession; /* Number of active sessions */ OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ #endif ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ }; /* Allowed values for ShellState.autoEQP */ #define AUTOEQP_off 0 #define AUTOEQP_on 1 #define AUTOEQP_trigger 2 #define AUTOEQP_full 3 /* Allowed values for ShellState.openMode */ #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ #define SHELL_OPEN_NORMAL 1 /* Normal database file */ #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ /* ** These are the allowed shellFlgs values */ #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ #define SHFLG_CountChanges 0x00000020 /* .changes setting */ #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */ /* ** Macros for testing and setting shellFlgs */ #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) /* ** These are the allowed modes. */ #define MODE_Line 0 /* One column per line. Blank line between records */ #define MODE_Column 1 /* One record per line in neat columns */ #define MODE_List 2 /* One record per line with a separator */ #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ #define MODE_Html 4 /* Generate an XHTML table */ #define MODE_Insert 5 /* Generate SQL "insert" statements */ #define MODE_Quote 6 /* Quote values as for SQL */ #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ #define MODE_Csv 8 /* Quote strings, numbers are plain */ #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ #define MODE_Pretty 11 /* Pretty-print schemas */ static const char *modeDescr[] = { "line", "column", "list", "semi", "html", "insert", "quote", "tcl", "csv", "explain", "ascii", "prettyprint", }; /* ** These are the column/row/line separators used by the various ** import/export modes. */ #define SEP_Column "|" #define SEP_Row "\n" #define SEP_Tab "\t" #define SEP_Space " " #define SEP_Comma "," #define SEP_CrLf "\r\n" #define SEP_Unit "\x1F" #define SEP_Record "\x1E" /* ** A callback for the sqlite3_log() interface. */ static void shellLog(void *pArg, int iErrCode, const char *zMsg){ ShellState *p = (ShellState*)pArg; if( p->pLog==0 ) return; utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); fflush(p->pLog); } /* ** SQL function: shell_putsnl(X) ** ** Write the text X to the screen (or whatever output is being directed) ** adding a newline at the end, and then return X. */ static void shellPutsFunc( sqlite3_context *pCtx, int nVal, sqlite3_value **apVal ){ ShellState *p = (ShellState*)sqlite3_user_data(pCtx); (void)nVal; utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); sqlite3_result_value(pCtx, apVal[0]); } /* ** SQL function: edit(VALUE) ** edit(VALUE,EDITOR) ** ** These steps: ** ** (1) Write VALUE into a temporary file. ** (2) Run program EDITOR on that temporary file. ** (3) Read the temporary file back and return its content as the result. ** (4) Delete the temporary file ** ** If the EDITOR argument is omitted, use the value in the VISUAL ** environment variable. If still there is no EDITOR, through an error. ** ** Also throw an error if the EDITOR program returns a non-zero exit code. */ #ifndef SQLITE_NOHAVE_SYSTEM static void editFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *zEditor; char *zTempFile = 0; sqlite3 *db; char *zCmd = 0; int bBin; int rc; FILE *f = 0; sqlite3_int64 sz; sqlite3_int64 x; unsigned char *p = 0; if( argc==2 ){ zEditor = (const char*)sqlite3_value_text(argv[1]); }else{ zEditor = getenv("VISUAL"); } if( zEditor==0 ){ sqlite3_result_error(context, "no editor for edit()", -1); return; } if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ sqlite3_result_error(context, "NULL input to edit()", -1); return; } db = sqlite3_context_db_handle(context); zTempFile = 0; sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); if( zTempFile==0 ){ sqlite3_uint64 r = 0; sqlite3_randomness(sizeof(r), &r); zTempFile = sqlite3_mprintf("temp%llx", r); if( zTempFile==0 ){ sqlite3_result_error_nomem(context); return; } } bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; f = fopen(zTempFile, bBin ? "wb" : "w"); if( f==0 ){ sqlite3_result_error(context, "edit() cannot open temp file", -1); goto edit_func_end; } sz = sqlite3_value_bytes(argv[0]); if( bBin ){ x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f); }else{ x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f); } fclose(f); f = 0; if( x!=sz ){ sqlite3_result_error(context, "edit() could not write the whole file", -1); goto edit_func_end; } zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); if( zCmd==0 ){ sqlite3_result_error_nomem(context); goto edit_func_end; } rc = system(zCmd); sqlite3_free(zCmd); if( rc ){ sqlite3_result_error(context, "EDITOR returned non-zero", -1); goto edit_func_end; } f = fopen(zTempFile, bBin ? "rb" : "r"); if( f==0 ){ sqlite3_result_error(context, "edit() cannot reopen temp file after edit", -1); goto edit_func_end; } fseek(f, 0, SEEK_END); sz = ftell(f); rewind(f); p = sqlite3_malloc64( sz+(bBin==0) ); if( p==0 ){ sqlite3_result_error_nomem(context); goto edit_func_end; } if( bBin ){ x = fread(p, 1, sz, f); }else{ x = fread(p, 1, sz, f); p[sz] = 0; } fclose(f); f = 0; if( x!=sz ){ sqlite3_result_error(context, "could not read back the whole file", -1); goto edit_func_end; } if( bBin ){ sqlite3_result_blob64(context, p, sz, sqlite3_free); }else{ sqlite3_result_text64(context, (const char*)p, sz, sqlite3_free, SQLITE_UTF8); } p = 0; edit_func_end: if( f ) fclose(f); unlink(zTempFile); sqlite3_free(zTempFile); sqlite3_free(p); } #endif /* SQLITE_NOHAVE_SYSTEM */ /* ** Save or restore the current output mode */ static void outputModePush(ShellState *p){ p->modePrior = p->mode; memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); } static void outputModePop(ShellState *p){ p->mode = p->modePrior; memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); } /* ** Output the given string as a hex-encoded blob (eg. X'1234' ) */ static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ int i; char *zBlob = (char *)pBlob; raw_printf(out,"X'"); for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); } raw_printf(out,"'"); } /* ** Find a string that is not found anywhere in z[]. Return a pointer ** to that string. ** ** Try to use zA and zB first. If both of those are already found in z[] ** then make up some string and store it in the buffer zBuf. */ static const char *unused_string( const char *z, /* Result must not appear anywhere in z */ const char *zA, const char *zB, /* Try these first */ char *zBuf /* Space to store a generated string */ ){ unsigned i = 0; if( strstr(z, zA)==0 ) return zA; if( strstr(z, zB)==0 ) return zB; do{ sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); }while( strstr(z,zBuf)!=0 ); return zBuf; } /* ** Output the given string as a quoted string using SQL quoting conventions. ** ** See also: output_quoted_escaped_string() */ static void output_quoted_string(FILE *out, const char *z){ int i; char c; setBinaryMode(out, 1); for(i=0; (c = z[i])!=0 && c!='\''; i++){} if( c==0 ){ utf8_printf(out,"'%s'",z); }else{ raw_printf(out, "'"); while( *z ){ for(i=0; (c = z[i])!=0 && c!='\''; i++){} if( c=='\'' ) i++; if( i ){ utf8_printf(out, "%.*s", i, z); z += i; } if( c=='\'' ){ raw_printf(out, "'"); continue; } if( c==0 ){ break; } z++; } raw_printf(out, "'"); } setTextMode(out, 1); } /* ** Output the given string as a quoted string using SQL quoting conventions. ** Additionallly , escape the "\n" and "\r" characters so that they do not ** get corrupted by end-of-line translation facilities in some operating ** systems. ** ** This is like output_quoted_string() but with the addition of the \r\n ** escape mechanism. */ static void output_quoted_escaped_string(FILE *out, const char *z){ int i; char c; setBinaryMode(out, 1); for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} if( c==0 ){ utf8_printf(out,"'%s'",z); }else{ const char *zNL = 0; const char *zCR = 0; int nNL = 0; int nCR = 0; char zBuf1[20], zBuf2[20]; for(i=0; z[i]; i++){ if( z[i]=='\n' ) nNL++; if( z[i]=='\r' ) nCR++; } if( nNL ){ raw_printf(out, "replace("); zNL = unused_string(z, "\\n", "\\012", zBuf1); } if( nCR ){ raw_printf(out, "replace("); zCR = unused_string(z, "\\r", "\\015", zBuf2); } raw_printf(out, "'"); while( *z ){ for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} if( c=='\'' ) i++; if( i ){ utf8_printf(out, "%.*s", i, z); z += i; } if( c=='\'' ){ raw_printf(out, "'"); continue; } if( c==0 ){ break; } z++; if( c=='\n' ){ raw_printf(out, "%s", zNL); continue; } raw_printf(out, "%s", zCR); } raw_printf(out, "'"); if( nCR ){ raw_printf(out, ",'%s',char(13))", zCR); } if( nNL ){ raw_printf(out, ",'%s',char(10))", zNL); } } setTextMode(out, 1); } /* ** Output the given string as a quoted according to C or TCL quoting rules. */ static void output_c_string(FILE *out, const char *z){ unsigned int c; fputc('"', out); while( (c = *(z++))!=0 ){ if( c=='\\' ){ fputc(c, out); fputc(c, out); }else if( c=='"' ){ fputc('\\', out); fputc('"', out); }else if( c=='\t' ){ fputc('\\', out); fputc('t', out); }else if( c=='\n' ){ fputc('\\', out); fputc('n', out); }else if( c=='\r' ){ fputc('\\', out); fputc('r', out); }else if( !isprint(c&0xff) ){ raw_printf(out, "\\%03o", c&0xff); }else{ fputc(c, out); } } fputc('"', out); } /* ** Output the given string with characters that are special to ** HTML escaped. */ static void output_html_string(FILE *out, const char *z){ int i; if( z==0 ) z = ""; while( *z ){ for(i=0; z[i] && z[i]!='<' && z[i]!='&' && z[i]!='>' && z[i]!='\"' && z[i]!='\''; i++){} if( i>0 ){ utf8_printf(out,"%.*s",i,z); } if( z[i]=='<' ){ raw_printf(out,"&lt;"); }else if( z[i]=='&' ){ raw_printf(out,"&amp;"); }else if( z[i]=='>' ){ raw_printf(out,"&gt;"); }else if( z[i]=='\"' ){ raw_printf(out,"&quot;"); }else if( z[i]=='\'' ){ raw_printf(out,"&#39;"); }else{ break; } z += i + 1; } } /* ** If a field contains any character identified by a 1 in the following ** array, then the string must be quoted for CSV. */ static const char needCsvQuote[] = { 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, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, }; /* ** Output a single term of CSV. Actually, p->colSeparator is used for ** the separator, which may or may not be a comma. p->nullValue is ** the null value. Strings are quoted if necessary. The separator ** is only issued if bSep is true. */ static void output_csv(ShellState *p, const char *z, int bSep){ FILE *out = p->out; if( z==0 ){ utf8_printf(out,"%s",p->nullValue); }else{ int i; int nSep = strlen30(p->colSeparator); for(i=0; z[i]; i++){ if( needCsvQuote[((unsigned char*)z)[i]] || (z[i]==p->colSeparator[0] && (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){ i = 0; break; } } if( i==0 ){ char *zQuoted = sqlite3_mprintf("\"%w\"", z); utf8_printf(out, "%s", zQuoted); sqlite3_free(zQuoted); }else{ utf8_printf(out, "%s", z); } } if( bSep ){ utf8_printf(p->out, "%s", p->colSeparator); } } /* ** This routine runs when the user presses Ctrl-C */ static void interrupt_handler(int NotUsed){ UNUSED_PARAMETER(NotUsed); seenInterrupt++; if( seenInterrupt>2 ) exit(1); if( globalDb ) sqlite3_interrupt(globalDb); } #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) /* ** This routine runs for console events (e.g. Ctrl-C) on Win32 */ static BOOL WINAPI ConsoleCtrlHandler( DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ ){ if( dwCtrlType==CTRL_C_EVENT ){ interrupt_handler(0); return TRUE; } return FALSE; } #endif #ifndef SQLITE_OMIT_AUTHORIZATION /* ** When the ".auth ON" is set, the following authorizer callback is ** invoked. It always returns SQLITE_OK. */ static int shellAuth( void *pClientData, int op, const char *zA1, const char *zA2, const char *zA3, const char *zA4 ){ ShellState *p = (ShellState*)pClientData; static const char *azAction[] = { 0, "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", "DROP_TRIGGER", "DROP_VIEW", "INSERT", "PRAGMA", "READ", "SELECT", "TRANSACTION", "UPDATE", "ATTACH", "DETACH", "ALTER_TABLE", "REINDEX", "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", "FUNCTION", "SAVEPOINT", "RECURSIVE" }; int i; const char *az[4]; az[0] = zA1; az[1] = zA2; az[2] = zA3; az[3] = zA4; utf8_printf(p->out, "authorizer: %s", azAction[op]); for(i=0; i<4; i++){ raw_printf(p->out, " "); if( az[i] ){ output_c_string(p->out, az[i]); }else{ raw_printf(p->out, "NULL"); } } raw_printf(p->out, "\n"); return SQLITE_OK; } #endif /* ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. ** ** This routine converts some CREATE TABLE statements for shadow tables ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. */ static void printSchemaLine(FILE *out, const char *z, const char *zTail){ if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); }else{ utf8_printf(out, "%s%s", z, zTail); } } static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ char c = z[n]; z[n] = 0; printSchemaLine(out, z, zTail); z[n] = c; } /* ** Return true if string z[] has nothing but whitespace and comments to the ** end of the first line. */ static int wsToEol(const char *z){ int i; for(i=0; z[i]; i++){ if( z[i]=='\n' ) return 1; if( IsSpace(z[i]) ) continue; if( z[i]=='-' && z[i+1]=='-' ) return 1; return 0; } return 1; } /* ** This is the callback routine that the shell ** invokes for each row of a query result. */ static int shell_callback( void *pArg, int nArg, /* Number of result columns */ char **azArg, /* Text of each result column */ char **azCol, /* Column names */ int *aiType /* Column types */ ){ int i; ShellState *p = (ShellState*)pArg; if( azArg==0 ) return 0; switch( p->cMode ){ case MODE_Line: { int w = 5; if( azArg==0 ) break; for(i=0; i<nArg; i++){ int len = strlen30(azCol[i] ? azCol[i] : ""); if( len>w ) w = len; } if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); for(i=0; i<nArg; i++){ utf8_printf(p->out,"%*s = %s%s", w, azCol[i], azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); } break; } case MODE_Explain: case MODE_Column: { static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13}; const int *colWidth; int showHdr; char *rowSep; if( p->cMode==MODE_Column ){ colWidth = p->colWidth; showHdr = p->showHeader; rowSep = p->rowSeparator; }else{ colWidth = aExplainWidths; showHdr = 1; rowSep = SEP_Row; } if( p->cnt++==0 ){ for(i=0; i<nArg; i++){ int w, n; if( i<ArraySize(p->colWidth) ){ w = colWidth[i]; }else{ w = 0; } if( w==0 ){ w = strlenChar(azCol[i] ? azCol[i] : ""); if( w<10 ) w = 10; n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue); if( w<n ) w = n; } if( i<ArraySize(p->actualWidth) ){ p->actualWidth[i] = w; } if( showHdr ){ utf8_width_print(p->out, w, azCol[i]); utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); } } if( showHdr ){ for(i=0; i<nArg; i++){ int w; if( i<ArraySize(p->actualWidth) ){ w = p->actualWidth[i]; if( w<0 ) w = -w; }else{ w = 10; } utf8_printf(p->out,"%-*.*s%s",w,w, "----------------------------------------------------------" "----------------------------------------------------------", i==nArg-1 ? rowSep : " "); } } } if( azArg==0 ) break; for(i=0; i<nArg; i++){ int w; if( i<ArraySize(p->actualWidth) ){ w = p->actualWidth[i]; }else{ w = 10; } if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){ w = strlenChar(azArg[i]); } if( i==1 && p->aiIndent && p->pStmt ){ if( p->iIndent<p->nIndent ){ utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); } p->iIndent++; } utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); } break; } case MODE_Semi: { /* .schema and .fullschema output */ printSchemaLine(p->out, azArg[0], ";\n"); break; } case MODE_Pretty: { /* .schema and .fullschema with --indent */ char *z; int j; int nParen = 0; char cEnd = 0; char c; int nLine = 0; assert( nArg==1 ); if( azArg[0]==0 ) break; if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 ){ utf8_printf(p->out, "%s;\n", azArg[0]); break; } z = sqlite3_mprintf("%s", azArg[0]); j = 0; for(i=0; IsSpace(z[i]); i++){} for(; (c = z[i])!=0; i++){ if( IsSpace(c) ){ if( z[j-1]=='\r' ) z[j-1] = '\n'; if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ j--; } z[j++] = c; } while( j>0 && IsSpace(z[j-1]) ){ j--; } z[j] = 0; if( strlen30(z)>=79 ){ for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */ if( c==cEnd ){ cEnd = 0; }else if( c=='"' || c=='\'' || c=='`' ){ cEnd = c; }else if( c=='[' ){ cEnd = ']'; }else if( c=='-' && z[i+1]=='-' ){ cEnd = '\n'; }else if( c=='(' ){ nParen++; }else if( c==')' ){ nParen--; if( nLine>0 && nParen==0 && j>0 ){ printSchemaLineN(p->out, z, j, "\n"); j = 0; } } z[j++] = c; if( nParen==1 && cEnd==0 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) ){ if( c=='\n' ) j--; printSchemaLineN(p->out, z, j, "\n "); j = 0; nLine++; while( IsSpace(z[i+1]) ){ i++; } } } z[j] = 0; } printSchemaLine(p->out, z, ";\n"); sqlite3_free(z); break; } case MODE_List: { if( p->cnt++==0 && p->showHeader ){ for(i=0; i<nArg; i++){ utf8_printf(p->out,"%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator); } } if( azArg==0 ) break; for(i=0; i<nArg; i++){ char *z = azArg[i]; if( z==0 ) z = p->nullValue; utf8_printf(p->out, "%s", z); if( i<nArg-1 ){ utf8_printf(p->out, "%s", p->colSeparator); }else{ utf8_printf(p->out, "%s", p->rowSeparator); } } break; } case MODE_Html: { if( p->cnt++==0 && p->showHeader ){ raw_printf(p->out,"<TR>"); for(i=0; i<nArg; i++){ raw_printf(p->out,"<TH>"); output_html_string(p->out, azCol[i]); raw_printf(p->out,"</TH>\n"); } raw_printf(p->out,"</TR>\n"); } if( azArg==0 ) break; raw_printf(p->out,"<TR>"); for(i=0; i<nArg; i++){ raw_printf(p->out,"<TD>"); output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); raw_printf(p->out,"</TD>\n"); } raw_printf(p->out,"</TR>\n"); break; } case MODE_Tcl: { if( p->cnt++==0 && p->showHeader ){ for(i=0; i<nArg; i++){ output_c_string(p->out,azCol[i] ? azCol[i] : ""); if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); } utf8_printf(p->out, "%s", p->rowSeparator); } if( azArg==0 ) break; for(i=0; i<nArg; i++){ output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); } utf8_printf(p->out, "%s", p->rowSeparator); break; } case MODE_Csv: { setBinaryMode(p->out, 1); if( p->cnt++==0 && p->showHeader ){ for(i=0; i<nArg; i++){ output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); } utf8_printf(p->out, "%s", p->rowSeparator); } if( nArg>0 ){ for(i=0; i<nArg; i++){ output_csv(p, azArg[i], i<nArg-1); } utf8_printf(p->out, "%s", p->rowSeparator); } setTextMode(p->out, 1); break; } case MODE_Insert: { if( azArg==0 ) break; utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); if( p->showHeader ){ raw_printf(p->out,"("); for(i=0; i<nArg; i++){ if( i>0 ) raw_printf(p->out, ","); if( quoteChar(azCol[i]) ){ char *z = sqlite3_mprintf("\"%w\"", azCol[i]); utf8_printf(p->out, "%s", z); sqlite3_free(z); }else{ raw_printf(p->out, "%s", azCol[i]); } } raw_printf(p->out,")"); } p->cnt++; for(i=0; i<nArg; i++){ raw_printf(p->out, i>0 ? "," : " VALUES("); if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ utf8_printf(p->out,"NULL"); }else if( aiType && aiType[i]==SQLITE_TEXT ){ if( ShellHasFlag(p, SHFLG_Newlines) ){ output_quoted_string(p->out, azArg[i]); }else{ output_quoted_escaped_string(p->out, azArg[i]); } }else if( aiType && aiType[i]==SQLITE_INTEGER ){ utf8_printf(p->out,"%s", azArg[i]); }else if( aiType && aiType[i]==SQLITE_FLOAT ){ char z[50]; double r = sqlite3_column_double(p->pStmt, i); sqlite3_snprintf(50,z,"%!.20g", r); raw_printf(p->out, "%s", z); }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ const void *pBlob = sqlite3_column_blob(p->pStmt, i); int nBlob = sqlite3_column_bytes(p->pStmt, i); output_hex_blob(p->out, pBlob, nBlob); }else if( isNumber(azArg[i], 0) ){ utf8_printf(p->out,"%s", azArg[i]); }else if( ShellHasFlag(p, SHFLG_Newlines) ){ output_quoted_string(p->out, azArg[i]); }else{ output_quoted_escaped_string(p->out, azArg[i]); } } raw_printf(p->out,");\n"); break; } case MODE_Quote: { if( azArg==0 ) break; if( p->cnt==0 && p->showHeader ){ for(i=0; i<nArg; i++){ if( i>0 ) raw_printf(p->out, ","); output_quoted_string(p->out, azCol[i]); } raw_printf(p->out,"\n"); } p->cnt++; for(i=0; i<nArg; i++){ if( i>0 ) raw_printf(p->out, ","); if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ utf8_printf(p->out,"NULL"); }else if( aiType && aiType[i]==SQLITE_TEXT ){ output_quoted_string(p->out, azArg[i]); }else if( aiType && aiType[i]==SQLITE_INTEGER ){ utf8_printf(p->out,"%s", azArg[i]); }else if( aiType && aiType[i]==SQLITE_FLOAT ){ char z[50]; double r = sqlite3_column_double(p->pStmt, i); sqlite3_snprintf(50,z,"%!.20g", r); raw_printf(p->out, "%s", z); }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ const void *pBlob = sqlite3_column_blob(p->pStmt, i); int nBlob = sqlite3_column_bytes(p->pStmt, i); output_hex_blob(p->out, pBlob, nBlob); }else if( isNumber(azArg[i], 0) ){ utf8_printf(p->out,"%s", azArg[i]); }else{ output_quoted_string(p->out, azArg[i]); } } raw_printf(p->out,"\n"); break; } case MODE_Ascii: { if( p->cnt++==0 && p->showHeader ){ for(i=0; i<nArg; i++){ if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); } utf8_printf(p->out, "%s", p->rowSeparator); } if( azArg==0 ) break; for(i=0; i<nArg; i++){ if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); } utf8_printf(p->out, "%s", p->rowSeparator); break; } } return 0; } /* ** This is the callback routine that the SQLite library ** invokes for each row of a query result. */ static int callback(void *pArg, int nArg, char **azArg, char **azCol){ /* since we don't have type info, call the shell_callback with a NULL value */ return shell_callback(pArg, nArg, azArg, azCol, NULL); } /* ** This is the callback routine from sqlite3_exec() that appends all ** output onto the end of a ShellText object. */ static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ ShellText *p = (ShellText*)pArg; int i; UNUSED_PARAMETER(az); if( azArg==0 ) return 0; if( p->n ) appendText(p, "|", 0); for(i=0; i<nArg; i++){ if( i ) appendText(p, ",", 0); if( azArg[i] ) appendText(p, azArg[i], 0); } return 0; } /* ** Generate an appropriate SELFTEST table in the main database. */ static void createSelftestTable(ShellState *p){ char *zErrMsg = 0; sqlite3_exec(p->db, "SAVEPOINT selftest_init;\n" "CREATE TABLE IF NOT EXISTS selftest(\n" " tno INTEGER PRIMARY KEY,\n" /* Test number */ " op TEXT,\n" /* Operator: memo run */ " cmd TEXT,\n" /* Command text */ " ans TEXT\n" /* Desired answer */ ");" "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" "INSERT INTO [_shell$self](rowid,op,cmd)\n" " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" " 'memo','Tests generated by --init');\n" "INSERT INTO [_shell$self]\n" " SELECT 'run',\n" " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " "FROM sqlite_master ORDER BY 2'',224))',\n" " hex(sha3_query('SELECT type,name,tbl_name,sql " "FROM sqlite_master ORDER BY 2',224));\n" "INSERT INTO [_shell$self]\n" " SELECT 'run'," " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" " printf('%w',name) || '\" NOT INDEXED'',224))',\n" " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" " FROM (\n" " SELECT name FROM sqlite_master\n" " WHERE type='table'\n" " AND name<>'selftest'\n" " AND coalesce(rootpage,0)>0\n" " )\n" " ORDER BY name;\n" "INSERT INTO [_shell$self]\n" " VALUES('run','PRAGMA integrity_check','ok');\n" "INSERT INTO selftest(tno,op,cmd,ans)" " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" "DROP TABLE [_shell$self];" ,0,0,&zErrMsg); if( zErrMsg ){ utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); } /* ** Set the destination table field of the ShellState structure to ** the name of the table given. Escape any quote characters in the ** table name. */ static void set_table_name(ShellState *p, const char *zName){ int i, n; char cQuote; char *z; if( p->zDestTable ){ free(p->zDestTable); p->zDestTable = 0; } if( zName==0 ) return; cQuote = quoteChar(zName); n = strlen30(zName); if( cQuote ) n += n+2; z = p->zDestTable = malloc( n+1 ); if( z==0 ){ raw_printf(stderr,"Error: out of memory\n"); exit(1); } n = 0; if( cQuote ) z[n++] = cQuote; for(i=0; zName[i]; i++){ z[n++] = zName[i]; if( zName[i]==cQuote ) z[n++] = cQuote; } if( cQuote ) z[n++] = cQuote; z[n] = 0; } /* ** Execute a query statement that will generate SQL output. Print ** the result columns, comma-separated, on a line and then add a ** semicolon terminator to the end of that line. ** ** If the number of columns is 1 and that column contains text "--" ** then write the semicolon on a separate line. That way, if a ** "--" comment occurs at the end of the statement, the comment ** won't consume the semicolon terminator. */ static int run_table_dump_query( ShellState *p, /* Query context */ const char *zSelect, /* SELECT statement to extract content */ const char *zFirstRow /* Print before first row, if not NULL */ ){ sqlite3_stmt *pSelect; int rc; int nResult; int i; const char *z; rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); if( rc!=SQLITE_OK || !pSelect ){ utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; return rc; } rc = sqlite3_step(pSelect); nResult = sqlite3_column_count(pSelect); while( rc==SQLITE_ROW ){ if( zFirstRow ){ utf8_printf(p->out, "%s", zFirstRow); zFirstRow = 0; } z = (const char*)sqlite3_column_text(pSelect, 0); utf8_printf(p->out, "%s", z); for(i=1; i<nResult; i++){ utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); } if( z==0 ) z = ""; while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; if( z[0] ){ raw_printf(p->out, "\n;\n"); }else{ raw_printf(p->out, ";\n"); } rc = sqlite3_step(pSelect); } rc = sqlite3_finalize(pSelect); if( rc!=SQLITE_OK ){ utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; } return rc; } /* ** Allocate space and save off current error string. */ static char *save_err_msg( sqlite3 *db /* Database to query */ ){ int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); char *zErrMsg = sqlite3_malloc64(nErrMsg); if( zErrMsg ){ memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); } return zErrMsg; } #ifdef __linux__ /* ** Attempt to display I/O stats on Linux using /proc/PID/io */ static void displayLinuxIoStats(FILE *out){ FILE *in; char z[200]; sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); in = fopen(z, "rb"); if( in==0 ) return; while( fgets(z, sizeof(z), in)!=0 ){ static const struct { const char *zPattern; const char *zDesc; } aTrans[] = { { "rchar: ", "Bytes received by read():" }, { "wchar: ", "Bytes sent to write():" }, { "syscr: ", "Read() system calls:" }, { "syscw: ", "Write() system calls:" }, { "read_bytes: ", "Bytes read from storage:" }, { "write_bytes: ", "Bytes written to storage:" }, { "cancelled_write_bytes: ", "Cancelled write bytes:" }, }; int i; for(i=0; i<ArraySize(aTrans); i++){ int n = strlen30(aTrans[i].zPattern); if( strncmp(aTrans[i].zPattern, z, n)==0 ){ utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); break; } } } fclose(in); } #endif /* ** Display a single line of status using 64-bit values. */ static void displayStatLine( ShellState *p, /* The shell context */ char *zLabel, /* Label for this one line */ char *zFormat, /* Format for the result */ int iStatusCtrl, /* Which status to display */ int bReset /* True to reset the stats */ ){ sqlite3_int64 iCur = -1; sqlite3_int64 iHiwtr = -1; int i, nPercent; char zLine[200]; sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); for(i=0, nPercent=0; zFormat[i]; i++){ if( zFormat[i]=='%' ) nPercent++; } if( nPercent>1 ){ sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); }else{ sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); } raw_printf(p->out, "%-36s %s\n", zLabel, zLine); } /* ** Display memory stats. */ static int display_stats( sqlite3 *db, /* Database to query */ ShellState *pArg, /* Pointer to ShellState */ int bReset /* True to reset the stats */ ){ int iCur; int iHiwtr; FILE *out; if( pArg==0 || pArg->out==0 ) return 0; out = pArg->out; if( pArg->pStmt && (pArg->statsOn & 2) ){ int nCol, i, x; sqlite3_stmt *pStmt = pArg->pStmt; char z[100]; nCol = sqlite3_column_count(pStmt); raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); for(i=0; i<nCol; i++){ sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); #ifndef SQLITE_OMIT_DECLTYPE sqlite3_snprintf(30, z+x, "declared type:"); utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); #endif #ifdef SQLITE_ENABLE_COLUMN_METADATA sqlite3_snprintf(30, z+x, "database name:"); utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); sqlite3_snprintf(30, z+x, "table name:"); utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); sqlite3_snprintf(30, z+x, "origin name:"); utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); #endif } } displayStatLine(pArg, "Memory Used:", "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); displayStatLine(pArg, "Number of Outstanding Allocations:", "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); if( pArg->shellFlgs & SHFLG_Pagecache ){ displayStatLine(pArg, "Number of Pcache Pages Used:", "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); } displayStatLine(pArg, "Number of Pcache Overflow Bytes:", "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); displayStatLine(pArg, "Largest Allocation:", "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); displayStatLine(pArg, "Largest Pcache Allocation:", "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); #ifdef YYTRACKMAXSTACKDEPTH displayStatLine(pArg, "Deepest Parser Stack:", "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); #endif if( db ){ if( pArg->shellFlgs & SHFLG_Lookaside ){ iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr); } iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); raw_printf(pArg->out, "Page cache hits: %d\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); raw_printf(pArg->out, "Page cache misses: %d\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); raw_printf(pArg->out, "Page cache writes: %d\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); raw_printf(pArg->out, "Page cache spills: %d\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur); } if( pArg->pStmt ){ iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset); raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); raw_printf(pArg->out, "Sort Operations: %d\n", iCur); iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset); raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); raw_printf(pArg->out, "Number of times run: %d\n", iCur); iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); } #ifdef __linux__ displayLinuxIoStats(pArg->out); #endif /* Do not remove this machine readable comment: extra-stats-output-here */ return 0; } /* ** Display scan stats. */ static void display_scanstats( sqlite3 *db, /* Database to query */ ShellState *pArg /* Pointer to ShellState */ ){ #ifndef SQLITE_ENABLE_STMT_SCANSTATUS UNUSED_PARAMETER(db); UNUSED_PARAMETER(pArg); #else int i, k, n, mx; raw_printf(pArg->out, "-------- scanstats --------\n"); mx = 0; for(k=0; k<=mx; k++){ double rEstLoop = 1.0; for(i=n=0; 1; i++){ sqlite3_stmt *p = pArg->pStmt; sqlite3_int64 nLoop, nVisit; double rEst; int iSid; const char *zExplain; if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ break; } sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); if( iSid>mx ) mx = iSid; if( iSid!=k ) continue; if( n==0 ){ rEstLoop = (double)nLoop; if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); } n++; sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); rEstLoop *= rEst; raw_printf(pArg->out, " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst ); } } raw_printf(pArg->out, "---------------------------\n"); #endif } /* ** Parameter azArray points to a zero-terminated array of strings. zStr ** points to a single nul-terminated string. Return non-zero if zStr ** is equal, according to strcmp(), to any of the strings in the array. ** Otherwise, return zero. */ static int str_in_array(const char *zStr, const char **azArray){ int i; for(i=0; azArray[i]; i++){ if( 0==strcmp(zStr, azArray[i]) ) return 1; } return 0; } /* ** If compiled statement pSql appears to be an EXPLAIN statement, allocate ** and populate the ShellState.aiIndent[] array with the number of ** spaces each opcode should be indented before it is output. ** ** The indenting rules are: ** ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent ** all opcodes that occur between the p2 jump destination and the opcode ** itself by 2 spaces. ** ** * For each "Goto", if the jump destination is earlier in the program ** and ends on one of: ** Yield SeekGt SeekLt RowSetRead Rewind ** or if the P1 parameter is one instead of zero, ** then indent all opcodes between the earlier instruction ** and "Goto" by 2 spaces. */ static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ const char *zSql; /* The text of the SQL statement */ const char *z; /* Used to check if this is an EXPLAIN */ int *abYield = 0; /* True if op is an OP_Yield */ int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ int iOp; /* Index of operation in p->aiIndent[] */ const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", "NextIfOpen", "PrevIfOpen", 0 }; const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", "Rewind", 0 }; const char *azGoto[] = { "Goto", 0 }; /* Try to figure out if this is really an EXPLAIN statement. If this ** cannot be verified, return early. */ if( sqlite3_column_count(pSql)!=8 ){ p->cMode = p->mode; return; } zSql = sqlite3_sql(pSql); if( zSql==0 ) return; for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); if( sqlite3_strnicmp(z, "explain", 7) ){ p->cMode = p->mode; return; } for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ int i; int iAddr = sqlite3_column_int(pSql, 0); const char *zOp = (const char*)sqlite3_column_text(pSql, 1); /* Set p2 to the P2 field of the current opcode. Then, assuming that ** p2 is an instruction address, set variable p2op to the index of that ** instruction in the aiIndent[] array. p2 and p2op may be different if ** the current instruction is part of a sub-program generated by an ** SQL trigger or foreign key. */ int p2 = sqlite3_column_int(pSql, 3); int p2op = (p2 + (iOp-iAddr)); /* Grow the p->aiIndent array as required */ if( iOp>=nAlloc ){ if( iOp==0 ){ /* Do further verfication that this is explain output. Abort if ** it is not */ static const char *explainCols[] = { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; int jj; for(jj=0; jj<ArraySize(explainCols); jj++){ if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ p->cMode = p->mode; sqlite3_reset(pSql); return; } } } nAlloc += 100; p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); } abYield[iOp] = str_in_array(zOp, azYield); p->aiIndent[iOp] = 0; p->nIndent = iOp+1; if( str_in_array(zOp, azNext) ){ for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; } if( str_in_array(zOp, azGoto) && p2op<p->nIndent && (abYield[p2op] || sqlite3_column_int(pSql, 2)) ){ for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; } } p->iIndent = 0; sqlite3_free(abYield); sqlite3_reset(pSql); } /* ** Free the array allocated by explain_data_prepare(). */ static void explain_data_delete(ShellState *p){ sqlite3_free(p->aiIndent); p->aiIndent = 0; p->nIndent = 0; p->iIndent = 0; } /* ** Disable and restore .wheretrace and .selecttrace settings. */ #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) extern int sqlite3SelectTrace; static int savedSelectTrace; #endif #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) extern int sqlite3WhereTrace; static int savedWhereTrace; #endif static void disable_debug_trace_modes(void){ #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) savedSelectTrace = sqlite3SelectTrace; sqlite3SelectTrace = 0; #endif #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) savedWhereTrace = sqlite3WhereTrace; sqlite3WhereTrace = 0; #endif } static void restore_debug_trace_modes(void){ #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) sqlite3SelectTrace = savedSelectTrace; #endif #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) sqlite3WhereTrace = savedWhereTrace; #endif } /* ** Run a prepared statement */ static void exec_prepared_stmt( ShellState *pArg, /* Pointer to ShellState */ sqlite3_stmt *pStmt /* Statment to run */ ){ int rc; /* perform the first step. this will tell us if we ** have a result set or not and how wide it is. */ rc = sqlite3_step(pStmt); /* if we have a result set... */ if( SQLITE_ROW == rc ){ /* allocate space for col name ptr, value ptr, and type */ int nCol = sqlite3_column_count(pStmt); void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); if( !pData ){ rc = SQLITE_NOMEM; }else{ char **azCols = (char **)pData; /* Names of result columns */ char **azVals = &azCols[nCol]; /* Results */ int *aiTypes = (int *)&azVals[nCol]; /* Result types */ int i, x; assert(sizeof(int) <= sizeof(char *)); /* save off ptrs to column names */ for(i=0; i<nCol; i++){ azCols[i] = (char *)sqlite3_column_name(pStmt, i); } do{ /* extract the data and data types */ for(i=0; i<nCol; i++){ aiTypes[i] = x = sqlite3_column_type(pStmt, i); if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){ azVals[i] = ""; }else{ azVals[i] = (char*)sqlite3_column_text(pStmt, i); } if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ rc = SQLITE_NOMEM; break; /* from for */ } } /* end for */ /* if data and types extracted successfully... */ if( SQLITE_ROW == rc ){ /* call the supplied callback with the result row data */ if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ rc = SQLITE_ABORT; }else{ rc = sqlite3_step(pStmt); } } } while( SQLITE_ROW == rc ); sqlite3_free(pData); } } } #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** This function is called to process SQL if the previous shell command ** was ".expert". It passes the SQL in the second argument directly to ** the sqlite3expert object. ** ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error ** code. In this case, (*pzErr) may be set to point to a buffer containing ** an English language error message. It is the responsibility of the ** caller to eventually free this buffer using sqlite3_free(). */ static int expertHandleSQL( ShellState *pState, const char *zSql, char **pzErr ){ assert( pState->expert.pExpert ); assert( pzErr==0 || *pzErr==0 ); return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); } /* ** This function is called either to silently clean up the object ** created by the ".expert" command (if bCancel==1), or to generate a ** report from it and then clean it up (if bCancel==0). ** ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error ** code. In this case, (*pzErr) may be set to point to a buffer containing ** an English language error message. It is the responsibility of the ** caller to eventually free this buffer using sqlite3_free(). */ static int expertFinish( ShellState *pState, int bCancel, char **pzErr ){ int rc = SQLITE_OK; sqlite3expert *p = pState->expert.pExpert; assert( p ); assert( bCancel || pzErr==0 || *pzErr==0 ); if( bCancel==0 ){ FILE *out = pState->out; int bVerbose = pState->expert.bVerbose; rc = sqlite3_expert_analyze(p, pzErr); if( rc==SQLITE_OK ){ int nQuery = sqlite3_expert_count(p); int i; if( bVerbose ){ const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); raw_printf(out, "-- Candidates -----------------------------\n"); raw_printf(out, "%s\n", zCand); } for(i=0; i<nQuery; i++){ const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); if( zIdx==0 ) zIdx = "(no new indexes)\n"; if( bVerbose ){ raw_printf(out, "-- Query %d --------------------------------\n",i+1); raw_printf(out, "%s\n\n", zSql); } raw_printf(out, "%s\n", zIdx); raw_printf(out, "%s\n", zEQP); } } } sqlite3_expert_destroy(p); pState->expert.pExpert = 0; return rc; } /* ** Implementation of ".expert" dot command. */ static int expertDotCommand( ShellState *pState, /* Current shell tool state */ char **azArg, /* Array of arguments passed to dot command */ int nArg /* Number of entries in azArg[] */ ){ int rc = SQLITE_OK; char *zErr = 0; int i; int iSample = 0; assert( pState->expert.pExpert==0 ); memset(&pState->expert, 0, sizeof(ExpertInfo)); for(i=1; rc==SQLITE_OK && i<nArg; i++){ char *z = azArg[i]; int n; if( z[0]=='-' && z[1]=='-' ) z++; n = strlen30(z); if( n>=2 && 0==strncmp(z, "-verbose", n) ){ pState->expert.bVerbose = 1; } else if( n>=2 && 0==strncmp(z, "-sample", n) ){ if( i==(nArg-1) ){ raw_printf(stderr, "option requires an argument: %s\n", z); rc = SQLITE_ERROR; }else{ iSample = (int)integerValue(azArg[++i]); if( iSample<0 || iSample>100 ){ raw_printf(stderr, "value out of range: %s\n", azArg[i]); rc = SQLITE_ERROR; } } } else{ raw_printf(stderr, "unknown option: %s\n", z); rc = SQLITE_ERROR; } } if( rc==SQLITE_OK ){ pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); if( pState->expert.pExpert==0 ){ raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr); rc = SQLITE_ERROR; }else{ sqlite3_expert_config( pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample ); } } return rc; } #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ /* ** Execute a statement or set of statements. Print ** any result rows/columns depending on the current mode ** set via the supplied callback. ** ** This is very similar to SQLite's built-in sqlite3_exec() ** function except it takes a slightly different callback ** and callback data argument. */ static int shell_exec( ShellState *pArg, /* Pointer to ShellState */ const char *zSql, /* SQL to be evaluated */ char **pzErrMsg /* Error msg written here */ ){ sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ int rc = SQLITE_OK; /* Return Code */ int rc2; const char *zLeftover; /* Tail of unprocessed SQL */ sqlite3 *db = pArg->db; if( pzErrMsg ){ *pzErrMsg = NULL; } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pArg->expert.pExpert ){ rc = expertHandleSQL(pArg, zSql, pzErrMsg); return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); } #endif while( zSql[0] && (SQLITE_OK == rc) ){ static const char *zStmtSql; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); if( SQLITE_OK != rc ){ if( pzErrMsg ){ *pzErrMsg = save_err_msg(db); } }else{ if( !pStmt ){ /* this happens for a comment or white-space */ zSql = zLeftover; while( IsSpace(zSql[0]) ) zSql++; continue; } zStmtSql = sqlite3_sql(pStmt); if( zStmtSql==0 ) zStmtSql = ""; while( IsSpace(zStmtSql[0]) ) zStmtSql++; /* save off the prepared statment handle and reset row count */ if( pArg ){ pArg->pStmt = pStmt; pArg->cnt = 0; } /* echo the sql statement if echo on */ if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){ utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); } /* Show the EXPLAIN QUERY PLAN if .eqp is on */ if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){ sqlite3_stmt *pExplain; char *zEQP; int triggerEQP = 0; disable_debug_trace_modes(); sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); if( pArg->autoEQP>=AUTOEQP_trigger ){ sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); } zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); if( rc==SQLITE_OK ){ while( sqlite3_step(pExplain)==SQLITE_ROW ){ raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0)); raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1)); raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2)); utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3)); } } sqlite3_finalize(pExplain); sqlite3_free(zEQP); if( pArg->autoEQP>=AUTOEQP_full ){ /* Also do an EXPLAIN for ".eqp full" mode */ zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); if( rc==SQLITE_OK ){ pArg->cMode = MODE_Explain; explain_data_prepare(pArg, pExplain); exec_prepared_stmt(pArg, pExplain); explain_data_delete(pArg); } sqlite3_finalize(pExplain); sqlite3_free(zEQP); } if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); /* Reprepare pStmt before reactiving trace modes */ sqlite3_finalize(pStmt); sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); } restore_debug_trace_modes(); } if( pArg ){ pArg->cMode = pArg->mode; if( pArg->autoExplain && sqlite3_column_count(pStmt)==8 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0 ){ pArg->cMode = MODE_Explain; } /* If the shell is currently in ".explain" mode, gather the extra ** data required to add indents to the output.*/ if( pArg->cMode==MODE_Explain ){ explain_data_prepare(pArg, pStmt); } } exec_prepared_stmt(pArg, pStmt); explain_data_delete(pArg); /* print usage stats if stats on */ if( pArg && pArg->statsOn ){ display_stats(db, pArg, 0); } /* print loop-counters if required */ if( pArg && pArg->scanstatsOn ){ display_scanstats(db, pArg); } /* Finalize the statement just executed. If this fails, save a ** copy of the error message. Otherwise, set zSql to point to the ** next statement to execute. */ rc2 = sqlite3_finalize(pStmt); if( rc!=SQLITE_NOMEM ) rc = rc2; if( rc==SQLITE_OK ){ zSql = zLeftover; while( IsSpace(zSql[0]) ) zSql++; }else if( pzErrMsg ){ *pzErrMsg = save_err_msg(db); } /* clear saved stmt handle */ if( pArg ){ pArg->pStmt = NULL; } } } /* end while */ return rc; } /* ** Release memory previously allocated by tableColumnList(). */ static void freeColumnList(char **azCol){ int i; for(i=1; azCol[i]; i++){ sqlite3_free(azCol[i]); } /* azCol[0] is a static string */ sqlite3_free(azCol); } /* ** Return a list of pointers to strings which are the names of all ** columns in table zTab. The memory to hold the names is dynamically ** allocated and must be released by the caller using a subsequent call ** to freeColumnList(). ** ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid ** value that needs to be preserved, then azCol[0] is filled in with the ** name of the rowid column. ** ** The first regular column in the table is azCol[1]. The list is terminated ** by an entry with azCol[i]==0. */ static char **tableColumnList(ShellState *p, const char *zTab){ char **azCol = 0; sqlite3_stmt *pStmt; char *zSql; int nCol = 0; int nAlloc = 0; int nPK = 0; /* Number of PRIMARY KEY columns seen */ int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); int rc; zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); if( rc ) return 0; while( sqlite3_step(pStmt)==SQLITE_ROW ){ if( nCol>=nAlloc-2 ){ nAlloc = nAlloc*2 + nCol + 10; azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); if( azCol==0 ){ raw_printf(stderr, "Error: out of memory\n"); exit(1); } } azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); if( sqlite3_column_int(pStmt, 5) ){ nPK++; if( nPK==1 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), "INTEGER")==0 ){ isIPK = 1; }else{ isIPK = 0; } } } sqlite3_finalize(pStmt); if( azCol==0 ) return 0; azCol[0] = 0; azCol[nCol+1] = 0; /* The decision of whether or not a rowid really needs to be preserved ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve ** rowids on tables where the rowid is inaccessible because there are other ** columns in the table named "rowid", "_rowid_", and "oid". */ if( preserveRowid && isIPK ){ /* If a single PRIMARY KEY column with type INTEGER was seen, then it ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID ** table or a INTEGER PRIMARY KEY DESC column, neither of which are ** ROWID aliases. To distinguish these cases, check to see if ** there is a "pk" entry in "PRAGMA index_list". There will be ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. */ zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" " WHERE origin='pk'", zTab); rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); if( rc ){ freeColumnList(azCol); return 0; } rc = sqlite3_step(pStmt); sqlite3_finalize(pStmt); preserveRowid = rc==SQLITE_ROW; } if( preserveRowid ){ /* Only preserve the rowid if we can find a name to use for the ** rowid */ static char *azRowid[] = { "rowid", "_rowid_", "oid" }; int i, j; for(j=0; j<3; j++){ for(i=1; i<=nCol; i++){ if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; } if( i>nCol ){ /* At this point, we know that azRowid[j] is not the name of any ** ordinary column in the table. Verify that azRowid[j] is a valid ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID ** tables will fail this last check */ rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; break; } } } return azCol; } /* ** Toggle the reverse_unordered_selects setting. */ static void toggleSelectOrder(sqlite3 *db){ sqlite3_stmt *pStmt = 0; int iSetting = 0; char zStmt[100]; sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); if( sqlite3_step(pStmt)==SQLITE_ROW ){ iSetting = sqlite3_column_int(pStmt, 0); } sqlite3_finalize(pStmt); sqlite3_snprintf(sizeof(zStmt), zStmt, "PRAGMA reverse_unordered_selects(%d)", !iSetting); sqlite3_exec(db, zStmt, 0, 0, 0); } /* ** This is a different callback routine used for dumping the database. ** Each row received by this callback consists of a table name, ** the table type ("index" or "table") and SQL to create the table. ** This routine should print text sufficient to recreate the table. */ static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ int rc; const char *zTable; const char *zType; const char *zSql; ShellState *p = (ShellState *)pArg; UNUSED_PARAMETER(azNotUsed); if( nArg!=3 || azArg==0 ) return 0; zTable = azArg[0]; zType = azArg[1]; zSql = azArg[2]; if( strcmp(zTable, "sqlite_sequence")==0 ){ raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ raw_printf(p->out, "ANALYZE sqlite_master;\n"); }else if( strncmp(zTable, "sqlite_", 7)==0 ){ return 0; }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ char *zIns; if( !p->writableSchema ){ raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); p->writableSchema = 1; } zIns = sqlite3_mprintf( "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" "VALUES('table','%q','%q',0,'%q');", zTable, zTable, zSql); utf8_printf(p->out, "%s\n", zIns); sqlite3_free(zIns); return 0; }else{ printSchemaLine(p->out, zSql, ";\n"); } if( strcmp(zType, "table")==0 ){ ShellText sSelect; ShellText sTable; char **azCol; int i; char *savedDestTable; int savedMode; azCol = tableColumnList(p, zTable); if( azCol==0 ){ p->nErr++; return 0; } /* Always quote the table name, even if it appears to be pure ascii, ** in case it is a keyword. Ex: INSERT INTO "table" ... */ initText(&sTable); appendText(&sTable, zTable, quoteChar(zTable)); /* If preserving the rowid, add a column list after the table name. ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" ** instead of the usual "INSERT INTO tab VALUES(...)". */ if( azCol[0] ){ appendText(&sTable, "(", 0); appendText(&sTable, azCol[0], 0); for(i=1; azCol[i]; i++){ appendText(&sTable, ",", 0); appendText(&sTable, azCol[i], quoteChar(azCol[i])); } appendText(&sTable, ")", 0); } /* Build an appropriate SELECT statement */ initText(&sSelect); appendText(&sSelect, "SELECT ", 0); if( azCol[0] ){ appendText(&sSelect, azCol[0], 0); appendText(&sSelect, ",", 0); } for(i=1; azCol[i]; i++){ appendText(&sSelect, azCol[i], quoteChar(azCol[i])); if( azCol[i+1] ){ appendText(&sSelect, ",", 0); } } freeColumnList(azCol); appendText(&sSelect, " FROM ", 0); appendText(&sSelect, zTable, quoteChar(zTable)); savedDestTable = p->zDestTable; savedMode = p->mode; p->zDestTable = sTable.z; p->mode = p->cMode = MODE_Insert; rc = shell_exec(p, sSelect.z, 0); if( (rc&0xff)==SQLITE_CORRUPT ){ raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); toggleSelectOrder(p->db); shell_exec(p, sSelect.z, 0); toggleSelectOrder(p->db); } p->zDestTable = savedDestTable; p->mode = savedMode; freeText(&sTable); freeText(&sSelect); if( rc ) p->nErr++; } return 0; } /* ** Run zQuery. Use dump_callback() as the callback routine so that ** the contents of the query are output as SQL statements. ** ** If we get a SQLITE_CORRUPT error, rerun the query after appending ** "ORDER BY rowid DESC" to the end. */ static int run_schema_dump_query( ShellState *p, const char *zQuery ){ int rc; char *zErr = 0; rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); if( rc==SQLITE_CORRUPT ){ char *zQ2; int len = strlen30(zQuery); raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); if( zErr ){ utf8_printf(p->out, "/****** %s ******/\n", zErr); sqlite3_free(zErr); zErr = 0; } zQ2 = malloc( len+100 ); if( zQ2==0 ) return rc; sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); if( rc ){ utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); }else{ rc = SQLITE_CORRUPT; } sqlite3_free(zErr); free(zQ2); } return rc; } /* ** Text of a help message */ static char zHelp[] = #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) ".archive ... Manage SQL archives: \".archive --help\" for details\n" #endif #ifndef SQLITE_OMIT_AUTHORIZATION ".auth ON|OFF Show authorizer callbacks\n" #endif ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n" ".bail on|off Stop after hitting an error. Default OFF\n" ".binary on|off Turn binary output on or off. Default OFF\n" ".cd DIRECTORY Change the working directory to DIRECTORY\n" ".changes on|off Show number of rows changed by SQL\n" ".check GLOB Fail if output since .testcase does not match\n" ".clone NEWDB Clone data into NEWDB from the existing database\n" ".databases List names and files of attached databases\n" ".dbinfo ?DB? Show status information about the database\n" ".dump ?TABLE? ... Dump the database in an SQL text format\n" " If TABLE specified, only dump tables matching\n" " LIKE pattern TABLE.\n" ".echo on|off Turn command echo on or off\n" ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n" ".excel Display the output of next command in a spreadsheet\n" ".exit Exit this program\n" ".expert EXPERIMENTAL. Suggest indexes for specified queries\n" /* Because explain mode comes on automatically now, the ".explain" mode ** is removed from the help screen. It is still supported for legacy, however */ /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/ ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n" ".headers on|off Turn display of headers on or off\n" ".help Show this message\n" ".import FILE TABLE Import data from FILE into TABLE\n" #ifndef SQLITE_OMIT_TEST_CONTROL ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n" #endif ".indexes ?TABLE? Show names of all indexes\n" " If TABLE specified, only show indexes for tables\n" " matching LIKE pattern TABLE.\n" #ifdef SQLITE_ENABLE_IOTRACE ".iotrace FILE Enable I/O diagnostic logging to FILE\n" #endif ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n" ".lint OPTIONS Report potential schema issues. Options:\n" " fkey-indexes Find missing foreign key indexes\n" #ifndef SQLITE_OMIT_LOAD_EXTENSION ".load FILE ?ENTRY? Load an extension library\n" #endif ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n" ".mode MODE ?TABLE? Set output mode where MODE is one of:\n" " ascii Columns/rows delimited by 0x1F and 0x1E\n" " csv Comma-separated values\n" " column Left-aligned columns. (See .width)\n" " html HTML <table> code\n" " insert SQL insert statements for TABLE\n" " line One value per line\n" " list Values delimited by \"|\"\n" " quote Escape answers as for SQL\n" " tabs Tab-separated values\n" " tcl TCL list elements\n" ".nullvalue STRING Use STRING in place of NULL values\n" ".once (-e|-x|FILE) Output for the next SQL command only to FILE\n" " or invoke system text editor (-e) or spreadsheet (-x)\n" " on the output.\n" ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n" " The --new option starts with an empty file\n" " Other options: --readonly --append --zip\n" ".output ?FILE? Send output to FILE or stdout\n" ".print STRING... Print literal STRING\n" ".prompt MAIN CONTINUE Replace the standard prompts\n" ".quit Exit this program\n" ".read FILENAME Execute SQL in FILENAME\n" ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n" ".save FILE Write in-memory database into FILE\n" ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n" ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n" " Add --indent for pretty-printing\n" ".selftest ?--init? Run tests defined in the SELFTEST table\n" ".separator COL ?ROW? Change the column separator and optionally the row\n" " separator for both the output mode and .import\n" #if defined(SQLITE_ENABLE_SESSION) ".session CMD ... Create or control sessions\n" #endif ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n" #ifndef SQLITE_NOHAVE_SYSTEM ".shell CMD ARGS... Run CMD ARGS... in a system shell\n" #endif ".show Show the current values for various settings\n" ".stats ?on|off? Show stats or turn stats on or off\n" #ifndef SQLITE_NOHAVE_SYSTEM ".system CMD ARGS... Run CMD ARGS... in a system shell\n" #endif ".tables ?TABLE? List names of tables\n" " If TABLE specified, only list tables matching\n" " LIKE pattern TABLE.\n" ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n" ".timeout MS Try opening locked tables for MS milliseconds\n" ".timer on|off Turn SQL timer on or off\n" ".trace FILE|off Output each SQL statement as it is run\n" ".vfsinfo ?AUX? Information about the top-level VFS\n" ".vfslist List all available VFSes\n" ".vfsname ?AUX? Print the name of the VFS stack\n" ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n" " Negative values right-justify\n" ; #if defined(SQLITE_ENABLE_SESSION) /* ** Print help information for the ".sessions" command */ void session_help(ShellState *p){ raw_printf(p->out, ".session ?NAME? SUBCOMMAND ?ARGS...?\n" "If ?NAME? is omitted, the first defined session is used.\n" "Subcommands:\n" " attach TABLE Attach TABLE\n" " changeset FILE Write a changeset into FILE\n" " close Close one session\n" " enable ?BOOLEAN? Set or query the enable bit\n" " filter GLOB... Reject tables matching GLOBs\n" " indirect ?BOOLEAN? Mark or query the indirect status\n" " isempty Query whether the session is empty\n" " list List currently open session names\n" " open DB NAME Open a new session on DB\n" " patchset FILE Write a patchset into FILE\n" ); } #endif /* Forward reference */ static int process_input(ShellState *p, FILE *in); /* ** Read the content of file zName into memory obtained from sqlite3_malloc64() ** and return a pointer to the buffer. The caller is responsible for freeing ** the memory. ** ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes ** read. ** ** For convenience, a nul-terminator byte is always appended to the data read ** from the file before the buffer is returned. This byte is not included in ** the final value of (*pnByte), if applicable. ** ** NULL is returned if any error is encountered. The final value of *pnByte ** is undefined in this case. */ static char *readFile(const char *zName, int *pnByte){ FILE *in = fopen(zName, "rb"); long nIn; size_t nRead; char *pBuf; if( in==0 ) return 0; fseek(in, 0, SEEK_END); nIn = ftell(in); rewind(in); pBuf = sqlite3_malloc64( nIn+1 ); if( pBuf==0 ) return 0; nRead = fread(pBuf, nIn, 1, in); fclose(in); if( nRead!=1 ){ sqlite3_free(pBuf); return 0; } pBuf[nIn] = 0; if( pnByte ) *pnByte = nIn; return pBuf; } #if defined(SQLITE_ENABLE_SESSION) /* ** Close a single OpenSession object and release all of its associated ** resources. */ static void session_close(OpenSession *pSession){ int i; sqlite3session_delete(pSession->p); sqlite3_free(pSession->zName); for(i=0; i<pSession->nFilter; i++){ sqlite3_free(pSession->azFilter[i]); } sqlite3_free(pSession->azFilter); memset(pSession, 0, sizeof(OpenSession)); } #endif /* ** Close all OpenSession objects and release all associated resources. */ #if defined(SQLITE_ENABLE_SESSION) static void session_close_all(ShellState *p){ int i; for(i=0; i<p->nSession; i++){ session_close(&p->aSession[i]); } p->nSession = 0; } #else # define session_close_all(X) #endif /* ** Implementation of the xFilter function for an open session. Omit ** any tables named by ".session filter" but let all other table through. */ #if defined(SQLITE_ENABLE_SESSION) static int session_filter(void *pCtx, const char *zTab){ OpenSession *pSession = (OpenSession*)pCtx; int i; for(i=0; i<pSession->nFilter; i++){ if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; } return 1; } #endif /* ** Try to deduce the type of file for zName based on its content. Return ** one of the SHELL_OPEN_* constants. ** ** If the file does not exist or is empty but its name looks like a ZIP ** archive and the dfltZip flag is true, then assume it is a ZIP archive. ** Otherwise, assume an ordinary database regardless of the filename if ** the type cannot be determined from content. */ static int deduceDatabaseType(const char *zName, int dfltZip){ FILE *f = fopen(zName, "rb"); size_t n; int rc = SHELL_OPEN_UNSPEC; char zBuf[100]; if( f==0 ){ if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ) return SHELL_OPEN_ZIPFILE; return SHELL_OPEN_NORMAL; } fseek(f, -25, SEEK_END); n = fread(zBuf, 25, 1, f); if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ rc = SHELL_OPEN_APPENDVFS; }else{ fseek(f, -22, SEEK_END); n = fread(zBuf, 22, 1, f); if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 && zBuf[3]==0x06 ){ rc = SHELL_OPEN_ZIPFILE; }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ return SHELL_OPEN_ZIPFILE; } } fclose(f); return rc; } /* ** Make sure the database is open. If it is not, then open it. If ** the database fails to open, print an error message and exit. */ static void open_db(ShellState *p, int keepAlive){ if( p->db==0 ){ sqlite3_initialize(); if( p->openMode==SHELL_OPEN_UNSPEC && access(p->zDbFilename,0)==0 ){ p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 0); } switch( p->openMode ){ case SHELL_OPEN_APPENDVFS: { sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs"); break; } case SHELL_OPEN_ZIPFILE: { sqlite3_open(":memory:", &p->db); break; } case SHELL_OPEN_READONLY: { sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0); break; } case SHELL_OPEN_UNSPEC: case SHELL_OPEN_NORMAL: { sqlite3_open(p->zDbFilename, &p->db); break; } } globalDb = p->db; if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", p->zDbFilename, sqlite3_errmsg(p->db)); if( keepAlive ) return; exit(1); } #ifndef SQLITE_OMIT_LOAD_EXTENSION sqlite3_enable_load_extension(p->db, 1); #endif sqlite3_fileio_init(p->db, 0, 0); sqlite3_shathree_init(p->db, 0, 0); sqlite3_completion_init(p->db, 0, 0); #ifdef SQLITE_HAVE_ZLIB sqlite3_zipfile_init(p->db, 0, 0); sqlite3_sqlar_init(p->db, 0, 0); #endif sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, shellAddSchemaName, 0, 0); sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, shellModuleSchema, 0, 0); sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, shellPutsFunc, 0, 0); #ifndef SQLITE_NOHAVE_SYSTEM sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, editFunc, 0, 0); sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, editFunc, 0, 0); #endif if( p->openMode==SHELL_OPEN_ZIPFILE ){ char *zSql = sqlite3_mprintf( "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename); sqlite3_exec(p->db, zSql, 0, 0, 0); sqlite3_free(zSql); } } } #if HAVE_READLINE || HAVE_EDITLINE /* ** Readline completion callbacks */ static char *readline_completion_generator(const char *text, int state){ static sqlite3_stmt *pStmt = 0; char *zRet; if( state==0 ){ char *zSql; sqlite3_finalize(pStmt); zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" " FROM completion(%Q) ORDER BY 1", text); sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); sqlite3_free(zSql); } if( sqlite3_step(pStmt)==SQLITE_ROW ){ zRet = strdup((const char*)sqlite3_column_text(pStmt, 0)); }else{ sqlite3_finalize(pStmt); pStmt = 0; zRet = 0; } return zRet; } static char **readline_completion(const char *zText, int iStart, int iEnd){ rl_attempted_completion_over = 1; return rl_completion_matches(zText, readline_completion_generator); } #elif HAVE_LINENOISE /* ** Linenoise completion callback */ static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ int nLine = strlen30(zLine); int i, iStart; sqlite3_stmt *pStmt = 0; char *zSql; char zBuf[1000]; if( nLine>sizeof(zBuf)-30 ) return; if( zLine[0]=='.' ) return; for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} if( i==nLine-1 ) return; iStart = i+1; memcpy(zBuf, zLine, iStart); zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" " FROM completion(%Q,%Q) ORDER BY 1", &zLine[iStart], zLine); sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); sqlite3_free(zSql); sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ while( sqlite3_step(pStmt)==SQLITE_ROW ){ const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); int nCompletion = sqlite3_column_bytes(pStmt, 0); if( iStart+nCompletion < sizeof(zBuf)-1 ){ memcpy(zBuf+iStart, zCompletion, nCompletion+1); linenoiseAddCompletion(lc, zBuf); } } sqlite3_finalize(pStmt); } #endif /* ** Do C-language style dequoting. ** ** \a -> alarm ** \b -> backspace ** \t -> tab ** \n -> newline ** \v -> vertical tab ** \f -> form feed ** \r -> carriage return ** \s -> space ** \" -> " ** \' -> ' ** \\ -> backslash ** \NNN -> ascii character NNN in octal */ static void resolve_backslashes(char *z){ int i, j; char c; while( *z && *z!='\\' ) z++; for(i=j=0; (c = z[i])!=0; i++, j++){ if( c=='\\' && z[i+1]!=0 ){ c = z[++i]; if( c=='a' ){ c = '\a'; }else if( c=='b' ){ c = '\b'; }else if( c=='t' ){ c = '\t'; }else if( c=='n' ){ c = '\n'; }else if( c=='v' ){ c = '\v'; }else if( c=='f' ){ c = '\f'; }else if( c=='r' ){ c = '\r'; }else if( c=='"' ){ c = '"'; }else if( c=='\'' ){ c = '\''; }else if( c=='\\' ){ c = '\\'; }else if( c>='0' && c<='7' ){ c -= '0'; if( z[i+1]>='0' && z[i+1]<='7' ){ i++; c = (c<<3) + z[i] - '0'; if( z[i+1]>='0' && z[i+1]<='7' ){ i++; c = (c<<3) + z[i] - '0'; } } } } z[j] = c; } if( j<i ) z[j] = 0; } /* ** Interpret zArg as either an integer or a boolean value. Return 1 or 0 ** for TRUE and FALSE. Return the integer value if appropriate. */ static int booleanValue(const char *zArg){ int i; if( zArg[0]=='0' && zArg[1]=='x' ){ for(i=2; hexDigitValue(zArg[i])>=0; i++){} }else{ for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} } if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ return 1; } if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ return 0; } utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg); return 0; } /* ** Set or clear a shell flag according to a boolean value. */ static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ if( booleanValue(zArg) ){ ShellSetFlag(p, mFlag); }else{ ShellClearFlag(p, mFlag); } } /* ** Close an output file, assuming it is not stderr or stdout */ static void output_file_close(FILE *f){ if( f && f!=stdout && f!=stderr ) fclose(f); } /* ** Try to open an output file. The names "stdout" and "stderr" are ** recognized and do the right thing. NULL is returned if the output ** filename is "off". */ static FILE *output_file_open(const char *zFile, int bTextMode){ FILE *f; if( strcmp(zFile,"stdout")==0 ){ f = stdout; }else if( strcmp(zFile, "stderr")==0 ){ f = stderr; }else if( strcmp(zFile, "off")==0 ){ f = 0; }else{ f = fopen(zFile, bTextMode ? "w" : "wb"); if( f==0 ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); } } return f; } #if !defined(SQLITE_UNTESTABLE) #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) /* ** A routine for handling output from sqlite3_trace(). */ static int sql_trace_callback( unsigned mType, void *pArg, void *pP, void *pX ){ FILE *f = (FILE*)pArg; UNUSED_PARAMETER(mType); UNUSED_PARAMETER(pP); if( f ){ const char *z = (const char*)pX; int i = strlen30(z); while( i>0 && z[i-1]==';' ){ i--; } utf8_printf(f, "%.*s;\n", i, z); } return 0; } #endif #endif /* ** A no-op routine that runs with the ".breakpoint" doc-command. This is ** a useful spot to set a debugger breakpoint. */ static void test_breakpoint(void){ static int nCall = 0; nCall++; } /* ** An object used to read a CSV and other files for import. */ typedef struct ImportCtx ImportCtx; struct ImportCtx { const char *zFile; /* Name of the input file */ FILE *in; /* Read the CSV text from this input stream */ char *z; /* Accumulated text for a field */ int n; /* Number of bytes in z */ int nAlloc; /* Space allocated for z[] */ int nLine; /* Current line number */ int bNotFirst; /* True if one or more bytes already read */ int cTerm; /* Character that terminated the most recent field */ int cColSep; /* The column separator character. (Usually ",") */ int cRowSep; /* The row separator character. (Usually "\n") */ }; /* Append a single byte to z[] */ static void import_append_char(ImportCtx *p, int c){ if( p->n+1>=p->nAlloc ){ p->nAlloc += p->nAlloc + 100; p->z = sqlite3_realloc64(p->z, p->nAlloc); if( p->z==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } } p->z[p->n++] = (char)c; } /* Read a single field of CSV text. Compatible with rfc4180 and extended ** with the option of having a separator other than ",". ** ** + Input comes from p->in. ** + Store results in p->z of length p->n. Space to hold p->z comes ** from sqlite3_malloc64(). ** + Use p->cSep as the column separator. The default is ",". ** + Use p->rSep as the row separator. The default is "\n". ** + Keep track of the line number in p->nLine. ** + Store the character that terminates the field in p->cTerm. Store ** EOF on end-of-file. ** + Report syntax errors on stderr */ static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ int c; int cSep = p->cColSep; int rSep = p->cRowSep; p->n = 0; c = fgetc(p->in); if( c==EOF || seenInterrupt ){ p->cTerm = EOF; return 0; } if( c=='"' ){ int pc, ppc; int startLine = p->nLine; int cQuote = c; pc = ppc = 0; while( 1 ){ c = fgetc(p->in); if( c==rSep ) p->nLine++; if( c==cQuote ){ if( pc==cQuote ){ pc = 0; continue; } } if( (c==cSep && pc==cQuote) || (c==rSep && pc==cQuote) || (c==rSep && pc=='\r' && ppc==cQuote) || (c==EOF && pc==cQuote) ){ do{ p->n--; }while( p->z[p->n]!=cQuote ); p->cTerm = c; break; } if( pc==cQuote && c!='\r' ){ utf8_printf(stderr, "%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote); } if( c==EOF ){ utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", p->zFile, startLine, cQuote); p->cTerm = c; break; } import_append_char(p, c); ppc = pc; pc = c; } }else{ /* If this is the first field being parsed and it begins with the ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ if( (c&0xff)==0xef && p->bNotFirst==0 ){ import_append_char(p, c); c = fgetc(p->in); if( (c&0xff)==0xbb ){ import_append_char(p, c); c = fgetc(p->in); if( (c&0xff)==0xbf ){ p->bNotFirst = 1; p->n = 0; return csv_read_one_field(p); } } } while( c!=EOF && c!=cSep && c!=rSep ){ import_append_char(p, c); c = fgetc(p->in); } if( c==rSep ){ p->nLine++; if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; } p->cTerm = c; } if( p->z ) p->z[p->n] = 0; p->bNotFirst = 1; return p->z; } /* Read a single field of ASCII delimited text. ** ** + Input comes from p->in. ** + Store results in p->z of length p->n. Space to hold p->z comes ** from sqlite3_malloc64(). ** + Use p->cSep as the column separator. The default is "\x1F". ** + Use p->rSep as the row separator. The default is "\x1E". ** + Keep track of the row number in p->nLine. ** + Store the character that terminates the field in p->cTerm. Store ** EOF on end-of-file. ** + Report syntax errors on stderr */ static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ int c; int cSep = p->cColSep; int rSep = p->cRowSep; p->n = 0; c = fgetc(p->in); if( c==EOF || seenInterrupt ){ p->cTerm = EOF; return 0; } while( c!=EOF && c!=cSep && c!=rSep ){ import_append_char(p, c); c = fgetc(p->in); } if( c==rSep ){ p->nLine++; } p->cTerm = c; if( p->z ) p->z[p->n] = 0; return p->z; } /* ** Try to transfer data for table zTable. If an error is seen while ** moving forward, try to go backwards. The backwards movement won't ** work for WITHOUT ROWID tables. */ static void tryToCloneData( ShellState *p, sqlite3 *newDb, const char *zTable ){ sqlite3_stmt *pQuery = 0; sqlite3_stmt *pInsert = 0; char *zQuery = 0; char *zInsert = 0; int rc; int i, j, n; int nTable = strlen30(zTable); int k = 0; int cnt = 0; const int spinRate = 10000; zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); if( rc ){ utf8_printf(stderr, "Error %d: %s on [%s]\n", sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); goto end_data_xfer; } n = sqlite3_column_count(pQuery); zInsert = sqlite3_malloc64(200 + nTable + n*3); if( zInsert==0 ){ raw_printf(stderr, "out of memory\n"); goto end_data_xfer; } sqlite3_snprintf(200+nTable,zInsert, "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); i = strlen30(zInsert); for(j=1; j<n; j++){ memcpy(zInsert+i, ",?", 2); i += 2; } memcpy(zInsert+i, ");", 3); rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); if( rc ){ utf8_printf(stderr, "Error %d: %s on [%s]\n", sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zQuery); goto end_data_xfer; } for(k=0; k<2; k++){ while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ for(i=0; i<n; i++){ switch( sqlite3_column_type(pQuery, i) ){ case SQLITE_NULL: { sqlite3_bind_null(pInsert, i+1); break; } case SQLITE_INTEGER: { sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); break; } case SQLITE_FLOAT: { sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); break; } case SQLITE_TEXT: { sqlite3_bind_text(pInsert, i+1, (const char*)sqlite3_column_text(pQuery,i), -1, SQLITE_STATIC); break; } case SQLITE_BLOB: { sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), sqlite3_column_bytes(pQuery,i), SQLITE_STATIC); break; } } } /* End for */ rc = sqlite3_step(pInsert); if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb)); } sqlite3_reset(pInsert); cnt++; if( (cnt%spinRate)==0 ){ printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); fflush(stdout); } } /* End while */ if( rc==SQLITE_DONE ) break; sqlite3_finalize(pQuery); sqlite3_free(zQuery); zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", zTable); rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); if( rc ){ utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); break; } } /* End for(k=0...) */ end_data_xfer: sqlite3_finalize(pQuery); sqlite3_finalize(pInsert); sqlite3_free(zQuery); sqlite3_free(zInsert); } /* ** Try to transfer all rows of the schema that match zWhere. For ** each row, invoke xForEach() on the object defined by that row. ** If an error is encountered while moving forward through the ** sqlite_master table, try again moving backwards. */ static void tryToCloneSchema( ShellState *p, sqlite3 *newDb, const char *zWhere, void (*xForEach)(ShellState*,sqlite3*,const char*) ){ sqlite3_stmt *pQuery = 0; char *zQuery = 0; int rc; const unsigned char *zName; const unsigned char *zSql; char *zErrMsg = 0; zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" " WHERE %s", zWhere); rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); if( rc ){ utf8_printf(stderr, "Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); goto end_schema_xfer; } while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ zName = sqlite3_column_text(pQuery, 0); zSql = sqlite3_column_text(pQuery, 1); printf("%s... ", zName); fflush(stdout); sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); if( zErrMsg ){ utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); sqlite3_free(zErrMsg); zErrMsg = 0; } if( xForEach ){ xForEach(p, newDb, (const char*)zName); } printf("done\n"); } if( rc!=SQLITE_DONE ){ sqlite3_finalize(pQuery); sqlite3_free(zQuery); zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" " WHERE %s ORDER BY rowid DESC", zWhere); rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); if( rc ){ utf8_printf(stderr, "Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); goto end_schema_xfer; } while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ zName = sqlite3_column_text(pQuery, 0); zSql = sqlite3_column_text(pQuery, 1); printf("%s... ", zName); fflush(stdout); sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); if( zErrMsg ){ utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); sqlite3_free(zErrMsg); zErrMsg = 0; } if( xForEach ){ xForEach(p, newDb, (const char*)zName); } printf("done\n"); } } end_schema_xfer: sqlite3_finalize(pQuery); sqlite3_free(zQuery); } /* ** Open a new database file named "zNewDb". Try to recover as much information ** as possible out of the main database (which might be corrupt) and write it ** into zNewDb. */ static void tryToClone(ShellState *p, const char *zNewDb){ int rc; sqlite3 *newDb = 0; if( access(zNewDb,0)==0 ){ utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); return; } rc = sqlite3_open(zNewDb, &newDb); if( rc ){ utf8_printf(stderr, "Cannot create output database: %s\n", sqlite3_errmsg(newDb)); }else{ sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); tryToCloneSchema(p, newDb, "type!='table'", 0); sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); } sqlite3_close(newDb); } /* ** Change the output file back to stdout. ** ** If the p->doXdgOpen flag is set, that means the output was being ** redirected to a temporary file named by p->zTempFile. In that case, ** launch start/open/xdg-open on that temporary file. */ static void output_reset(ShellState *p){ if( p->outfile[0]=='|' ){ #ifndef SQLITE_OMIT_POPEN pclose(p->out); #endif }else{ output_file_close(p->out); #ifndef SQLITE_NOHAVE_SYSTEM if( p->doXdgOpen ){ const char *zXdgOpenCmd = #if defined(_WIN32) "start"; #elif defined(__APPLE__) "open"; #else "xdg-open"; #endif char *zCmd; zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); if( system(zCmd) ){ utf8_printf(stderr, "Failed: [%s]\n", zCmd); } sqlite3_free(zCmd); outputModePop(p); p->doXdgOpen = 0; } #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ } p->outfile[0] = 0; p->out = stdout; } /* ** Run an SQL command and return the single integer result. */ static int db_int(ShellState *p, const char *zSql){ sqlite3_stmt *pStmt; int res = 0; sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ res = sqlite3_column_int(pStmt,0); } sqlite3_finalize(pStmt); return res; } /* ** Convert a 2-byte or 4-byte big-endian integer into a native integer */ static unsigned int get2byteInt(unsigned char *a){ return (a[0]<<8) + a[1]; } static unsigned int get4byteInt(unsigned char *a){ return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; } /* ** Implementation of the ".info" command. ** ** Return 1 on error, 2 to exit, and 0 otherwise. */ static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ static const struct { const char *zName; int ofst; } aField[] = { { "file change counter:", 24 }, { "database page count:", 28 }, { "freelist page count:", 36 }, { "schema cookie:", 40 }, { "schema format:", 44 }, { "default cache size:", 48 }, { "autovacuum top root:", 52 }, { "incremental vacuum:", 64 }, { "text encoding:", 56 }, { "user version:", 60 }, { "application id:", 68 }, { "software version:", 96 }, }; static const struct { const char *zName; const char *zSql; } aQuery[] = { { "number of tables:", "SELECT count(*) FROM %s WHERE type='table'" }, { "number of indexes:", "SELECT count(*) FROM %s WHERE type='index'" }, { "number of triggers:", "SELECT count(*) FROM %s WHERE type='trigger'" }, { "number of views:", "SELECT count(*) FROM %s WHERE type='view'" }, { "schema size:", "SELECT total(length(sql)) FROM %s" }, }; int i; char *zSchemaTab; char *zDb = nArg>=2 ? azArg[1] : "main"; sqlite3_stmt *pStmt = 0; unsigned char aHdr[100]; open_db(p, 0); if( p->db==0 ) return 1; sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", -1, &pStmt, 0); sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); if( sqlite3_step(pStmt)==SQLITE_ROW && sqlite3_column_bytes(pStmt,0)>100 ){ memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); sqlite3_finalize(pStmt); }else{ raw_printf(stderr, "unable to read database header\n"); sqlite3_finalize(pStmt); return 1; } i = get2byteInt(aHdr+16); if( i==1 ) i = 65536; utf8_printf(p->out, "%-20s %d\n", "database page size:", i); utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); for(i=0; i<ArraySize(aField); i++){ int ofst = aField[i].ofst; unsigned int val = get4byteInt(aHdr + ofst); utf8_printf(p->out, "%-20s %u", aField[i].zName, val); switch( ofst ){ case 56: { if( val==1 ) raw_printf(p->out, " (utf8)"); if( val==2 ) raw_printf(p->out, " (utf16le)"); if( val==3 ) raw_printf(p->out, " (utf16be)"); } } raw_printf(p->out, "\n"); } if( zDb==0 ){ zSchemaTab = sqlite3_mprintf("main.sqlite_master"); }else if( strcmp(zDb,"temp")==0 ){ zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master"); }else{ zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb); } for(i=0; i<ArraySize(aQuery); i++){ char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); int val = db_int(p, zSql); sqlite3_free(zSql); utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); } sqlite3_free(zSchemaTab); return 0; } /* ** Print the current sqlite3_errmsg() value to stderr and return 1. */ static int shellDatabaseError(sqlite3 *db){ const char *zErr = sqlite3_errmsg(db); utf8_printf(stderr, "Error: %s\n", zErr); return 1; } /* ** Print an out-of-memory message to stderr and return 1. */ static int shellNomemError(void){ raw_printf(stderr, "Error: out of memory\n"); return 1; } /* ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE ** if they match and FALSE (0) if they do not match. ** ** Globbing rules: ** ** '*' Matches any sequence of zero or more characters. ** ** '?' Matches exactly one character. ** ** [...] Matches one character from the enclosed list of ** characters. ** ** [^...] Matches one character not in the enclosed list. ** ** '#' Matches any sequence of one or more digits with an ** optional + or - sign in front ** ** ' ' Any span of whitespace matches any other span of ** whitespace. ** ** Extra whitespace at the end of z[] is ignored. */ static int testcase_glob(const char *zGlob, const char *z){ int c, c2; int invert; int seen; while( (c = (*(zGlob++)))!=0 ){ if( IsSpace(c) ){ if( !IsSpace(*z) ) return 0; while( IsSpace(*zGlob) ) zGlob++; while( IsSpace(*z) ) z++; }else if( c=='*' ){ while( (c=(*(zGlob++))) == '*' || c=='?' ){ if( c=='?' && (*(z++))==0 ) return 0; } if( c==0 ){ return 1; }else if( c=='[' ){ while( *z && testcase_glob(zGlob-1,z)==0 ){ z++; } return (*z)!=0; } while( (c2 = (*(z++)))!=0 ){ while( c2!=c ){ c2 = *(z++); if( c2==0 ) return 0; } if( testcase_glob(zGlob,z) ) return 1; } return 0; }else if( c=='?' ){ if( (*(z++))==0 ) return 0; }else if( c=='[' ){ int prior_c = 0; seen = 0; invert = 0; c = *(z++); if( c==0 ) return 0; c2 = *(zGlob++); if( c2=='^' ){ invert = 1; c2 = *(zGlob++); } if( c2==']' ){ if( c==']' ) seen = 1; c2 = *(zGlob++); } while( c2 && c2!=']' ){ if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ c2 = *(zGlob++); if( c>=prior_c && c<=c2 ) seen = 1; prior_c = 0; }else{ if( c==c2 ){ seen = 1; } prior_c = c2; } c2 = *(zGlob++); } if( c2==0 || (seen ^ invert)==0 ) return 0; }else if( c=='#' ){ if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; if( !IsDigit(z[0]) ) return 0; z++; while( IsDigit(z[0]) ){ z++; } }else{ if( c!=(*(z++)) ) return 0; } } while( IsSpace(*z) ){ z++; } return *z==0; } /* ** Compare the string as a command-line option with either one or two ** initial "-" characters. */ static int optionMatch(const char *zStr, const char *zOpt){ if( zStr[0]!='-' ) return 0; zStr++; if( zStr[0]=='-' ) zStr++; return strcmp(zStr, zOpt)==0; } /* ** Delete a file. */ int shellDeleteFile(const char *zFilename){ int rc; #ifdef _WIN32 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); rc = _wunlink(z); sqlite3_free(z); #else rc = unlink(zFilename); #endif return rc; } /* ** Try to delete the temporary file (if there is one) and free the ** memory used to hold the name of the temp file. */ static void clearTempFile(ShellState *p){ if( p->zTempFile==0 ) return; if( p->doXdgOpen ) return; if( shellDeleteFile(p->zTempFile) ) return; sqlite3_free(p->zTempFile); p->zTempFile = 0; } /* ** Create a new temp file name with the given suffix. */ static void newTempFile(ShellState *p, const char *zSuffix){ clearTempFile(p); sqlite3_free(p->zTempFile); p->zTempFile = 0; if( p->db ){ sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); } if( p->zTempFile==0 ){ sqlite3_uint64 r; sqlite3_randomness(sizeof(r), &r); p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix); }else{ p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); } if( p->zTempFile==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } } /* ** The implementation of SQL scalar function fkey_collate_clause(), used ** by the ".lint fkey-indexes" command. This scalar function is always ** called with four arguments - the parent table name, the parent column name, ** the child table name and the child column name. ** ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') ** ** If either of the named tables or columns do not exist, this function ** returns an empty string. An empty string is also returned if both tables ** and columns exist but have the same default collation sequence. Or, ** if both exist but the default collation sequences are different, this ** function returns the string " COLLATE <parent-collation>", where ** <parent-collation> is the default collation sequence of the parent column. */ static void shellFkeyCollateClause( sqlite3_context *pCtx, int nVal, sqlite3_value **apVal ){ sqlite3 *db = sqlite3_context_db_handle(pCtx); const char *zParent; const char *zParentCol; const char *zParentSeq; const char *zChild; const char *zChildCol; const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ int rc; assert( nVal==4 ); zParent = (const char*)sqlite3_value_text(apVal[0]); zParentCol = (const char*)sqlite3_value_text(apVal[1]); zChild = (const char*)sqlite3_value_text(apVal[2]); zChildCol = (const char*)sqlite3_value_text(apVal[3]); sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); rc = sqlite3_table_column_metadata( db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 ); if( rc==SQLITE_OK ){ rc = sqlite3_table_column_metadata( db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 ); } if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); sqlite3_free(z); } } /* ** The implementation of dot-command ".lint fkey-indexes". */ static int lintFkeyIndexes( ShellState *pState, /* Current shell tool state */ char **azArg, /* Array of arguments passed to dot command */ int nArg /* Number of entries in azArg[] */ ){ sqlite3 *db = pState->db; /* Database handle to query "main" db of */ FILE *out = pState->out; /* Stream to write non-error output to */ int bVerbose = 0; /* If -verbose is present */ int bGroupByParent = 0; /* If -groupbyparent is present */ int i; /* To iterate through azArg[] */ const char *zIndent = ""; /* How much to indent CREATE INDEX by */ int rc; /* Return code */ sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ /* ** This SELECT statement returns one row for each foreign key constraint ** in the schema of the main database. The column values are: ** ** 0. The text of an SQL statement similar to: ** ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" ** ** This SELECT is similar to the one that the foreign keys implementation ** needs to run internally on child tables. If there is an index that can ** be used to optimize this query, then it can also be used by the FK ** implementation to optimize DELETE or UPDATE statements on the parent ** table. ** ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema ** contains an index that can be used to optimize the query. ** ** 2. Human readable text that describes the child table and columns. e.g. ** ** "child_table(child_key1, child_key2)" ** ** 3. Human readable text that describes the parent table and columns. e.g. ** ** "parent_table(parent_key1, parent_key2)" ** ** 4. A full CREATE INDEX statement for an index that could be used to ** optimize DELETE or UPDATE statements on the parent table. e.g. ** ** "CREATE INDEX child_table_child_key ON child_table(child_key)" ** ** 5. The name of the parent table. ** ** These six values are used by the C logic below to generate the report. */ const char *zSql = "SELECT " " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " " || fkey_collate_clause(" " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" ", " " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('" " || group_concat('*=?', ' AND ') || ')'" ", " " s.name || '(' || group_concat(f.[from], ', ') || ')'" ", " " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" ", " " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" " || ' ON ' || quote(s.name) || '('" " || group_concat(quote(f.[from]) ||" " fkey_collate_clause(" " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" " || ');'" ", " " f.[table] " "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f " "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " "GROUP BY s.name, f.id " "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" ; const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)"; for(i=2; i<nArg; i++){ int n = strlen30(azArg[i]); if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ bVerbose = 1; } else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ bGroupByParent = 1; zIndent = " "; } else{ raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1] ); return SQLITE_ERROR; } } /* Register the fkey_collate_clause() SQL function */ rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 0, shellFkeyCollateClause, 0, 0 ); if( rc==SQLITE_OK ){ rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); } if( rc==SQLITE_OK ){ sqlite3_bind_int(pSql, 1, bGroupByParent); } if( rc==SQLITE_OK ){ int rc2; char *zPrev = 0; while( SQLITE_ROW==sqlite3_step(pSql) ){ int res = -1; sqlite3_stmt *pExplain = 0; const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); const char *zCI = (const char*)sqlite3_column_text(pSql, 4); const char *zParent = (const char*)sqlite3_column_text(pSql, 5); rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); if( rc!=SQLITE_OK ) break; if( SQLITE_ROW==sqlite3_step(pExplain) ){ const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); res = ( 0==sqlite3_strglob(zGlob, zPlan) || 0==sqlite3_strglob(zGlobIPK, zPlan) ); } rc = sqlite3_finalize(pExplain); if( rc!=SQLITE_OK ) break; if( res<0 ){ raw_printf(stderr, "Error: internal error"); break; }else{ if( bGroupByParent && (bVerbose || res==0) && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) ){ raw_printf(out, "-- Parent table %s\n", zParent); sqlite3_free(zPrev); zPrev = sqlite3_mprintf("%s", zParent); } if( res==0 ){ raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); }else if( bVerbose ){ raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", zIndent, zFrom, zTarget ); } } } sqlite3_free(zPrev); if( rc!=SQLITE_OK ){ raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); } rc2 = sqlite3_finalize(pSql); if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ rc = rc2; raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); } }else{ raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); } return rc; } /* ** Implementation of ".lint" dot command. */ static int lintDotCommand( ShellState *pState, /* Current shell tool state */ char **azArg, /* Array of arguments passed to dot command */ int nArg /* Number of entries in azArg[] */ ){ int n; n = (nArg>=2 ? strlen30(azArg[1]) : 0); if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; return lintFkeyIndexes(pState, azArg, nArg); usage: raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); raw_printf(stderr, "Where sub-commands are:\n"); raw_printf(stderr, " fkey-indexes\n"); return SQLITE_ERROR; } #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) /********************************************************************************* ** The ".archive" or ".ar" command. */ static void shellPrepare( sqlite3 *db, int *pRc, const char *zSql, sqlite3_stmt **ppStmt ){ *ppStmt = 0; if( *pRc==SQLITE_OK ){ int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); if( rc!=SQLITE_OK ){ raw_printf(stderr, "sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db) ); *pRc = rc; } } } static void shellPreparePrintf( sqlite3 *db, int *pRc, sqlite3_stmt **ppStmt, const char *zFmt, ... ){ *ppStmt = 0; if( *pRc==SQLITE_OK ){ va_list ap; char *z; va_start(ap, zFmt); z = sqlite3_vmprintf(zFmt, ap); if( z==0 ){ *pRc = SQLITE_NOMEM; }else{ shellPrepare(db, pRc, z, ppStmt); sqlite3_free(z); } } } static void shellFinalize( int *pRc, sqlite3_stmt *pStmt ){ if( pStmt ){ sqlite3 *db = sqlite3_db_handle(pStmt); int rc = sqlite3_finalize(pStmt); if( *pRc==SQLITE_OK ){ if( rc!=SQLITE_OK ){ raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); } *pRc = rc; } } } static void shellReset( int *pRc, sqlite3_stmt *pStmt ){ int rc = sqlite3_reset(pStmt); if( *pRc==SQLITE_OK ){ if( rc!=SQLITE_OK ){ sqlite3 *db = sqlite3_db_handle(pStmt); raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); } *pRc = rc; } } /* ** Structure representing a single ".ar" command. */ typedef struct ArCommand ArCommand; struct ArCommand { u8 eCmd; /* An AR_CMD_* value */ u8 bVerbose; /* True if --verbose */ u8 bZip; /* True if the archive is a ZIP */ u8 bDryRun; /* True if --dry-run */ u8 bAppend; /* True if --append */ int nArg; /* Number of command arguments */ char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ const char *zFile; /* --file argument, or NULL */ const char *zDir; /* --directory argument, or NULL */ char **azArg; /* Array of command arguments */ ShellState *p; /* Shell state */ sqlite3 *db; /* Database containing the archive */ }; /* ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. */ static int arUsage(FILE *f){ raw_printf(f, "\n" "Usage: .ar [OPTION...] [FILE...]\n" "The .ar command manages sqlar archives.\n" "\n" "Examples:\n" " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n" " .ar -tf archive.sar # List members of archive.sar\n" " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n" "\n" "Each command line must feature exactly one command option:\n" " -c, --create Create a new archive\n" " -u, --update Update or add files to an existing archive\n" " -t, --list List contents of archive\n" " -x, --extract Extract files from archive\n" "\n" "And zero or more optional options:\n" " -v, --verbose Print each filename as it is processed\n" " -f FILE, --file FILE Operate on archive FILE (default is current db)\n" " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS\n" " -C DIR, --directory DIR Change to directory DIR to read/extract files\n" " -n, --dryrun Show the SQL that would have occurred\n" "\n" "See also: http://sqlite.org/cli.html#sqlar_archive_support\n" "\n" ); return SQLITE_ERROR; } /* ** Print an error message for the .ar command to stderr and return ** SQLITE_ERROR. */ static int arErrorMsg(const char *zFmt, ...){ va_list ap; char *z; va_start(ap, zFmt); z = sqlite3_vmprintf(zFmt, ap); va_end(ap); raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z); sqlite3_free(z); return SQLITE_ERROR; } /* ** Values for ArCommand.eCmd. */ #define AR_CMD_CREATE 1 #define AR_CMD_EXTRACT 2 #define AR_CMD_LIST 3 #define AR_CMD_UPDATE 4 #define AR_CMD_HELP 5 /* ** Other (non-command) switches. */ #define AR_SWITCH_VERBOSE 6 #define AR_SWITCH_FILE 7 #define AR_SWITCH_DIRECTORY 8 #define AR_SWITCH_APPEND 9 #define AR_SWITCH_DRYRUN 10 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ switch( eSwitch ){ case AR_CMD_CREATE: case AR_CMD_EXTRACT: case AR_CMD_LIST: case AR_CMD_UPDATE: case AR_CMD_HELP: if( pAr->eCmd ){ return arErrorMsg("multiple command options"); } pAr->eCmd = eSwitch; break; case AR_SWITCH_DRYRUN: pAr->bDryRun = 1; break; case AR_SWITCH_VERBOSE: pAr->bVerbose = 1; break; case AR_SWITCH_APPEND: pAr->bAppend = 1; /* Fall thru into --file */ case AR_SWITCH_FILE: pAr->zFile = zArg; break; case AR_SWITCH_DIRECTORY: pAr->zDir = zArg; break; } return SQLITE_OK; } /* ** Parse the command line for an ".ar" command. The results are written into ** structure (*pAr). SQLITE_OK is returned if the command line is parsed ** successfully, otherwise an error message is written to stderr and ** SQLITE_ERROR returned. */ static int arParseCommand( char **azArg, /* Array of arguments passed to dot command */ int nArg, /* Number of entries in azArg[] */ ArCommand *pAr /* Populate this object */ ){ struct ArSwitch { const char *zLong; char cShort; u8 eSwitch; u8 bArg; } aSwitch[] = { { "create", 'c', AR_CMD_CREATE, 0 }, { "extract", 'x', AR_CMD_EXTRACT, 0 }, { "list", 't', AR_CMD_LIST, 0 }, { "update", 'u', AR_CMD_UPDATE, 0 }, { "help", 'h', AR_CMD_HELP, 0 }, { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, { "file", 'f', AR_SWITCH_FILE, 1 }, { "append", 'a', AR_SWITCH_APPEND, 1 }, { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, }; int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); struct ArSwitch *pEnd = &aSwitch[nSwitch]; if( nArg<=1 ){ return arUsage(stderr); }else{ char *z = azArg[1]; memset(pAr, 0, sizeof(ArCommand)); if( z[0]!='-' ){ /* Traditional style [tar] invocation */ int i; int iArg = 2; for(i=0; z[i]; i++){ const char *zArg = 0; struct ArSwitch *pOpt; for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ if( z[i]==pOpt->cShort ) break; } if( pOpt==pEnd ){ return arErrorMsg("unrecognized option: %c", z[i]); } if( pOpt->bArg ){ if( iArg>=nArg ){ return arErrorMsg("option requires an argument: %c",z[i]); } zArg = azArg[iArg++]; } if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; } pAr->nArg = nArg-iArg; if( pAr->nArg>0 ){ pAr->azArg = &azArg[iArg]; } }else{ /* Non-traditional invocation */ int iArg; for(iArg=1; iArg<nArg; iArg++){ int n; z = azArg[iArg]; if( z[0]!='-' ){ /* All remaining command line words are command arguments. */ pAr->azArg = &azArg[iArg]; pAr->nArg = nArg-iArg; break; } n = strlen30(z); if( z[1]!='-' ){ int i; /* One or more short options */ for(i=1; i<n; i++){ const char *zArg = 0; struct ArSwitch *pOpt; for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ if( z[i]==pOpt->cShort ) break; } if( pOpt==pEnd ){ return arErrorMsg("unrecognized option: %c\n", z[i]); } if( pOpt->bArg ){ if( i<(n-1) ){ zArg = &z[i+1]; i = n; }else{ if( iArg>=(nArg-1) ){ return arErrorMsg("option requires an argument: %c\n",z[i]); } zArg = azArg[++iArg]; } } if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; } }else if( z[2]=='\0' ){ /* A -- option, indicating that all remaining command line words ** are command arguments. */ pAr->azArg = &azArg[iArg+1]; pAr->nArg = nArg-iArg-1; break; }else{ /* A long option */ const char *zArg = 0; /* Argument for option, if any */ struct ArSwitch *pMatch = 0; /* Matching option */ struct ArSwitch *pOpt; /* Iterator */ for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ const char *zLong = pOpt->zLong; if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ if( pMatch ){ return arErrorMsg("ambiguous option: %s",z); }else{ pMatch = pOpt; } } } if( pMatch==0 ){ return arErrorMsg("unrecognized option: %s", z); } if( pMatch->bArg ){ if( iArg>=(nArg-1) ){ return arErrorMsg("option requires an argument: %s", z); } zArg = azArg[++iArg]; } if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; } } } } return SQLITE_OK; } /* ** This function assumes that all arguments within the ArCommand.azArg[] ** array refer to archive members, as for the --extract or --list commands. ** It checks that each of them are present. If any specified file is not ** present in the archive, an error is printed to stderr and an error ** code returned. Otherwise, if all specified arguments are present in ** the archive, SQLITE_OK is returned. ** ** This function strips any trailing '/' characters from each argument. ** This is consistent with the way the [tar] command seems to work on ** Linux. */ static int arCheckEntries(ArCommand *pAr){ int rc = SQLITE_OK; if( pAr->nArg ){ int i, j; sqlite3_stmt *pTest = 0; shellPreparePrintf(pAr->db, &rc, &pTest, "SELECT name FROM %s WHERE name=$name", pAr->zSrcTable ); j = sqlite3_bind_parameter_index(pTest, "$name"); for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ char *z = pAr->azArg[i]; int n = strlen30(z); int bOk = 0; while( n>0 && z[n-1]=='/' ) n--; z[n] = '\0'; sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); if( SQLITE_ROW==sqlite3_step(pTest) ){ bOk = 1; } shellReset(&rc, pTest); if( rc==SQLITE_OK && bOk==0 ){ utf8_printf(stderr, "not found in archive: %s\n", z); rc = SQLITE_ERROR; } } shellFinalize(&rc, pTest); } return rc; } /* ** Format a WHERE clause that can be used against the "sqlar" table to ** identify all archive members that match the command arguments held ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. ** The caller is responsible for eventually calling sqlite3_free() on ** any non-NULL (*pzWhere) value. */ static void arWhereClause( int *pRc, ArCommand *pAr, char **pzWhere /* OUT: New WHERE clause */ ){ char *zWhere = 0; if( *pRc==SQLITE_OK ){ if( pAr->nArg==0 ){ zWhere = sqlite3_mprintf("1"); }else{ int i; const char *zSep = ""; for(i=0; i<pAr->nArg; i++){ const char *z = pAr->azArg[i]; zWhere = sqlite3_mprintf( "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", zWhere, zSep, z, strlen30(z)+1, z ); if( zWhere==0 ){ *pRc = SQLITE_NOMEM; break; } zSep = " OR "; } } } *pzWhere = zWhere; } /* ** Implementation of .ar "lisT" command. */ static int arListCommand(ArCommand *pAr){ const char *zSql = "SELECT %s FROM %s WHERE %s"; const char *azCols[] = { "name", "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" }; char *zWhere = 0; sqlite3_stmt *pSql = 0; int rc; rc = arCheckEntries(pAr); arWhereClause(&rc, pAr, &zWhere); shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], pAr->zSrcTable, zWhere); if( pAr->bDryRun ){ utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); }else{ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ if( pAr->bVerbose ){ utf8_printf(pAr->p->out, "%s % 10d %s %s\n", sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1), sqlite3_column_text(pSql, 2), sqlite3_column_text(pSql, 3) ); }else{ utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); } } } shellFinalize(&rc, pSql); return rc; } /* ** Implementation of .ar "eXtract" command. */ static int arExtractCommand(ArCommand *pAr){ const char *zSql1 = "SELECT " " ($dir || name)," " writefile(($dir || name), %s, mode, mtime) " "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"; const char *azExtraArg[] = { "sqlar_uncompress(data, sz)", "data" }; sqlite3_stmt *pSql = 0; int rc = SQLITE_OK; char *zDir = 0; char *zWhere = 0; int i, j; /* If arguments are specified, check that they actually exist within ** the archive before proceeding. And formulate a WHERE clause to ** match them. */ rc = arCheckEntries(pAr); arWhereClause(&rc, pAr, &zWhere); if( rc==SQLITE_OK ){ if( pAr->zDir ){ zDir = sqlite3_mprintf("%s/", pAr->zDir); }else{ zDir = sqlite3_mprintf(""); } if( zDir==0 ) rc = SQLITE_NOMEM; } shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere ); if( rc==SQLITE_OK ){ j = sqlite3_bind_parameter_index(pSql, "$dir"); sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); /* Run the SELECT statement twice. The first time, writefile() is called ** for all archive members that should be extracted. The second time, ** only for the directories. This is because the timestamps for ** extracted directories must be reset after they are populated (as ** populating them changes the timestamp). */ for(i=0; i<2; i++){ j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); sqlite3_bind_int(pSql, j, i); if( pAr->bDryRun ){ utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); }else{ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ if( i==0 && pAr->bVerbose ){ utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); } } } shellReset(&rc, pSql); } shellFinalize(&rc, pSql); } sqlite3_free(zDir); sqlite3_free(zWhere); return rc; } /* ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. */ static int arExecSql(ArCommand *pAr, const char *zSql){ int rc; if( pAr->bDryRun ){ utf8_printf(pAr->p->out, "%s\n", zSql); rc = SQLITE_OK; }else{ char *zErr = 0; rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); if( zErr ){ utf8_printf(stdout, "ERROR: %s\n", zErr); sqlite3_free(zErr); } } return rc; } /* ** Implementation of .ar "create" and "update" commands. ** ** Create the "sqlar" table in the database if it does not already exist. ** Then add each file in the azFile[] array to the archive. Directories ** are added recursively. If argument bVerbose is non-zero, a message is ** printed on stdout for each file archived. ** ** The create command is the same as update, except that it drops ** any existing "sqlar" table before beginning. */ static int arCreateOrUpdateCommand( ArCommand *pAr, /* Command arguments and options */ int bUpdate /* true for a --create. false for --update */ ){ const char *zCreate = "CREATE TABLE IF NOT EXISTS sqlar(\n" " name TEXT PRIMARY KEY, -- name of the file\n" " mode INT, -- access permissions\n" " mtime INT, -- last modification time\n" " sz INT, -- original file size\n" " data BLOB -- compressed content\n" ")"; const char *zDrop = "DROP TABLE IF EXISTS sqlar"; const char *zInsertFmt[2] = { "REPLACE INTO %s(name,mode,mtime,sz,data)\n" " SELECT\n" " %s,\n" " mode,\n" " mtime,\n" " CASE substr(lsmode(mode),1,1)\n" " WHEN '-' THEN length(data)\n" " WHEN 'd' THEN 0\n" " ELSE -1 END,\n" " sqlar_compress(data)\n" " FROM fsdir(%Q,%Q)\n" " WHERE lsmode(mode) NOT LIKE '?%%';", "REPLACE INTO %s(name,mode,mtime,data)\n" " SELECT\n" " %s,\n" " mode,\n" " mtime,\n" " data\n" " FROM fsdir(%Q,%Q)\n" " WHERE lsmode(mode) NOT LIKE '?%%';" }; int i; /* For iterating through azFile[] */ int rc; /* Return code */ const char *zTab = 0; /* SQL table into which to insert */ char *zSql; char zTemp[50]; arExecSql(pAr, "PRAGMA page_size=512"); rc = arExecSql(pAr, "SAVEPOINT ar;"); if( rc!=SQLITE_OK ) return rc; zTemp[0] = 0; if( pAr->bZip ){ /* Initialize the zipfile virtual table, if necessary */ if( pAr->zFile ){ sqlite3_uint64 r; sqlite3_randomness(sizeof(r),&r); sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); zTab = zTemp; zSql = sqlite3_mprintf( "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", zTab, pAr->zFile ); rc = arExecSql(pAr, zSql); sqlite3_free(zSql); }else{ zTab = "zip"; } }else{ /* Initialize the table for an SQLAR */ zTab = "sqlar"; if( bUpdate==0 ){ rc = arExecSql(pAr, zDrop); if( rc!=SQLITE_OK ) goto end_ar_transaction; } rc = arExecSql(pAr, zCreate); } for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, pAr->bVerbose ? "shell_putsnl(name)" : "name", pAr->azArg[i], pAr->zDir); rc = arExecSql(pAr, zSql2); sqlite3_free(zSql2); } end_ar_transaction: if( rc!=SQLITE_OK ){ arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;"); }else{ rc = arExecSql(pAr, "RELEASE ar;"); if( pAr->bZip && pAr->zFile ){ zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); arExecSql(pAr, zSql); sqlite3_free(zSql); } } return rc; } /* ** Implementation of ".ar" dot command. */ static int arDotCommand( ShellState *pState, /* Current shell tool state */ char **azArg, /* Array of arguments passed to dot command */ int nArg /* Number of entries in azArg[] */ ){ ArCommand cmd; int rc; memset(&cmd, 0, sizeof(cmd)); rc = arParseCommand(azArg, nArg, &cmd); if( rc==SQLITE_OK ){ int eDbType = SHELL_OPEN_UNSPEC; cmd.p = pState; cmd.db = pState->db; if( cmd.zFile ){ eDbType = deduceDatabaseType(cmd.zFile, 1); }else{ eDbType = pState->openMode; } if( eDbType==SHELL_OPEN_ZIPFILE ){ if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ if( cmd.zFile==0 ){ cmd.zSrcTable = sqlite3_mprintf("zip"); }else{ cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); } } cmd.bZip = 1; }else if( cmd.zFile ){ int flags; if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){ flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; }else{ flags = SQLITE_OPEN_READONLY; } cmd.db = 0; if( cmd.bDryRun ){ utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); } rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); if( rc!=SQLITE_OK ){ utf8_printf(stderr, "cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db) ); goto end_ar_command; } sqlite3_fileio_init(cmd.db, 0, 0); sqlite3_sqlar_init(cmd.db, 0, 0); sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, shellPutsFunc, 0, 0); } if( cmd.zSrcTable==0 && cmd.bZip==0 ){ if( cmd.eCmd!=AR_CMD_CREATE && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) ){ utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); rc = SQLITE_ERROR; goto end_ar_command; } cmd.zSrcTable = sqlite3_mprintf("sqlar"); } switch( cmd.eCmd ){ case AR_CMD_CREATE: rc = arCreateOrUpdateCommand(&cmd, 0); break; case AR_CMD_EXTRACT: rc = arExtractCommand(&cmd); break; case AR_CMD_LIST: rc = arListCommand(&cmd); break; case AR_CMD_HELP: arUsage(pState->out); break; default: assert( cmd.eCmd==AR_CMD_UPDATE ); rc = arCreateOrUpdateCommand(&cmd, 1); break; } } end_ar_command: if( cmd.db!=pState->db ){ sqlite3_close(cmd.db); } sqlite3_free(cmd.zSrcTable); return rc; } /* End of the ".archive" or ".ar" command logic **********************************************************************************/ #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ /* ** If an input line begins with "." then invoke this routine to ** process that line. ** ** Return 1 on error, 2 to exit, and 0 otherwise. */ static int do_meta_command(char *zLine, ShellState *p){ int h = 1; int nArg = 0; int n, c; int rc = 0; char *azArg[50]; #ifndef SQLITE_OMIT_VIRTUALTABLE if( p->expert.pExpert ){ expertFinish(p, 1, 0); } #endif /* Parse the input line into tokens. */ while( zLine[h] && nArg<ArraySize(azArg) ){ while( IsSpace(zLine[h]) ){ h++; } if( zLine[h]==0 ) break; if( zLine[h]=='\'' || zLine[h]=='"' ){ int delim = zLine[h++]; azArg[nArg++] = &zLine[h]; while( zLine[h] && zLine[h]!=delim ){ if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; h++; } if( zLine[h]==delim ){ zLine[h++] = 0; } if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); }else{ azArg[nArg++] = &zLine[h]; while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } if( zLine[h] ) zLine[h++] = 0; resolve_backslashes(azArg[nArg-1]); } } /* Process the input line. */ if( nArg==0 ) return 0; /* no tokens, no error */ n = strlen30(azArg[0]); c = azArg[0][0]; clearTempFile(p); #ifndef SQLITE_OMIT_AUTHORIZATION if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ if( nArg!=2 ){ raw_printf(stderr, "Usage: .auth ON|OFF\n"); rc = 1; goto meta_command_exit; } open_db(p, 0); if( booleanValue(azArg[1]) ){ sqlite3_set_authorizer(p->db, shellAuth, p); }else{ sqlite3_set_authorizer(p->db, 0, 0); } }else #endif #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ open_db(p, 0); rc = arDotCommand(p, azArg, nArg); }else #endif if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) ){ const char *zDestFile = 0; const char *zDb = 0; sqlite3 *pDest; sqlite3_backup *pBackup; int j; for(j=1; j<nArg; j++){ const char *z = azArg[j]; if( z[0]=='-' ){ while( z[0]=='-' ) z++; /* No options to process at this time */ { utf8_printf(stderr, "unknown option: %s\n", azArg[j]); return 1; } }else if( zDestFile==0 ){ zDestFile = azArg[j]; }else if( zDb==0 ){ zDb = zDestFile; zDestFile = azArg[j]; }else{ raw_printf(stderr, "too many arguments to .backup\n"); return 1; } } if( zDestFile==0 ){ raw_printf(stderr, "missing FILENAME argument on .backup\n"); return 1; } if( zDb==0 ) zDb = "main"; rc = sqlite3_open(zDestFile, &pDest); if( rc!=SQLITE_OK ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); sqlite3_close(pDest); return 1; } open_db(p, 0); pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); if( pBackup==0 ){ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); sqlite3_close(pDest); return 1; } while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} sqlite3_backup_finish(pBackup); if( rc==SQLITE_DONE ){ rc = 0; }else{ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); rc = 1; } sqlite3_close(pDest); }else if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ if( nArg==2 ){ bail_on_error = booleanValue(azArg[1]); }else{ raw_printf(stderr, "Usage: .bail on|off\n"); rc = 1; } }else if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ if( nArg==2 ){ if( booleanValue(azArg[1]) ){ setBinaryMode(p->out, 1); }else{ setTextMode(p->out, 1); } }else{ raw_printf(stderr, "Usage: .binary on|off\n"); rc = 1; } }else if( c=='c' && strcmp(azArg[0],"cd")==0 ){ if( nArg==2 ){ #if defined(_WIN32) || defined(WIN32) wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); rc = !SetCurrentDirectoryW(z); sqlite3_free(z); #else rc = chdir(azArg[1]); #endif if( rc ){ utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); rc = 1; } }else{ raw_printf(stderr, "Usage: .cd DIRECTORY\n"); rc = 1; } }else /* The undocumented ".breakpoint" command causes a call to the no-op ** routine named test_breakpoint(). */ if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ test_breakpoint(); }else if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ if( nArg==2 ){ setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); }else{ raw_printf(stderr, "Usage: .changes on|off\n"); rc = 1; } }else /* Cancel output redirection, if it is currently set (by .testcase) ** Then read the content of the testcase-out.txt file and compare against ** azArg[1]. If there are differences, report an error and exit. */ if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ char *zRes = 0; output_reset(p); if( nArg!=2 ){ raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); rc = 2; }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); rc = 2; }else if( testcase_glob(azArg[1],zRes)==0 ){ utf8_printf(stderr, "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", p->zTestcase, azArg[1], zRes); rc = 1; }else{ utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); p->nCheck++; } sqlite3_free(zRes); }else if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ if( nArg==2 ){ tryToClone(p, azArg[1]); }else{ raw_printf(stderr, "Usage: .clone FILENAME\n"); rc = 1; } }else if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ ShellState data; char *zErrMsg = 0; open_db(p, 0); memcpy(&data, p, sizeof(data)); data.showHeader = 0; data.cMode = data.mode = MODE_List; sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": "); data.cnt = 0; sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list", callback, &data, &zErrMsg); if( zErrMsg ){ utf8_printf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); rc = 1; } }else if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){ rc = shell_dbinfo_command(p, nArg, azArg); }else if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ const char *zLike = 0; int i; int savedShowHeader = p->showHeader; ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines); for(i=1; i<nArg; i++){ if( azArg[i][0]=='-' ){ const char *z = azArg[i]+1; if( z[0]=='-' ) z++; if( strcmp(z,"preserve-rowids")==0 ){ #ifdef SQLITE_OMIT_VIRTUALTABLE raw_printf(stderr, "The --preserve-rowids option is not compatible" " with SQLITE_OMIT_VIRTUALTABLE\n"); rc = 1; goto meta_command_exit; #else ShellSetFlag(p, SHFLG_PreserveRowid); #endif }else if( strcmp(z,"newlines")==0 ){ ShellSetFlag(p, SHFLG_Newlines); }else { raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); rc = 1; goto meta_command_exit; } }else if( zLike ){ raw_printf(stderr, "Usage: .dump ?--preserve-rowids? " "?--newlines? ?LIKE-PATTERN?\n"); rc = 1; goto meta_command_exit; }else{ zLike = azArg[i]; } } open_db(p, 0); /* When playing back a "dump", the content might appear in an order ** which causes immediate foreign key constraints to be violated. ** So disable foreign-key constraint enforcement to prevent problems. */ raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); raw_printf(p->out, "BEGIN TRANSACTION;\n"); p->writableSchema = 0; p->showHeader = 0; /* Set writable_schema=ON since doing so forces SQLite to initialize ** as much of the schema as it can even if the sqlite_master table is ** corrupt. */ sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); p->nErr = 0; if( zLike==0 ){ run_schema_dump_query(p, "SELECT name, type, sql FROM sqlite_master " "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" ); run_schema_dump_query(p, "SELECT name, type, sql FROM sqlite_master " "WHERE name=='sqlite_sequence'" ); run_table_dump_query(p, "SELECT sql FROM sqlite_master " "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 ); }else{ char *zSql; zSql = sqlite3_mprintf( "SELECT name, type, sql FROM sqlite_master " "WHERE tbl_name LIKE %Q AND type=='table'" " AND sql NOT NULL", zLike); run_schema_dump_query(p,zSql); sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT sql FROM sqlite_master " "WHERE sql NOT NULL" " AND type IN ('index','trigger','view')" " AND tbl_name LIKE %Q", zLike); run_table_dump_query(p, zSql, 0); sqlite3_free(zSql); } if( p->writableSchema ){ raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); p->writableSchema = 0; } sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n"); p->showHeader = savedShowHeader; }else if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ if( nArg==2 ){ setOrClearFlag(p, SHFLG_Echo, azArg[1]); }else{ raw_printf(stderr, "Usage: .echo on|off\n"); rc = 1; } }else if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ if( nArg==2 ){ if( strcmp(azArg[1],"full")==0 ){ p->autoEQP = AUTOEQP_full; }else if( strcmp(azArg[1],"trigger")==0 ){ p->autoEQP = AUTOEQP_trigger; }else{ p->autoEQP = (u8)booleanValue(azArg[1]); } }else{ raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n"); rc = 1; } }else if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); rc = 2; }else /* The ".explain" command is automatic now. It is largely pointless. It ** retained purely for backwards compatibility */ if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ int val = 1; if( nArg>=2 ){ if( strcmp(azArg[1],"auto")==0 ){ val = 99; }else{ val = booleanValue(azArg[1]); } } if( val==1 && p->mode!=MODE_Explain ){ p->normalMode = p->mode; p->mode = MODE_Explain; p->autoExplain = 0; }else if( val==0 ){ if( p->mode==MODE_Explain ) p->mode = p->normalMode; p->autoExplain = 0; }else if( val==99 ){ if( p->mode==MODE_Explain ) p->mode = p->normalMode; p->autoExplain = 1; } }else #ifndef SQLITE_OMIT_VIRTUALTABLE if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ open_db(p, 0); expertDotCommand(p, azArg, nArg); }else #endif if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ ShellState data; char *zErrMsg = 0; int doStats = 0; memcpy(&data, p, sizeof(data)); data.showHeader = 0; data.cMode = data.mode = MODE_Semi; if( nArg==2 && optionMatch(azArg[1], "indent") ){ data.cMode = data.mode = MODE_Pretty; nArg = 1; } if( nArg!=1 ){ raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); rc = 1; goto meta_command_exit; } open_db(p, 0); rc = sqlite3_exec(p->db, "SELECT sql FROM" " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" " FROM sqlite_master UNION ALL" " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " "ORDER BY rowid", callback, &data, &zErrMsg ); if( rc==SQLITE_OK ){ sqlite3_stmt *pStmt; rc = sqlite3_prepare_v2(p->db, "SELECT rowid FROM sqlite_master" " WHERE name GLOB 'sqlite_stat[134]'", -1, &pStmt, 0); doStats = sqlite3_step(pStmt)==SQLITE_ROW; sqlite3_finalize(pStmt); } if( doStats==0 ){ raw_printf(p->out, "/* No STAT tables available */\n"); }else{ raw_printf(p->out, "ANALYZE sqlite_master;\n"); sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'", callback, &data, &zErrMsg); data.cMode = data.mode = MODE_Insert; data.zDestTable = "sqlite_stat1"; shell_exec(p, "SELECT * FROM sqlite_stat1", &zErrMsg); data.zDestTable = "sqlite_stat3"; shell_exec(p, "SELECT * FROM sqlite_stat3", &zErrMsg); data.zDestTable = "sqlite_stat4"; shell_exec(p, "SELECT * FROM sqlite_stat4", &zErrMsg); raw_printf(p->out, "ANALYZE sqlite_master;\n"); } }else if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ if( nArg==2 ){ p->showHeader = booleanValue(azArg[1]); }else{ raw_printf(stderr, "Usage: .headers on|off\n"); rc = 1; } }else if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ utf8_printf(p->out, "%s", zHelp); }else if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ char *zTable; /* Insert data into this table */ char *zFile; /* Name of file to extra content from */ sqlite3_stmt *pStmt = NULL; /* A statement */ int nCol; /* Number of columns in the table */ int nByte; /* Number of bytes in an SQL string */ int i, j; /* Loop counters */ int needCommit; /* True to COMMIT or ROLLBACK at end */ int nSep; /* Number of bytes in p->colSeparator[] */ char *zSql; /* An SQL statement */ ImportCtx sCtx; /* Reader context */ char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */ if( nArg!=3 ){ raw_printf(stderr, "Usage: .import FILE TABLE\n"); goto meta_command_exit; } zFile = azArg[1]; zTable = azArg[2]; seenInterrupt = 0; memset(&sCtx, 0, sizeof(sCtx)); open_db(p, 0); nSep = strlen30(p->colSeparator); if( nSep==0 ){ raw_printf(stderr, "Error: non-null column separator required for import\n"); return 1; } if( nSep>1 ){ raw_printf(stderr, "Error: multi-character column separators not allowed" " for import\n"); return 1; } nSep = strlen30(p->rowSeparator); if( nSep==0 ){ raw_printf(stderr, "Error: non-null row separator required for import\n"); return 1; } if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){ /* When importing CSV (only), if the row separator is set to the ** default output row separator, change it to the default input ** row separator. This avoids having to maintain different input ** and output row separators. */ sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); nSep = strlen30(p->rowSeparator); } if( nSep>1 ){ raw_printf(stderr, "Error: multi-character row separators not allowed" " for import\n"); return 1; } sCtx.zFile = zFile; sCtx.nLine = 1; if( sCtx.zFile[0]=='|' ){ #ifdef SQLITE_OMIT_POPEN raw_printf(stderr, "Error: pipes are not supported in this OS\n"); return 1; #else sCtx.in = popen(sCtx.zFile+1, "r"); sCtx.zFile = "<pipe>"; xCloser = pclose; #endif }else{ sCtx.in = fopen(sCtx.zFile, "rb"); xCloser = fclose; } if( p->mode==MODE_Ascii ){ xRead = ascii_read_one_field; }else{ xRead = csv_read_one_field; } if( sCtx.in==0 ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); return 1; } sCtx.cColSep = p->colSeparator[0]; sCtx.cRowSep = p->rowSeparator[0]; zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); if( zSql==0 ){ raw_printf(stderr, "Error: out of memory\n"); xCloser(sCtx.in); return 1; } nByte = strlen30(zSql); rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); char cSep = '('; while( xRead(&sCtx) ){ zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); cSep = ','; if( sCtx.cTerm!=sCtx.cColSep ) break; } if( cSep=='(' ){ sqlite3_free(zCreate); sqlite3_free(sCtx.z); xCloser(sCtx.in); utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); return 1; } zCreate = sqlite3_mprintf("%z\n)", zCreate); rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); sqlite3_free(zCreate); if( rc ){ utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, sqlite3_errmsg(p->db)); sqlite3_free(sCtx.z); xCloser(sCtx.in); return 1; } rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); } sqlite3_free(zSql); if( rc ){ if (pStmt) sqlite3_finalize(pStmt); utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); xCloser(sCtx.in); return 1; } nCol = sqlite3_column_count(pStmt); sqlite3_finalize(pStmt); pStmt = 0; if( nCol==0 ) return 0; /* no columns, no error */ zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); if( zSql==0 ){ raw_printf(stderr, "Error: out of memory\n"); xCloser(sCtx.in); return 1; } sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); j = strlen30(zSql); for(i=1; i<nCol; i++){ zSql[j++] = ','; zSql[j++] = '?'; } zSql[j++] = ')'; zSql[j] = 0; rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); if( rc ){ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); if (pStmt) sqlite3_finalize(pStmt); xCloser(sCtx.in); return 1; } needCommit = sqlite3_get_autocommit(p->db); if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); do{ int startLine = sCtx.nLine; for(i=0; i<nCol; i++){ char *z = xRead(&sCtx); /* ** Did we reach end-of-file before finding any columns? ** If so, stop instead of NULL filling the remaining columns. */ if( z==0 && i==0 ) break; /* ** Did we reach end-of-file OR end-of-line before finding any ** columns in ASCII mode? If so, stop instead of NULL filling ** the remaining columns. */ if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " "filling the rest with NULL\n", sCtx.zFile, startLine, nCol, i+1); i += 2; while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } } } if( sCtx.cTerm==sCtx.cColSep ){ do{ xRead(&sCtx); i++; }while( sCtx.cTerm==sCtx.cColSep ); utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " "extras ignored\n", sCtx.zFile, startLine, nCol, i); } if( i>=nCol ){ sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ){ utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, startLine, sqlite3_errmsg(p->db)); } } }while( sCtx.cTerm!=EOF ); xCloser(sCtx.in); sqlite3_free(sCtx.z); sqlite3_finalize(pStmt); if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); }else #ifndef SQLITE_UNTESTABLE if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ char *zSql; char *zCollist = 0; sqlite3_stmt *pStmt; int tnum = 0; int i; if( nArg!=3 ){ utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"); rc = 1; goto meta_command_exit; } open_db(p, 0); zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master" " WHERE name='%q' AND type='index'", azArg[1]); sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); if( sqlite3_step(pStmt)==SQLITE_ROW ){ tnum = sqlite3_column_int(pStmt, 0); } sqlite3_finalize(pStmt); if( tnum==0 ){ utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); rc = 1; goto meta_command_exit; } zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); i = 0; while( sqlite3_step(pStmt)==SQLITE_ROW ){ char zLabel[20]; const char *zCol = (const char*)sqlite3_column_text(pStmt,2); i++; if( zCol==0 ){ if( sqlite3_column_int(pStmt,1)==-1 ){ zCol = "_ROWID_"; }else{ sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); zCol = zLabel; } } if( zCollist==0 ){ zCollist = sqlite3_mprintf("\"%w\"", zCol); }else{ zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); } } sqlite3_finalize(pStmt); zSql = sqlite3_mprintf( "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID", azArg[2], zCollist, zCollist); sqlite3_free(zCollist); rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); if( rc==SQLITE_OK ){ rc = sqlite3_exec(p->db, zSql, 0, 0, 0); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); if( rc ){ utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); }else{ utf8_printf(stdout, "%s;\n", zSql); raw_printf(stdout, "WARNING: writing to an imposter table will corrupt the index!\n" ); } }else{ raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); rc = 1; } sqlite3_free(zSql); }else #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ #ifdef SQLITE_ENABLE_IOTRACE if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); if( iotrace && iotrace!=stdout ) fclose(iotrace); iotrace = 0; if( nArg<2 ){ sqlite3IoTrace = 0; }else if( strcmp(azArg[1], "-")==0 ){ sqlite3IoTrace = iotracePrintf; iotrace = stdout; }else{ iotrace = fopen(azArg[1], "w"); if( iotrace==0 ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); sqlite3IoTrace = 0; rc = 1; }else{ sqlite3IoTrace = iotracePrintf; } } }else #endif if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ static const struct { const char *zLimitName; /* Name of a limit */ int limitCode; /* Integer code for that limit */ } aLimit[] = { { "length", SQLITE_LIMIT_LENGTH }, { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, { "column", SQLITE_LIMIT_COLUMN }, { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, { "attached", SQLITE_LIMIT_ATTACHED }, { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, }; int i, n2; open_db(p, 0); if( nArg==1 ){ for(i=0; i<ArraySize(aLimit); i++){ printf("%20s %d\n", aLimit[i].zLimitName, sqlite3_limit(p->db, aLimit[i].limitCode, -1)); } }else if( nArg>3 ){ raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); rc = 1; goto meta_command_exit; }else{ int iLimit = -1; n2 = strlen30(azArg[1]); for(i=0; i<ArraySize(aLimit); i++){ if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ if( iLimit<0 ){ iLimit = i; }else{ utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); rc = 1; goto meta_command_exit; } } } if( iLimit<0 ){ utf8_printf(stderr, "unknown limit: \"%s\"\n" "enter \".limits\" with no arguments for a list.\n", azArg[1]); rc = 1; goto meta_command_exit; } if( nArg==3 ){ sqlite3_limit(p->db, aLimit[iLimit].limitCode, (int)integerValue(azArg[2])); } printf("%20s %d\n", aLimit[iLimit].zLimitName, sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); } }else if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ open_db(p, 0); lintDotCommand(p, azArg, nArg); }else #ifndef SQLITE_OMIT_LOAD_EXTENSION if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ const char *zFile, *zProc; char *zErrMsg = 0; if( nArg<2 ){ raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); rc = 1; goto meta_command_exit; } zFile = azArg[1]; zProc = nArg>=3 ? azArg[2] : 0; open_db(p, 0); rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); if( rc!=SQLITE_OK ){ utf8_printf(stderr, "Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); rc = 1; } }else #endif if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ if( nArg!=2 ){ raw_printf(stderr, "Usage: .log FILENAME\n"); rc = 1; }else{ const char *zFile = azArg[1]; output_file_close(p->pLog); p->pLog = output_file_open(zFile, 0); } }else if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ const char *zMode = nArg>=2 ? azArg[1] : ""; int n2 = strlen30(zMode); int c2 = zMode[0]; if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ p->mode = MODE_Line; sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ p->mode = MODE_Column; sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ p->mode = MODE_List; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ p->mode = MODE_Html; }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ p->mode = MODE_Tcl; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ p->mode = MODE_Csv; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ p->mode = MODE_List; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ p->mode = MODE_Insert; set_table_name(p, nArg>=3 ? azArg[2] : "table"); }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ p->mode = MODE_Quote; }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ p->mode = MODE_Ascii; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); }else if( nArg==1 ){ raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); }else{ raw_printf(stderr, "Error: mode should be one of: " "ascii column csv html insert line list quote tabs tcl\n"); rc = 1; } p->cMode = p->mode; }else if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ if( nArg==2 ){ sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); }else{ raw_printf(stderr, "Usage: .nullvalue STRING\n"); rc = 1; } }else if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ char *zNewFilename; /* Name of the database file to open */ int iName = 1; /* Index in azArg[] of the filename */ int newFlag = 0; /* True to delete file before opening */ /* Close the existing database */ session_close_all(p); sqlite3_close(p->db); p->db = 0; p->zDbFilename = 0; sqlite3_free(p->zFreeOnClose); p->zFreeOnClose = 0; p->openMode = SHELL_OPEN_UNSPEC; /* Check for command-line arguments */ for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){ const char *z = azArg[iName]; if( optionMatch(z,"new") ){ newFlag = 1; #ifdef SQLITE_HAVE_ZLIB }else if( optionMatch(z, "zip") ){ p->openMode = SHELL_OPEN_ZIPFILE; #endif }else if( optionMatch(z, "append") ){ p->openMode = SHELL_OPEN_APPENDVFS; }else if( optionMatch(z, "readonly") ){ p->openMode = SHELL_OPEN_READONLY; }else if( z[0]=='-' ){ utf8_printf(stderr, "unknown option: %s\n", z); rc = 1; goto meta_command_exit; } } /* If a filename is specified, try to open it first */ zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0; if( zNewFilename ){ if( newFlag ) shellDeleteFile(zNewFilename); p->zDbFilename = zNewFilename; open_db(p, 1); if( p->db==0 ){ utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); sqlite3_free(zNewFilename); }else{ p->zFreeOnClose = zNewFilename; } } if( p->db==0 ){ /* As a fall-back open a TEMP database */ p->zDbFilename = 0; open_db(p, 0); } }else if( (c=='o' && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) ){ const char *zFile = nArg>=2 ? azArg[1] : "stdout"; int bTxtMode = 0; if( azArg[0][0]=='e' ){ /* Transform the ".excel" command into ".once -x" */ nArg = 2; azArg[0] = "once"; zFile = azArg[1] = "-x"; n = 4; } if( nArg>2 ){ utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]); rc = 1; goto meta_command_exit; } if( n>1 && strncmp(azArg[0], "once", n)==0 ){ if( nArg<2 ){ raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n"); rc = 1; goto meta_command_exit; } p->outCount = 2; }else{ p->outCount = 0; } output_reset(p); if( zFile[0]=='-' && zFile[1]=='-' ) zFile++; #ifndef SQLITE_NOHAVE_SYSTEM if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){ p->doXdgOpen = 1; outputModePush(p); if( zFile[1]=='x' ){ newTempFile(p, "csv"); p->mode = MODE_Csv; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); }else{ newTempFile(p, "txt"); bTxtMode = 1; } zFile = p->zTempFile; } #endif /* SQLITE_NOHAVE_SYSTEM */ if( zFile[0]=='|' ){ #ifdef SQLITE_OMIT_POPEN raw_printf(stderr, "Error: pipes are not supported in this OS\n"); rc = 1; p->out = stdout; #else p->out = popen(zFile + 1, "w"); if( p->out==0 ){ utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); p->out = stdout; rc = 1; }else{ sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); } #endif }else{ p->out = output_file_open(zFile, bTxtMode); if( p->out==0 ){ if( strcmp(zFile,"off")!=0 ){ utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); } p->out = stdout; rc = 1; } else { sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); } } }else if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ int i; for(i=1; i<nArg; i++){ if( i>1 ) raw_printf(p->out, " "); utf8_printf(p->out, "%s", azArg[i]); } raw_printf(p->out, "\n"); }else if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ if( nArg >= 2) { strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); } if( nArg >= 3) { strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); } }else if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ rc = 2; }else if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ FILE *alt; if( nArg!=2 ){ raw_printf(stderr, "Usage: .read FILE\n"); rc = 1; goto meta_command_exit; } alt = fopen(azArg[1], "rb"); if( alt==0 ){ utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); rc = 1; }else{ rc = process_input(p, alt); fclose(alt); } }else if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ const char *zSrcFile; const char *zDb; sqlite3 *pSrc; sqlite3_backup *pBackup; int nTimeout = 0; if( nArg==2 ){ zSrcFile = azArg[1]; zDb = "main"; }else if( nArg==3 ){ zSrcFile = azArg[2]; zDb = azArg[1]; }else{ raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_open(zSrcFile, &pSrc); if( rc!=SQLITE_OK ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); sqlite3_close(pSrc); return 1; } open_db(p, 0); pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); if( pBackup==0 ){ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); sqlite3_close(pSrc); return 1; } while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK || rc==SQLITE_BUSY ){ if( rc==SQLITE_BUSY ){ if( nTimeout++ >= 3 ) break; sqlite3_sleep(100); } } sqlite3_backup_finish(pBackup); if( rc==SQLITE_DONE ){ rc = 0; }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ raw_printf(stderr, "Error: source database is busy\n"); rc = 1; }else{ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); rc = 1; } sqlite3_close(pSrc); }else if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ if( nArg==2 ){ p->scanstatsOn = (u8)booleanValue(azArg[1]); #ifndef SQLITE_ENABLE_STMT_SCANSTATUS raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); #endif }else{ raw_printf(stderr, "Usage: .scanstats on|off\n"); rc = 1; } }else if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ ShellText sSelect; ShellState data; char *zErrMsg = 0; const char *zDiv = "("; const char *zName = 0; int iSchema = 0; int bDebug = 0; int ii; open_db(p, 0); memcpy(&data, p, sizeof(data)); data.showHeader = 0; data.cMode = data.mode = MODE_Semi; initText(&sSelect); for(ii=1; ii<nArg; ii++){ if( optionMatch(azArg[ii],"indent") ){ data.cMode = data.mode = MODE_Pretty; }else if( optionMatch(azArg[ii],"debug") ){ bDebug = 1; }else if( zName==0 ){ zName = azArg[ii]; }else{ raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n"); rc = 1; goto meta_command_exit; } } if( zName!=0 ){ int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0; if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){ char *new_argv[2], *new_colv[2]; new_argv[0] = sqlite3_mprintf( "CREATE TABLE %s (\n" " type text,\n" " name text,\n" " tbl_name text,\n" " rootpage integer,\n" " sql text\n" ")", isMaster ? "sqlite_master" : "sqlite_temp_master"); new_argv[1] = 0; new_colv[0] = "sql"; new_colv[1] = 0; callback(&data, 1, new_argv, new_colv); sqlite3_free(new_argv[0]); } } if( zDiv ){ sqlite3_stmt *pStmt = 0; rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", -1, &pStmt, 0); if( rc ){ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); sqlite3_finalize(pStmt); rc = 1; goto meta_command_exit; } appendText(&sSelect, "SELECT sql FROM", 0); iSchema = 0; while( sqlite3_step(pStmt)==SQLITE_ROW ){ const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); char zScNum[30]; sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); appendText(&sSelect, zDiv, 0); zDiv = " UNION ALL "; appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); if( sqlite3_stricmp(zDb, "main")!=0 ){ appendText(&sSelect, zDb, '"'); }else{ appendText(&sSelect, "NULL", 0); } appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); appendText(&sSelect, zScNum, 0); appendText(&sSelect, " AS snum, ", 0); appendText(&sSelect, zDb, '\''); appendText(&sSelect, " AS sname FROM ", 0); appendText(&sSelect, zDb, '"'); appendText(&sSelect, ".sqlite_master", 0); } sqlite3_finalize(pStmt); #ifdef SQLITE_INTROSPECTION_PRAGMAS if( zName ){ appendText(&sSelect, " UNION ALL SELECT shell_module_schema(name)," " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0); } #endif appendText(&sSelect, ") WHERE ", 0); if( zName ){ char *zQarg = sqlite3_mprintf("%Q", zName); int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || strchr(zName, '[') != 0; if( strchr(zName, '.') ){ appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); }else{ appendText(&sSelect, "lower(tbl_name)", 0); } appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); appendText(&sSelect, zQarg, 0); if( !bGlob ){ appendText(&sSelect, " ESCAPE '\\' ", 0); } appendText(&sSelect, " AND ", 0); sqlite3_free(zQarg); } appendText(&sSelect, "type!='meta' AND sql IS NOT NULL" " ORDER BY snum, rowid", 0); if( bDebug ){ utf8_printf(p->out, "SQL: %s;\n", sSelect.z); }else{ rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); } freeText(&sSelect); } if( zErrMsg ){ utf8_printf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); rc = 1; }else if( rc != SQLITE_OK ){ raw_printf(stderr,"Error: querying schema information\n"); rc = 1; }else{ rc = 0; } }else #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ sqlite3SelectTrace = (int)integerValue(azArg[1]); }else #endif #if defined(SQLITE_ENABLE_SESSION) if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ OpenSession *pSession = &p->aSession[0]; char **azCmd = &azArg[1]; int iSes = 0; int nCmd = nArg - 1; int i; if( nArg<=1 ) goto session_syntax_error; open_db(p, 0); if( nArg>=3 ){ for(iSes=0; iSes<p->nSession; iSes++){ if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break; } if( iSes<p->nSession ){ pSession = &p->aSession[iSes]; azCmd++; nCmd--; }else{ pSession = &p->aSession[0]; iSes = 0; } } /* .session attach TABLE ** Invoke the sqlite3session_attach() interface to attach a particular ** table so that it is never filtered. */ if( strcmp(azCmd[0],"attach")==0 ){ if( nCmd!=2 ) goto session_syntax_error; if( pSession->p==0 ){ session_not_open: raw_printf(stderr, "ERROR: No sessions are open\n"); }else{ rc = sqlite3session_attach(pSession->p, azCmd[1]); if( rc ){ raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); rc = 0; } } }else /* .session changeset FILE ** .session patchset FILE ** Write a changeset or patchset into a file. The file is overwritten. */ if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ FILE *out = 0; if( nCmd!=2 ) goto session_syntax_error; if( pSession->p==0 ) goto session_not_open; out = fopen(azCmd[1], "wb"); if( out==0 ){ utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]); }else{ int szChng; void *pChng; if( azCmd[0][0]=='c' ){ rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); }else{ rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); } if( rc ){ printf("Error: error code %d\n", rc); rc = 0; } if( pChng && fwrite(pChng, szChng, 1, out)!=1 ){ raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", szChng); } sqlite3_free(pChng); fclose(out); } }else /* .session close ** Close the identified session */ if( strcmp(azCmd[0], "close")==0 ){ if( nCmd!=1 ) goto session_syntax_error; if( p->nSession ){ session_close(pSession); p->aSession[iSes] = p->aSession[--p->nSession]; } }else /* .session enable ?BOOLEAN? ** Query or set the enable flag */ if( strcmp(azCmd[0], "enable")==0 ){ int ii; if( nCmd>2 ) goto session_syntax_error; ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); if( p->nSession ){ ii = sqlite3session_enable(pSession->p, ii); utf8_printf(p->out, "session %s enable flag = %d\n", pSession->zName, ii); } }else /* .session filter GLOB .... ** Set a list of GLOB patterns of table names to be excluded. */ if( strcmp(azCmd[0], "filter")==0 ){ int ii, nByte; if( nCmd<2 ) goto session_syntax_error; if( p->nSession ){ for(ii=0; ii<pSession->nFilter; ii++){ sqlite3_free(pSession->azFilter[ii]); } sqlite3_free(pSession->azFilter); nByte = sizeof(pSession->azFilter[0])*(nCmd-1); pSession->azFilter = sqlite3_malloc( nByte ); if( pSession->azFilter==0 ){ raw_printf(stderr, "Error: out or memory\n"); exit(1); } for(ii=1; ii<nCmd; ii++){ pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); } pSession->nFilter = ii-1; } }else /* .session indirect ?BOOLEAN? ** Query or set the indirect flag */ if( strcmp(azCmd[0], "indirect")==0 ){ int ii; if( nCmd>2 ) goto session_syntax_error; ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); if( p->nSession ){ ii = sqlite3session_indirect(pSession->p, ii); utf8_printf(p->out, "session %s indirect flag = %d\n", pSession->zName, ii); } }else /* .session isempty ** Determine if the session is empty */ if( strcmp(azCmd[0], "isempty")==0 ){ int ii; if( nCmd!=1 ) goto session_syntax_error; if( p->nSession ){ ii = sqlite3session_isempty(pSession->p); utf8_printf(p->out, "session %s isempty flag = %d\n", pSession->zName, ii); } }else /* .session list ** List all currently open sessions */ if( strcmp(azCmd[0],"list")==0 ){ for(i=0; i<p->nSession; i++){ utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName); } }else /* .session open DB NAME ** Open a new session called NAME on the attached database DB. ** DB is normally "main". */ if( strcmp(azCmd[0],"open")==0 ){ char *zName; if( nCmd!=3 ) goto session_syntax_error; zName = azCmd[2]; if( zName[0]==0 ) goto session_syntax_error; for(i=0; i<p->nSession; i++){ if( strcmp(p->aSession[i].zName,zName)==0 ){ utf8_printf(stderr, "Session \"%s\" already exists\n", zName); goto meta_command_exit; } } if( p->nSession>=ArraySize(p->aSession) ){ raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession)); goto meta_command_exit; } pSession = &p->aSession[p->nSession]; rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); if( rc ){ raw_printf(stderr, "Cannot open session: error code=%d\n", rc); rc = 0; goto meta_command_exit; } pSession->nFilter = 0; sqlite3session_table_filter(pSession->p, session_filter, pSession); p->nSession++; pSession->zName = sqlite3_mprintf("%s", zName); }else /* If no command name matches, show a syntax error */ session_syntax_error: session_help(p); }else #endif #ifdef SQLITE_DEBUG /* Undocumented commands for internal testing. Subject to change ** without notice. */ if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ int i, v; for(i=1; i<nArg; i++){ v = booleanValue(azArg[i]); utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); } } if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ int i; sqlite3_int64 v; for(i=1; i<nArg; i++){ char zBuf[200]; v = integerValue(azArg[i]); sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); utf8_printf(p->out, "%s", zBuf); } } }else #endif if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ int bIsInit = 0; /* True to initialize the SELFTEST table */ int bVerbose = 0; /* Verbose output */ int bSelftestExists; /* True if SELFTEST already exists */ int i, k; /* Loop counters */ int nTest = 0; /* Number of tests runs */ int nErr = 0; /* Number of errors seen */ ShellText str; /* Answer for a query */ sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ open_db(p,0); for(i=1; i<nArg; i++){ const char *z = azArg[i]; if( z[0]=='-' && z[1]=='-' ) z++; if( strcmp(z,"-init")==0 ){ bIsInit = 1; }else if( strcmp(z,"-v")==0 ){ bVerbose++; }else { utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]); raw_printf(stderr, "Should be one of: --init -v\n"); rc = 1; goto meta_command_exit; } } if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) != SQLITE_OK ){ bSelftestExists = 0; }else{ bSelftestExists = 1; } if( bIsInit ){ createSelftestTable(p); bSelftestExists = 1; } initText(&str); appendText(&str, "x", 0); for(k=bSelftestExists; k>=0; k--){ if( k==1 ){ rc = sqlite3_prepare_v2(p->db, "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", -1, &pStmt, 0); }else{ rc = sqlite3_prepare_v2(p->db, "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," " (1,'run','PRAGMA integrity_check','ok')", -1, &pStmt, 0); } if( rc ){ raw_printf(stderr, "Error querying the selftest table\n"); rc = 1; sqlite3_finalize(pStmt); goto meta_command_exit; } for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ int tno = sqlite3_column_int(pStmt, 0); const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); k = 0; if( bVerbose>0 ){ char *zQuote = sqlite3_mprintf("%q", zSql); printf("%d: %s %s\n", tno, zOp, zSql); sqlite3_free(zQuote); } if( strcmp(zOp,"memo")==0 ){ utf8_printf(p->out, "%s\n", zSql); }else if( strcmp(zOp,"run")==0 ){ char *zErrMsg = 0; str.n = 0; str.z[0] = 0; rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); nTest++; if( bVerbose ){ utf8_printf(p->out, "Result: %s\n", str.z); } if( rc || zErrMsg ){ nErr++; rc = 1; utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); sqlite3_free(zErrMsg); }else if( strcmp(zAns,str.z)!=0 ){ nErr++; rc = 1; utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); } }else { utf8_printf(stderr, "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); rc = 1; break; } } /* End loop over rows of content from SELFTEST */ sqlite3_finalize(pStmt); } /* End loop over k */ freeText(&str); utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); }else if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ if( nArg<2 || nArg>3 ){ raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); rc = 1; } if( nArg>=2 ){ sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); } if( nArg>=3 ){ sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); } }else if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ const char *zLike = 0; /* Which table to checksum. 0 means everything */ int i; /* Loop counter */ int bSchema = 0; /* Also hash the schema */ int bSeparate = 0; /* Hash each table separately */ int iSize = 224; /* Hash algorithm to use */ int bDebug = 0; /* Only show the query that would have run */ sqlite3_stmt *pStmt; /* For querying tables names */ char *zSql; /* SQL to be run */ char *zSep; /* Separator */ ShellText sSql; /* Complete SQL for the query to run the hash */ ShellText sQuery; /* Set of queries used to read all content */ open_db(p, 0); for(i=1; i<nArg; i++){ const char *z = azArg[i]; if( z[0]=='-' ){ z++; if( z[0]=='-' ) z++; if( strcmp(z,"schema")==0 ){ bSchema = 1; }else if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 ){ iSize = atoi(&z[5]); }else if( strcmp(z,"debug")==0 ){ bDebug = 1; }else { utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]); raw_printf(stderr, "Should be one of: --schema" " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n"); rc = 1; goto meta_command_exit; } }else if( zLike ){ raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); rc = 1; goto meta_command_exit; }else{ zLike = z; bSeparate = 1; if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; } } if( bSchema ){ zSql = "SELECT lower(name) FROM sqlite_master" " WHERE type='table' AND coalesce(rootpage,0)>1" " UNION ALL SELECT 'sqlite_master'" " ORDER BY 1 collate nocase"; }else{ zSql = "SELECT lower(name) FROM sqlite_master" " WHERE type='table' AND coalesce(rootpage,0)>1" " AND name NOT LIKE 'sqlite_%'" " ORDER BY 1 collate nocase"; } sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); initText(&sQuery); initText(&sSql); appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); zSep = "VALUES("; while( SQLITE_ROW==sqlite3_step(pStmt) ){ const char *zTab = (const char*)sqlite3_column_text(pStmt,0); if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; if( strncmp(zTab, "sqlite_",7)!=0 ){ appendText(&sQuery,"SELECT * FROM ", 0); appendText(&sQuery,zTab,'"'); appendText(&sQuery," NOT INDEXED;", 0); }else if( strcmp(zTab, "sqlite_master")==0 ){ appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master" " ORDER BY name;", 0); }else if( strcmp(zTab, "sqlite_sequence")==0 ){ appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" " ORDER BY name;", 0); }else if( strcmp(zTab, "sqlite_stat1")==0 ){ appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" " ORDER BY tbl,idx;", 0); }else if( strcmp(zTab, "sqlite_stat3")==0 || strcmp(zTab, "sqlite_stat4")==0 ){ appendText(&sQuery, "SELECT * FROM ", 0); appendText(&sQuery, zTab, 0); appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); } appendText(&sSql, zSep, 0); appendText(&sSql, sQuery.z, '\''); sQuery.n = 0; appendText(&sSql, ",", 0); appendText(&sSql, zTab, '\''); zSep = "),("; } sqlite3_finalize(pStmt); if( bSeparate ){ zSql = sqlite3_mprintf( "%s))" " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" " FROM [sha3sum$query]", sSql.z, iSize); }else{ zSql = sqlite3_mprintf( "%s))" " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" " FROM [sha3sum$query]", sSql.z, iSize); } freeText(&sQuery); freeText(&sSql); if( bDebug ){ utf8_printf(p->out, "%s\n", zSql); }else{ shell_exec(p, zSql, 0); } sqlite3_free(zSql); }else #ifndef SQLITE_NOHAVE_SYSTEM if( c=='s' && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) ){ char *zCmd; int i, x; if( nArg<2 ){ raw_printf(stderr, "Usage: .system COMMAND\n"); rc = 1; goto meta_command_exit; } zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); for(i=2; i<nArg; i++){ zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", zCmd, azArg[i]); } x = system(zCmd); sqlite3_free(zCmd); if( x ) raw_printf(stderr, "System command returns %d\n", x); }else #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ static const char *azBool[] = { "off", "on", "trigger", "full"}; int i; if( nArg!=1 ){ raw_printf(stderr, "Usage: .show\n"); rc = 1; goto meta_command_exit; } utf8_printf(p->out, "%12.12s: %s\n","echo", azBool[ShellHasFlag(p, SHFLG_Echo)]); utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); utf8_printf(p->out, "%12.12s: %s\n","explain", p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); utf8_printf(p->out, "%12.12s: ", "nullvalue"); output_c_string(p->out, p->nullValue); raw_printf(p->out, "\n"); utf8_printf(p->out,"%12.12s: %s\n","output", strlen30(p->outfile) ? p->outfile : "stdout"); utf8_printf(p->out,"%12.12s: ", "colseparator"); output_c_string(p->out, p->colSeparator); raw_printf(p->out, "\n"); utf8_printf(p->out,"%12.12s: ", "rowseparator"); output_c_string(p->out, p->rowSeparator); raw_printf(p->out, "\n"); utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]); utf8_printf(p->out, "%12.12s: ", "width"); for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { raw_printf(p->out, "%d ", p->colWidth[i]); } raw_printf(p->out, "\n"); utf8_printf(p->out, "%12.12s: %s\n", "filename", p->zDbFilename ? p->zDbFilename : ""); }else if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ if( nArg==2 ){ p->statsOn = (u8)booleanValue(azArg[1]); }else if( nArg==1 ){ display_stats(p->db, p, 0); }else{ raw_printf(stderr, "Usage: .stats ?on|off?\n"); rc = 1; } }else if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) || (c=='i' && (strncmp(azArg[0], "indices", n)==0 || strncmp(azArg[0], "indexes", n)==0) ) ){ sqlite3_stmt *pStmt; char **azResult; int nRow, nAlloc; int ii; ShellText s; initText(&s); open_db(p, 0); rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); if( rc ) return shellDatabaseError(p->db); if( nArg>2 && c=='i' ){ /* It is an historical accident that the .indexes command shows an error ** when called with the wrong number of arguments whereas the .tables ** command does not. */ raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); rc = 1; goto meta_command_exit; } for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); if( zDbName==0 ) continue; if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); if( sqlite3_stricmp(zDbName, "main")==0 ){ appendText(&s, "SELECT name FROM ", 0); }else{ appendText(&s, "SELECT ", 0); appendText(&s, zDbName, '\''); appendText(&s, "||'.'||name FROM ", 0); } appendText(&s, zDbName, '"'); appendText(&s, ".sqlite_master ", 0); if( c=='t' ){ appendText(&s," WHERE type IN ('table','view')" " AND name NOT LIKE 'sqlite_%'" " AND name LIKE ?1", 0); }else{ appendText(&s," WHERE type='index'" " AND tbl_name LIKE ?1", 0); } } rc = sqlite3_finalize(pStmt); appendText(&s, " ORDER BY 1", 0); rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); freeText(&s); if( rc ) return shellDatabaseError(p->db); /* Run the SQL statement prepared by the above block. Store the results ** as an array of nul-terminated strings in azResult[]. */ nRow = nAlloc = 0; azResult = 0; if( nArg>1 ){ sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); }else{ sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); } while( sqlite3_step(pStmt)==SQLITE_ROW ){ if( nRow>=nAlloc ){ char **azNew; int n2 = nAlloc*2 + 10; azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); if( azNew==0 ){ rc = shellNomemError(); break; } nAlloc = n2; azResult = azNew; } azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); if( 0==azResult[nRow] ){ rc = shellNomemError(); break; } nRow++; } if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ rc = shellDatabaseError(p->db); } /* Pretty-print the contents of array azResult[] to the output */ if( rc==0 && nRow>0 ){ int len, maxlen = 0; int i, j; int nPrintCol, nPrintRow; for(i=0; i<nRow; i++){ len = strlen30(azResult[i]); if( len>maxlen ) maxlen = len; } nPrintCol = 80/(maxlen+2); if( nPrintCol<1 ) nPrintCol = 1; nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; for(i=0; i<nPrintRow; i++){ for(j=i; j<nRow; j+=nPrintRow){ char *zSp = j<nPrintRow ? "" : " "; utf8_printf(p->out, "%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:""); } raw_printf(p->out, "\n"); } } for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); sqlite3_free(azResult); }else /* Begin redirecting output to the file "testcase-out.txt" */ if( c=='t' && strcmp(azArg[0],"testcase")==0 ){ output_reset(p); p->out = output_file_open("testcase-out.txt", 0); if( p->out==0 ){ raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); } if( nArg>=2 ){ sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); }else{ sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); } }else #ifndef SQLITE_UNTESTABLE if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ static const struct { const char *zCtrlName; /* Name of a test-control option */ int ctrlCode; /* Integer code for that option */ const char *zUsage; /* Usage notes */ } aCtrl[] = { { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" }, { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" }, /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/ /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/ { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" }, /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */ { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"}, #ifdef SQLITE_N_KEYWORD { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD, "IDENTIFIER" }, #endif { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" }, { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" }, { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" }, #ifdef YYCOVERAGE { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" }, #endif { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " }, { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" }, { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" }, { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" }, { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" }, }; int testctrl = -1; int iCtrl = -1; int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ int isOk = 0; int i, n2; const char *zCmd = 0; open_db(p, 0); zCmd = nArg>=2 ? azArg[1] : "help"; /* The argument can optionally begin with "-" or "--" */ if( zCmd[0]=='-' && zCmd[1] ){ zCmd++; if( zCmd[0]=='-' && zCmd[1] ) zCmd++; } /* --help lists all test-controls */ if( strcmp(zCmd,"help")==0 ){ utf8_printf(p->out, "Available test-controls:\n"); for(i=0; i<ArraySize(aCtrl); i++){ utf8_printf(p->out, " .testctrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage); } rc = 1; goto meta_command_exit; } /* convert testctrl text option to value. allow any unique prefix ** of the option name, or a numerical value. */ n2 = strlen30(zCmd); for(i=0; i<ArraySize(aCtrl); i++){ if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ if( testctrl<0 ){ testctrl = aCtrl[i].ctrlCode; iCtrl = i; }else{ utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" "Use \".testctrl --help\" for help\n", zCmd); rc = 1; goto meta_command_exit; } } } if( testctrl<0 ){ utf8_printf(stderr,"Error: unknown test-control: %s\n" "Use \".testctrl --help\" for help\n", zCmd); }else{ switch(testctrl){ /* sqlite3_test_control(int, db, int) */ case SQLITE_TESTCTRL_OPTIMIZATIONS: case SQLITE_TESTCTRL_RESERVE: if( nArg==3 ){ int opt = (int)strtol(azArg[2], 0, 0); rc2 = sqlite3_test_control(testctrl, p->db, opt); isOk = 3; } break; /* sqlite3_test_control(int) */ case SQLITE_TESTCTRL_PRNG_SAVE: case SQLITE_TESTCTRL_PRNG_RESTORE: case SQLITE_TESTCTRL_PRNG_RESET: case SQLITE_TESTCTRL_BYTEORDER: if( nArg==2 ){ rc2 = sqlite3_test_control(testctrl); isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; } break; /* sqlite3_test_control(int, uint) */ case SQLITE_TESTCTRL_PENDING_BYTE: if( nArg==3 ){ unsigned int opt = (unsigned int)integerValue(azArg[2]); rc2 = sqlite3_test_control(testctrl, opt); isOk = 3; } break; /* sqlite3_test_control(int, int) */ case SQLITE_TESTCTRL_ASSERT: case SQLITE_TESTCTRL_ALWAYS: if( nArg==3 ){ int opt = booleanValue(azArg[2]); rc2 = sqlite3_test_control(testctrl, opt); isOk = 1; } break; /* sqlite3_test_control(int, int) */ case SQLITE_TESTCTRL_LOCALTIME_FAULT: case SQLITE_TESTCTRL_NEVER_CORRUPT: if( nArg==3 ){ int opt = booleanValue(azArg[2]); rc2 = sqlite3_test_control(testctrl, opt); isOk = 3; } break; /* sqlite3_test_control(int, char *) */ #ifdef SQLITE_N_KEYWORD case SQLITE_TESTCTRL_ISKEYWORD: if( nArg==3 ){ const char *opt = azArg[2]; rc2 = sqlite3_test_control(testctrl, opt); isOk = 1; } break; #endif case SQLITE_TESTCTRL_IMPOSTER: if( nArg==5 ){ rc2 = sqlite3_test_control(testctrl, p->db, azArg[2], integerValue(azArg[3]), integerValue(azArg[4])); isOk = 3; } break; #ifdef YYCOVERAGE case SQLITE_TESTCTRL_PARSER_COVERAGE: if( nArg==2 ){ sqlite3_test_control(testctrl, p->out); isOk = 3; } #endif } } if( isOk==0 && iCtrl>=0 ){ utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage); rc = 1; }else if( isOk==1 ){ raw_printf(p->out, "%d\n", rc2); }else if( isOk==2 ){ raw_printf(p->out, "0x%08x\n", rc2); } }else #endif /* !defined(SQLITE_UNTESTABLE) */ if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ open_db(p, 0); sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); }else if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ if( nArg==2 ){ enableTimer = booleanValue(azArg[1]); if( enableTimer && !HAS_TIMER ){ raw_printf(stderr, "Error: timer not available on this system.\n"); enableTimer = 0; } }else{ raw_printf(stderr, "Usage: .timer on|off\n"); rc = 1; } }else if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ open_db(p, 0); if( nArg!=2 ){ raw_printf(stderr, "Usage: .trace FILE|off\n"); rc = 1; goto meta_command_exit; } output_file_close(p->traceOut); p->traceOut = output_file_open(azArg[1], 0); #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) if( p->traceOut==0 ){ sqlite3_trace_v2(p->db, 0, 0, 0); }else{ sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut); } #endif }else #if SQLITE_USER_AUTHENTICATION if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ if( nArg<2 ){ raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); rc = 1; goto meta_command_exit; } open_db(p, 0); if( strcmp(azArg[1],"login")==0 ){ if( nArg!=4 ){ raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3])); if( rc ){ utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); rc = 1; } }else if( strcmp(azArg[1],"add")==0 ){ if( nArg!=5 ){ raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), booleanValue(azArg[4])); if( rc ){ raw_printf(stderr, "User-Add failed: %d\n", rc); rc = 1; } }else if( strcmp(azArg[1],"edit")==0 ){ if( nArg!=5 ){ raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), booleanValue(azArg[4])); if( rc ){ raw_printf(stderr, "User-Edit failed: %d\n", rc); rc = 1; } }else if( strcmp(azArg[1],"delete")==0 ){ if( nArg!=3 ){ raw_printf(stderr, "Usage: .user delete USER\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_user_delete(p->db, azArg[2]); if( rc ){ raw_printf(stderr, "User-Delete failed: %d\n", rc); rc = 1; } }else{ raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); rc = 1; goto meta_command_exit; } }else #endif /* SQLITE_USER_AUTHENTICATION */ if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, sqlite3_libversion(), sqlite3_sourceid()); #if SQLITE_HAVE_ZLIB utf8_printf(p->out, "zlib version %s\n", zlibVersion()); #endif #define CTIMEOPT_VAL_(opt) #opt #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) #if defined(__clang__) && defined(__clang_major__) utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." CTIMEOPT_VAL(__clang_minor__) "." CTIMEOPT_VAL(__clang_patchlevel__) "\n"); #elif defined(_MSC_VER) utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); #elif defined(__GNUC__) && defined(__VERSION__) utf8_printf(p->out, "gcc-" __VERSION__ "\n"); #endif }else if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ const char *zDbName = nArg==2 ? azArg[1] : "main"; sqlite3_vfs *pVfs = 0; if( p->db ){ sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); if( pVfs ){ utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); } } }else if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ sqlite3_vfs *pVfs; sqlite3_vfs *pCurrent = 0; if( p->db ){ sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); } for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, pVfs==pCurrent ? " <--- CURRENT" : ""); raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); if( pVfs->pNext ){ raw_printf(p->out, "-----------------------------------\n"); } } }else if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ const char *zDbName = nArg==2 ? azArg[1] : "main"; char *zVfsName = 0; if( p->db ){ sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); if( zVfsName ){ utf8_printf(p->out, "%s\n", zVfsName); sqlite3_free(zVfsName); } } }else #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff; }else #endif if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ int j; assert( nArg<=ArraySize(azArg) ); for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){ p->colWidth[j-1] = (int)integerValue(azArg[j]); } }else { utf8_printf(stderr, "Error: unknown command or invalid arguments: " " \"%s\". Enter \".help\" for help\n", azArg[0]); rc = 1; } meta_command_exit: if( p->outCount ){ p->outCount--; if( p->outCount==0 ) output_reset(p); } return rc; } /* ** Return TRUE if a semicolon occurs anywhere in the first N characters ** of string z[]. */ static int line_contains_semicolon(const char *z, int N){ int i; for(i=0; i<N; i++){ if( z[i]==';' ) return 1; } return 0; } /* ** Test to see if a line consists entirely of whitespace. */ static int _all_whitespace(const char *z){ for(; *z; z++){ if( IsSpace(z[0]) ) continue; if( *z=='/' && z[1]=='*' ){ z += 2; while( *z && (*z!='*' || z[1]!='/') ){ z++; } if( *z==0 ) return 0; z++; continue; } if( *z=='-' && z[1]=='-' ){ z += 2; while( *z && *z!='\n' ){ z++; } if( *z==0 ) return 1; continue; } return 0; } return 1; } /* ** Return TRUE if the line typed in is an SQL command terminator other ** than a semi-colon. The SQL Server style "go" command is understood ** as is the Oracle "/". */ static int line_is_command_terminator(const char *zLine){ while( IsSpace(zLine[0]) ){ zLine++; }; if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){ return 1; /* Oracle */ } if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' && _all_whitespace(&zLine[2]) ){ return 1; /* SQL Server */ } return 0; } /* ** We need a default sqlite3_complete() implementation to use in case ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes ** any arbitrary text is a complete SQL statement. This is not very ** user-friendly, but it does seem to work. */ #ifdef SQLITE_OMIT_COMPLETE int sqlite3_complete(const char *zSql){ return 1; } #endif /* ** Return true if zSql is a complete SQL statement. Return false if it ** ends in the middle of a string literal or C-style comment. */ static int line_is_complete(char *zSql, int nSql){ int rc; if( zSql==0 ) return 1; zSql[nSql] = ';'; zSql[nSql+1] = 0; rc = sqlite3_complete(zSql); zSql[nSql] = 0; return rc; } /* ** Run a single line of SQL */ static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ int rc; char *zErrMsg = 0; open_db(p, 0); if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); BEGIN_TIMER; rc = shell_exec(p, zSql, &zErrMsg); END_TIMER; if( rc || zErrMsg ){ char zPrefix[100]; if( in!=0 || !stdin_is_interactive ){ sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error: near line %d:", startline); }else{ sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); } if( zErrMsg!=0 ){ utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); sqlite3_free(zErrMsg); zErrMsg = 0; }else{ utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); } return 1; }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ raw_printf(p->out, "changes: %3d total_changes: %d\n", sqlite3_changes(p->db), sqlite3_total_changes(p->db)); } return 0; } /* ** Read input from *in and process it. If *in==0 then input ** is interactive - the user is typing it it. Otherwise, input ** is coming from a file or device. A prompt is issued and history ** is saved only if input is interactive. An interrupt signal will ** cause this routine to exit immediately, unless input is interactive. ** ** Return the number of errors. */ static int process_input(ShellState *p, FILE *in){ char *zLine = 0; /* A single input line */ char *zSql = 0; /* Accumulated SQL text */ int nLine; /* Length of current line */ int nSql = 0; /* Bytes of zSql[] used */ int nAlloc = 0; /* Allocated zSql[] space */ int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */ int rc; /* Error code */ int errCnt = 0; /* Number of errors seen */ int lineno = 0; /* Current line number */ int startline = 0; /* Line number for start of current input */ while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){ fflush(p->out); zLine = one_input_line(in, zLine, nSql>0); if( zLine==0 ){ /* End of input */ if( in==0 && stdin_is_interactive ) printf("\n"); break; } if( seenInterrupt ){ if( in!=0 ) break; seenInterrupt = 0; } lineno++; if( nSql==0 && _all_whitespace(zLine) ){ if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); continue; } if( zLine && zLine[0]=='.' && nSql==0 ){ if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); rc = do_meta_command(zLine, p); if( rc==2 ){ /* exit requested */ break; }else if( rc ){ errCnt++; } continue; } if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ memcpy(zLine,";",2); } nLine = strlen30(zLine); if( nSql+nLine+2>=nAlloc ){ nAlloc = nSql+nLine+100; zSql = realloc(zSql, nAlloc); if( zSql==0 ){ raw_printf(stderr, "Error: out of memory\n"); exit(1); } } nSqlPrior = nSql; if( nSql==0 ){ int i; for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} assert( nAlloc>0 && zSql!=0 ); memcpy(zSql, zLine+i, nLine+1-i); startline = lineno; nSql = nLine-i; }else{ zSql[nSql++] = '\n'; memcpy(zSql+nSql, zLine, nLine+1); nSql += nLine; } if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) && sqlite3_complete(zSql) ){ errCnt += runOneSqlLine(p, zSql, in, startline); nSql = 0; if( p->outCount ){ output_reset(p); p->outCount = 0; }else{ clearTempFile(p); } }else if( nSql && _all_whitespace(zSql) ){ if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); nSql = 0; } } if( nSql && !_all_whitespace(zSql) ){ runOneSqlLine(p, zSql, in, startline); } free(zSql); free(zLine); return errCnt>0; } /* ** Return a pathname which is the user's home directory. A ** 0 return indicates an error of some kind. */ static char *find_home_dir(int clearFlag){ static char *home_dir = NULL; if( clearFlag ){ free(home_dir); home_dir = 0; return 0; } if( home_dir ) return home_dir; #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ && !defined(__RTP__) && !defined(_WRS_KERNEL) { struct passwd *pwent; uid_t uid = getuid(); if( (pwent=getpwuid(uid)) != NULL) { home_dir = pwent->pw_dir; } } #endif #if defined(_WIN32_WCE) /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() */ home_dir = "/"; #else #if defined(_WIN32) || defined(WIN32) if (!home_dir) { home_dir = getenv("USERPROFILE"); } #endif if (!home_dir) { home_dir = getenv("HOME"); } #if defined(_WIN32) || defined(WIN32) if (!home_dir) { char *zDrive, *zPath; int n; zDrive = getenv("HOMEDRIVE"); zPath = getenv("HOMEPATH"); if( zDrive && zPath ){ n = strlen30(zDrive) + strlen30(zPath) + 1; home_dir = malloc( n ); if( home_dir==0 ) return 0; sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); return home_dir; } home_dir = "c:\\"; } #endif #endif /* !_WIN32_WCE */ if( home_dir ){ int n = strlen30(home_dir) + 1; char *z = malloc( n ); if( z ) memcpy(z, home_dir, n); home_dir = z; } return home_dir; } /* ** Read input from the file given by sqliterc_override. Or if that ** parameter is NULL, take input from ~/.sqliterc ** ** Returns the number of errors. */ static void process_sqliterc( ShellState *p, /* Configuration data */ const char *sqliterc_override /* Name of config file. NULL to use default */ ){ char *home_dir = NULL; const char *sqliterc = sqliterc_override; char *zBuf = 0; FILE *in = NULL; if (sqliterc == NULL) { home_dir = find_home_dir(0); if( home_dir==0 ){ raw_printf(stderr, "-- warning: cannot find home directory;" " cannot read ~/.sqliterc\n"); return; } sqlite3_initialize(); zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); sqliterc = zBuf; } in = fopen(sqliterc,"rb"); if( in ){ if( stdin_is_interactive ){ utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); } process_input(p,in); fclose(in); } sqlite3_free(zBuf); } /* ** Show available command line options */ static const char zOptions[] = #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) " -A ARGS... run \".archive ARGS\" and exit\n" #endif " -append append the database to the end of the file\n" " -ascii set output mode to 'ascii'\n" " -bail stop after hitting an error\n" " -batch force batch I/O\n" " -column set output mode to 'column'\n" " -cmd COMMAND run \"COMMAND\" before reading stdin\n" " -csv set output mode to 'csv'\n" " -echo print commands before execution\n" " -init FILENAME read/process named file\n" " -[no]header turn headers on or off\n" #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) " -heap SIZE Size of heap for memsys3 or memsys5\n" #endif " -help show this message\n" " -html set output mode to HTML\n" " -interactive force interactive I/O\n" " -line set output mode to 'line'\n" " -list set output mode to 'list'\n" " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" " -mmap N default mmap size set to N\n" #ifdef SQLITE_ENABLE_MULTIPLEX " -multiplex enable the multiplexor VFS\n" #endif " -newline SEP set output row separator. Default: '\\n'\n" " -nullvalue TEXT set text string for NULL values. Default ''\n" " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" " -quote set output mode to 'quote'\n" " -readonly open the database read-only\n" " -separator SEP set output column separator. Default: '|'\n" " -stats print memory stats before each finalize\n" " -version show SQLite version\n" " -vfs NAME use NAME as the default VFS\n" #ifdef SQLITE_ENABLE_VFSTRACE " -vfstrace enable tracing of all VFS calls\n" #endif #ifdef SQLITE_HAVE_ZLIB " -zip open the file as a ZIP Archive\n" #endif ; static void usage(int showDetail){ utf8_printf(stderr, "Usage: %s [OPTIONS] FILENAME [SQL]\n" "FILENAME is the name of an SQLite database. A new database is created\n" "if the file does not previously exist.\n", Argv0); if( showDetail ){ utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); }else{ raw_printf(stderr, "Use the -help option for additional information\n"); } exit(1); } /* ** Initialize the state information in data */ static void main_init(ShellState *data) { memset(data, 0, sizeof(*data)); data->normalMode = data->cMode = data->mode = MODE_List; data->autoExplain = 1; memcpy(data->colSeparator,SEP_Column, 2); memcpy(data->rowSeparator,SEP_Row, 2); data->showHeader = 0; data->shellFlgs = SHFLG_Lookaside; sqlite3_config(SQLITE_CONFIG_URI, 1); sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); sqlite3_config(SQLITE_CONFIG_MULTITHREAD); sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); } /* ** Output text to the console in a font that attracts extra attention. */ #ifdef _WIN32 static void printBold(const char *zText){ HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; GetConsoleScreenBufferInfo(out, &defaultScreenInfo); SetConsoleTextAttribute(out, FOREGROUND_RED|FOREGROUND_INTENSITY ); printf("%s", zText); SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); } #else static void printBold(const char *zText){ printf("\033[1m%s\033[0m", zText); } #endif /* ** Get the argument to an --option. Throw an error and die if no argument ** is available. */ static char *cmdline_option_value(int argc, char **argv, int i){ if( i==argc ){ utf8_printf(stderr, "%s: Error: missing argument to %s\n", argv[0], argv[argc-1]); exit(1); } return argv[i]; } #ifndef SQLITE_SHELL_IS_UTF8 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) # define SQLITE_SHELL_IS_UTF8 (0) # else # define SQLITE_SHELL_IS_UTF8 (1) # endif #endif #if SQLITE_SHELL_IS_UTF8 int SQLITE_CDECL main(int argc, char **argv){ #else int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ char **argv; #endif char *zErrMsg = 0; ShellState data; const char *zInitFile = 0; int i; int rc = 0; int warnInmemoryDb = 0; int readStdin = 1; int nCmd = 0; char **azCmd = 0; setBinaryMode(stdin, 0); setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ stdin_is_interactive = isatty(0); stdout_is_console = isatty(1); #if USE_SYSTEM_SQLITE+0!=1 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", sqlite3_sourceid(), SQLITE_SOURCE_ID); exit(1); } #endif main_init(&data); /* On Windows, we must translate command-line arguments into UTF-8. ** The SQLite memory allocator subsystem has to be enabled in order to ** do this. But we want to run an sqlite3_shutdown() afterwards so that ** subsequent sqlite3_config() calls will work. So copy all results into ** memory that does not come from the SQLite memory allocator. */ #if !SQLITE_SHELL_IS_UTF8 sqlite3_initialize(); argv = malloc(sizeof(argv[0])*argc); if( argv==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } for(i=0; i<argc; i++){ char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); int n; if( z==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } n = (int)strlen(z); argv[i] = malloc( n+1 ); if( argv[i]==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } memcpy(argv[i], z, n+1); sqlite3_free(z); } sqlite3_shutdown(); #endif assert( argc>=1 && argv && argv[0] ); Argv0 = argv[0]; /* Make sure we have a valid signal handler early, before anything ** else is done. */ #ifdef SIGINT signal(SIGINT, interrupt_handler); #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); #endif #ifdef SQLITE_SHELL_DBNAME_PROC { /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name ** of a C-function that will provide the name of the database file. Use ** this compile-time option to embed this shell program in larger ** applications. */ extern void SQLITE_SHELL_DBNAME_PROC(const char**); SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename); warnInmemoryDb = 0; } #endif /* Do an initial pass through the command-line argument to locate ** the name of the database file, the name of the initialization file, ** the size of the alternative malloc heap, ** and the first command to execute. */ for(i=1; i<argc; i++){ char *z; z = argv[i]; if( z[0]!='-' ){ if( data.zDbFilename==0 ){ data.zDbFilename = z; }else{ /* Excesss arguments are interpreted as SQL (or dot-commands) and ** mean that nothing is read from stdin */ readStdin = 0; nCmd++; azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); if( azCmd==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } azCmd[nCmd-1] = z; } } if( z[1]=='-' ) z++; if( strcmp(z,"-separator")==0 || strcmp(z,"-nullvalue")==0 || strcmp(z,"-newline")==0 || strcmp(z,"-cmd")==0 ){ (void)cmdline_option_value(argc, argv, ++i); }else if( strcmp(z,"-init")==0 ){ zInitFile = cmdline_option_value(argc, argv, ++i); }else if( strcmp(z,"-batch")==0 ){ /* Need to check for batch mode here to so we can avoid printing ** informational messages (like from process_sqliterc) before ** we do the actual processing of arguments later in a second pass. */ stdin_is_interactive = 0; }else if( strcmp(z,"-heap")==0 ){ #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) const char *zSize; sqlite3_int64 szHeap; zSize = cmdline_option_value(argc, argv, ++i); szHeap = integerValue(zSize); if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); #else (void)cmdline_option_value(argc, argv, ++i); #endif }else if( strcmp(z,"-pagecache")==0 ){ int n, sz; sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); if( sz>70000 ) sz = 70000; if( sz<0 ) sz = 0; n = (int)integerValue(cmdline_option_value(argc,argv,++i)); sqlite3_config(SQLITE_CONFIG_PAGECACHE, (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); data.shellFlgs |= SHFLG_Pagecache; }else if( strcmp(z,"-lookaside")==0 ){ int n, sz; sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); if( sz<0 ) sz = 0; n = (int)integerValue(cmdline_option_value(argc,argv,++i)); if( n<0 ) n = 0; sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; #ifdef SQLITE_ENABLE_VFSTRACE }else if( strcmp(z,"-vfstrace")==0 ){ extern int vfstrace_register( const char *zTraceName, const char *zOldVfsName, int (*xOut)(const char*,void*), void *pOutArg, int makeDefault ); vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); #endif #ifdef SQLITE_ENABLE_MULTIPLEX }else if( strcmp(z,"-multiplex")==0 ){ extern int sqlite3_multiple_initialize(const char*,int); sqlite3_multiplex_initialize(0, 1); #endif }else if( strcmp(z,"-mmap")==0 ){ sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); }else if( strcmp(z,"-vfs")==0 ){ sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i)); if( pVfs ){ sqlite3_vfs_register(pVfs, 1); }else{ utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); exit(1); } #ifdef SQLITE_HAVE_ZLIB }else if( strcmp(z,"-zip")==0 ){ data.openMode = SHELL_OPEN_ZIPFILE; #endif }else if( strcmp(z,"-append")==0 ){ data.openMode = SHELL_OPEN_APPENDVFS; }else if( strcmp(z,"-readonly")==0 ){ data.openMode = SHELL_OPEN_READONLY; #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) }else if( strncmp(z, "-A",2)==0 ){ /* All remaining command-line arguments are passed to the ".archive" ** command, so ignore them */ break; #endif } } if( data.zDbFilename==0 ){ #ifndef SQLITE_OMIT_MEMORYDB data.zDbFilename = ":memory:"; warnInmemoryDb = argc==1; #else utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); return 1; #endif } data.out = stdout; sqlite3_appendvfs_init(0,0,0); /* Go ahead and open the database file if it already exists. If the ** file does not exist, delay opening it. This prevents empty database ** files from being created if a user mistypes the database name argument ** to the sqlite command-line tool. */ if( access(data.zDbFilename, 0)==0 ){ open_db(&data, 0); } /* Process the initialization file if there is one. If no -init option ** is given on the command line, look for a file named ~/.sqliterc and ** try to process it. */ process_sqliterc(&data,zInitFile); /* Make a second pass through the command-line argument and set ** options. This second pass is delayed until after the initialization ** file is processed so that the command-line arguments will override ** settings in the initialization file. */ for(i=1; i<argc; i++){ char *z = argv[i]; if( z[0]!='-' ) continue; if( z[1]=='-' ){ z++; } if( strcmp(z,"-init")==0 ){ i++; }else if( strcmp(z,"-html")==0 ){ data.mode = MODE_Html; }else if( strcmp(z,"-list")==0 ){ data.mode = MODE_List; }else if( strcmp(z,"-quote")==0 ){ data.mode = MODE_Quote; }else if( strcmp(z,"-line")==0 ){ data.mode = MODE_Line; }else if( strcmp(z,"-column")==0 ){ data.mode = MODE_Column; }else if( strcmp(z,"-csv")==0 ){ data.mode = MODE_Csv; memcpy(data.colSeparator,",",2); #ifdef SQLITE_HAVE_ZLIB }else if( strcmp(z,"-zip")==0 ){ data.openMode = SHELL_OPEN_ZIPFILE; #endif }else if( strcmp(z,"-append")==0 ){ data.openMode = SHELL_OPEN_APPENDVFS; }else if( strcmp(z,"-readonly")==0 ){ data.openMode = SHELL_OPEN_READONLY; }else if( strcmp(z,"-ascii")==0 ){ data.mode = MODE_Ascii; sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit); sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record); }else if( strcmp(z,"-separator")==0 ){ sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, "%s",cmdline_option_value(argc,argv,++i)); }else if( strcmp(z,"-newline")==0 ){ sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, "%s",cmdline_option_value(argc,argv,++i)); }else if( strcmp(z,"-nullvalue")==0 ){ sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, "%s",cmdline_option_value(argc,argv,++i)); }else if( strcmp(z,"-header")==0 ){ data.showHeader = 1; }else if( strcmp(z,"-noheader")==0 ){ data.showHeader = 0; }else if( strcmp(z,"-echo")==0 ){ ShellSetFlag(&data, SHFLG_Echo); }else if( strcmp(z,"-eqp")==0 ){ data.autoEQP = AUTOEQP_on; }else if( strcmp(z,"-eqpfull")==0 ){ data.autoEQP = AUTOEQP_full; }else if( strcmp(z,"-stats")==0 ){ data.statsOn = 1; }else if( strcmp(z,"-scanstats")==0 ){ data.scanstatsOn = 1; }else if( strcmp(z,"-backslash")==0 ){ /* Undocumented command-line option: -backslash ** Causes C-style backslash escapes to be evaluated in SQL statements ** prior to sending the SQL into SQLite. Useful for injecting ** crazy bytes in the middle of SQL statements for testing and debugging. */ ShellSetFlag(&data, SHFLG_Backslash); }else if( strcmp(z,"-bail")==0 ){ bail_on_error = 1; }else if( strcmp(z,"-version")==0 ){ printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); return 0; }else if( strcmp(z,"-interactive")==0 ){ stdin_is_interactive = 1; }else if( strcmp(z,"-batch")==0 ){ stdin_is_interactive = 0; }else if( strcmp(z,"-heap")==0 ){ i++; }else if( strcmp(z,"-pagecache")==0 ){ i+=2; }else if( strcmp(z,"-lookaside")==0 ){ i+=2; }else if( strcmp(z,"-mmap")==0 ){ i++; }else if( strcmp(z,"-vfs")==0 ){ i++; #ifdef SQLITE_ENABLE_VFSTRACE }else if( strcmp(z,"-vfstrace")==0 ){ i++; #endif #ifdef SQLITE_ENABLE_MULTIPLEX }else if( strcmp(z,"-multiplex")==0 ){ i++; #endif }else if( strcmp(z,"-help")==0 ){ usage(1); }else if( strcmp(z,"-cmd")==0 ){ /* Run commands that follow -cmd first and separately from commands ** that simply appear on the command-line. This seems goofy. It would ** be better if all commands ran in the order that they appear. But ** we retain the goofy behavior for historical compatibility. */ if( i==argc-1 ) break; z = cmdline_option_value(argc,argv,++i); if( z[0]=='.' ){ rc = do_meta_command(z, &data); if( rc && bail_on_error ) return rc==2 ? 0 : rc; }else{ open_db(&data, 0); rc = shell_exec(&data, z, &zErrMsg); if( zErrMsg!=0 ){ utf8_printf(stderr,"Error: %s\n", zErrMsg); if( bail_on_error ) return rc!=0 ? rc : 1; }else if( rc!=0 ){ utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); if( bail_on_error ) return rc; } } #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) }else if( strncmp(z, "-A", 2)==0 ){ if( nCmd>0 ){ utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" " with \"%s\"\n", z); return 1; } open_db(&data, 0); if( z[2] ){ argv[i] = &z[2]; arDotCommand(&data, argv+(i-1), argc-(i-1)); }else{ arDotCommand(&data, argv+i, argc-i); } readStdin = 0; break; #endif }else{ utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); raw_printf(stderr,"Use -help for a list of options.\n"); return 1; } data.cMode = data.mode; } if( !readStdin ){ /* Run all arguments that do not begin with '-' as if they were separate ** command-line inputs, except for the argToSkip argument which contains ** the database filename. */ for(i=0; i<nCmd; i++){ if( azCmd[i][0]=='.' ){ rc = do_meta_command(azCmd[i], &data); if( rc ) return rc==2 ? 0 : rc; }else{ open_db(&data, 0); rc = shell_exec(&data, azCmd[i], &zErrMsg); if( zErrMsg!=0 ){ utf8_printf(stderr,"Error: %s\n", zErrMsg); return rc!=0 ? rc : 1; }else if( rc!=0 ){ utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); return rc; } } } free(azCmd); }else{ /* Run commands received from standard input */ if( stdin_is_interactive ){ char *zHome; char *zHistory = 0; int nHistory; printf( "SQLite version %s %.19s\n" /*extra-version-info*/ "Enter \".help\" for usage hints.\n", sqlite3_libversion(), sqlite3_sourceid() ); if( warnInmemoryDb ){ printf("Connected to a "); printBold("transient in-memory database"); printf(".\nUse \".open FILENAME\" to reopen on a " "persistent database.\n"); } zHome = find_home_dir(0); if( zHome ){ nHistory = strlen30(zHome) + 20; if( (zHistory = malloc(nHistory))!=0 ){ sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); } } if( zHistory ){ shell_read_history(zHistory); } #if HAVE_READLINE || HAVE_EDITLINE rl_attempted_completion_function = readline_completion; #elif HAVE_LINENOISE linenoiseSetCompletionCallback(linenoise_completion); #endif rc = process_input(&data, 0); if( zHistory ){ shell_stifle_history(2000); shell_write_history(zHistory); free(zHistory); } }else{ rc = process_input(&data, stdin); } } set_table_name(&data, 0); if( data.db ){ session_close_all(&data); sqlite3_close(data.db); } sqlite3_free(data.zFreeOnClose); find_home_dir(1); output_reset(&data); data.doXdgOpen = 0; clearTempFile(&data); #if !SQLITE_SHELL_IS_UTF8 for(i=0; i<argc; i++) free(argv[i]); free(argv); #endif return rc; }
the_stack_data/98574301.c
/* Tests in detail the core arithmetic for pcmp{e,i}str{i,m} using pcmpistri to drive it. Does not check the e-vs-i or i-vs-m aspect. */ #include <string.h> #include <stdio.h> #include <assert.h> typedef unsigned int UInt; typedef signed int Int; typedef unsigned char UChar; typedef signed char Char; typedef unsigned long long int ULong; typedef UChar Bool; #define False ((Bool)0) #define True ((Bool)1) //typedef unsigned char V128[16]; typedef union { UChar uChar[16]; UInt uInt[4]; } V128; #define SHIFT_O 11 #define SHIFT_S 7 #define SHIFT_Z 6 #define SHIFT_A 4 #define SHIFT_C 0 #define SHIFT_P 2 #define MASK_O (1ULL << SHIFT_O) #define MASK_S (1ULL << SHIFT_S) #define MASK_Z (1ULL << SHIFT_Z) #define MASK_A (1ULL << SHIFT_A) #define MASK_C (1ULL << SHIFT_C) #define MASK_P (1ULL << SHIFT_P) UInt clz32 ( UInt x ) { Int y, m, n; y = -(x >> 16); m = (y >> 16) & 16; n = 16 - m; x = x >> m; y = x - 0x100; m = (y >> 16) & 8; n = n + m; x = x << m; y = x - 0x1000; m = (y >> 16) & 4; n = n + m; x = x << m; y = x - 0x4000; m = (y >> 16) & 2; n = n + m; x = x << m; y = x >> 14; m = y & ~(y >> 1); return n + 2 - m; } UInt ctz32 ( UInt x ) { return 32 - clz32((~x) & (x-1)); } void expand ( V128* dst, char* summary ) { Int i; assert( strlen(summary) == 16 ); for (i = 0; i < 16; i++) { UChar xx = 0; UChar x = summary[15-i]; if (x >= '0' && x <= '9') { xx = x - '0'; } else if (x >= 'A' && x <= 'F') { xx = x - 'A' + 10; } else if (x >= 'a' && x <= 'f') { xx = x - 'a' + 10; } else assert(0); assert(xx < 16); xx = (xx << 4) | xx; assert(xx < 256); dst->uChar[i] = xx; } } void try_istri ( char* which, UInt(*h_fn)(V128*,V128*), UInt(*s_fn)(V128*,V128*), char* summL, char* summR ) { assert(strlen(which) == 2); V128 argL, argR; expand(&argL, summL); expand(&argR, summR); UInt h_res = h_fn(&argL, &argR); UInt s_res = s_fn(&argL, &argR); printf("istri %s %s %s -> %08x %08x %s\n", which, summL, summR, h_res, s_res, h_res == s_res ? "" : "!!!!"); } UInt zmask_from_V128 ( V128* arg ) { UInt i, res = 0; for (i = 0; i < 16; i++) { res |= ((arg->uChar[i] == 0) ? 1 : 0) << i; } return res; } ////////////////////////////////////////////////////////// // // // GENERAL // // // ////////////////////////////////////////////////////////// /* Given partial results from a pcmpXstrX operation (intRes1, basically), generate an I format (index value for ECX) output, and also the new OSZACP flags. */ static void pcmpXstrX_WRK_gen_output_fmt_I(/*OUT*/V128* resV, /*OUT*/UInt* resOSZACP, UInt intRes1, UInt zmaskL, UInt zmaskR, UInt validL, UInt pol, UInt idx ) { assert((pol >> 2) == 0); assert((idx >> 1) == 0); UInt intRes2 = 0; switch (pol) { case 0: intRes2 = intRes1; break; // pol + case 1: intRes2 = ~intRes1; break; // pol - case 2: intRes2 = intRes1; break; // pol m+ case 3: intRes2 = intRes1 ^ validL; break; // pol m- } intRes2 &= 0xFFFF; // generate ecx value UInt newECX = 0; if (idx) { // index of ms-1-bit newECX = intRes2 == 0 ? 16 : (31 - clz32(intRes2)); } else { // index of ls-1-bit newECX = intRes2 == 0 ? 16 : ctz32(intRes2); } *(UInt*)(&resV[0]) = newECX; // generate new flags, common to all ISTRI and ISTRM cases *resOSZACP // A, P are zero = ((intRes2 == 0) ? 0 : MASK_C) // C == 0 iff intRes2 == 0 | ((zmaskL == 0) ? 0 : MASK_Z) // Z == 1 iff any in argL is 0 | ((zmaskR == 0) ? 0 : MASK_S) // S == 1 iff any in argR is 0 | ((intRes2 & 1) << SHIFT_O); // O == IntRes2[0] } /* Compute result and new OSZACP flags for all PCMP{E,I}STR{I,M} variants. For xSTRI variants, the new ECX value is placed in the 32 bits pointed to by *resV. For xSTRM variants, the result is a 128 bit value and is placed at *resV in the obvious way. For all variants, the new OSZACP value is placed at *resOSZACP. argLV and argRV are the vector args. The caller must prepare a 16-bit mask for each, zmaskL and zmaskR. For ISTRx variants this must be 1 for each zero byte of of the respective arg. For ESTRx variants this is derived from the explicit length indication, and must be 0 in all places except at the bit index corresponding to the valid length (0 .. 16). If the valid length is 16 then the mask must be all zeroes. In all cases, bits 31:16 must be zero. imm8 is the original immediate from the instruction. isSTRM indicates whether this is a xSTRM or xSTRI variant, which controls how much of *res is written. If the given imm8 case can be handled, the return value is True. If not, False is returned, and neither *res not *resOSZACP are altered. */ Bool pcmpXstrX_WRK ( /*OUT*/V128* resV, /*OUT*/UInt* resOSZACP, V128* argLV, V128* argRV, UInt zmaskL, UInt zmaskR, UInt imm8, Bool isSTRM ) { assert(imm8 < 0x80); assert((zmaskL >> 16) == 0); assert((zmaskR >> 16) == 0); /* Explicitly reject any imm8 values that haven't been validated, even if they would probably work. Life is too short to have unvalidated cases in the code base. */ switch (imm8) { case 0x00: case 0x02: case 0x08: case 0x0A: case 0x0C: case 0x0E: case 0x12: case 0x14: case 0x18: case 0x1A: case 0x30: case 0x34: case 0x38: case 0x3A: case 0x40: case 0x42: case 0x44: case 0x46: case 0x4A: break; default: return False; } UInt fmt = (imm8 >> 0) & 3; // imm8[1:0] data format UInt agg = (imm8 >> 2) & 3; // imm8[3:2] aggregation fn UInt pol = (imm8 >> 4) & 3; // imm8[5:4] polarity UInt idx = (imm8 >> 6) & 1; // imm8[6] 1==msb/bytemask /*----------------------------------------*/ /*-- strcmp on byte data --*/ /*----------------------------------------*/ if (agg == 2/*equal each, aka strcmp*/ && (fmt == 0/*ub*/ || fmt == 2/*sb*/) && !isSTRM) { Int i; UChar* argL = (UChar*)argLV; UChar* argR = (UChar*)argRV; UInt boolResII = 0; for (i = 15; i >= 0; i--) { UChar cL = argL[i]; UChar cR = argR[i]; boolResII = (boolResII << 1) | (cL == cR ? 1 : 0); } UInt validL = ~(zmaskL | -zmaskL); // not(left(zmaskL)) UInt validR = ~(zmaskR | -zmaskR); // not(left(zmaskR)) // do invalidation, common to all equal-each cases UInt intRes1 = (boolResII & validL & validR) // if both valid, use cmpres | (~ (validL | validR)); // if both invalid, force 1 // else force 0 intRes1 &= 0xFFFF; // generate I-format output pcmpXstrX_WRK_gen_output_fmt_I( resV, resOSZACP, intRes1, zmaskL, zmaskR, validL, pol, idx ); return True; } /*----------------------------------------*/ /*-- set membership on byte data --*/ /*----------------------------------------*/ if (agg == 0/*equal any, aka find chars in a set*/ && (fmt == 0/*ub*/ || fmt == 2/*sb*/) && !isSTRM) { /* argL: the string, argR: charset */ UInt si, ci; UChar* argL = (UChar*)argLV; UChar* argR = (UChar*)argRV; UInt boolRes = 0; UInt validL = ~(zmaskL | -zmaskL); // not(left(zmaskL)) UInt validR = ~(zmaskR | -zmaskR); // not(left(zmaskR)) for (si = 0; si < 16; si++) { if ((validL & (1 << si)) == 0) // run off the end of the string. break; UInt m = 0; for (ci = 0; ci < 16; ci++) { if ((validR & (1 << ci)) == 0) break; if (argR[ci] == argL[si]) { m = 1; break; } } boolRes |= (m << si); } // boolRes is "pre-invalidated" UInt intRes1 = boolRes & 0xFFFF; // generate I-format output pcmpXstrX_WRK_gen_output_fmt_I( resV, resOSZACP, intRes1, zmaskL, zmaskR, validL, pol, idx ); return True; } /*----------------------------------------*/ /*-- substring search on byte data --*/ /*----------------------------------------*/ if (agg == 3/*equal ordered, aka substring search*/ && (fmt == 0/*ub*/ || fmt == 2/*sb*/) && !isSTRM) { /* argL: haystack, argR: needle */ UInt ni, hi; UChar* argL = (UChar*)argLV; UChar* argR = (UChar*)argRV; UInt boolRes = 0; UInt validL = ~(zmaskL | -zmaskL); // not(left(zmaskL)) UInt validR = ~(zmaskR | -zmaskR); // not(left(zmaskR)) for (hi = 0; hi < 16; hi++) { UInt m = 1; for (ni = 0; ni < 16; ni++) { if ((validR & (1 << ni)) == 0) break; UInt i = ni + hi; if (i >= 16) break; if (argL[i] != argR[ni]) { m = 0; break; } } boolRes |= (m << hi); if ((validL & (1 << hi)) == 0) // run off the end of the haystack break; } // boolRes is "pre-invalidated" UInt intRes1 = boolRes & 0xFFFF; // generate I-format output pcmpXstrX_WRK_gen_output_fmt_I( resV, resOSZACP, intRes1, zmaskL, zmaskR, validL, pol, idx ); return True; } /*----------------------------------------*/ /*-- ranges, unsigned byte data --*/ /*----------------------------------------*/ if (agg == 1/*ranges*/ && fmt == 0/*ub*/ && !isSTRM) { /* argL: string, argR: range-pairs */ UInt ri, si; UChar* argL = (UChar*)argLV; UChar* argR = (UChar*)argRV; UInt boolRes = 0; UInt validL = ~(zmaskL | -zmaskL); // not(left(zmaskL)) UInt validR = ~(zmaskR | -zmaskR); // not(left(zmaskR)) for (si = 0; si < 16; si++) { if ((validL & (1 << si)) == 0) // run off the end of the string break; UInt m = 0; for (ri = 0; ri < 16; ri += 2) { if ((validR & (3 << ri)) != (3 << ri)) break; if (argR[ri] <= argL[si] && argL[si] <= argR[ri+1]) { m = 1; break; } } boolRes |= (m << si); } // boolRes is "pre-invalidated" UInt intRes1 = boolRes & 0xFFFF; // generate I-format output pcmpXstrX_WRK_gen_output_fmt_I( resV, resOSZACP, intRes1, zmaskL, zmaskR, validL, pol, idx ); return True; } /*----------------------------------------*/ /*-- ranges, signed byte data --*/ /*----------------------------------------*/ if (agg == 1/*ranges*/ && fmt == 2/*sb*/ && !isSTRM) { /* argL: string, argR: range-pairs */ UInt ri, si; Char* argL = (Char*)argLV; Char* argR = (Char*)argRV; UInt boolRes = 0; UInt validL = ~(zmaskL | -zmaskL); // not(left(zmaskL)) UInt validR = ~(zmaskR | -zmaskR); // not(left(zmaskR)) for (si = 0; si < 16; si++) { if ((validL & (1 << si)) == 0) // run off the end of the string break; UInt m = 0; for (ri = 0; ri < 16; ri += 2) { if ((validR & (3 << ri)) != (3 << ri)) break; if (argR[ri] <= argL[si] && argL[si] <= argR[ri+1]) { m = 1; break; } } boolRes |= (m << si); } // boolRes is "pre-invalidated" UInt intRes1 = boolRes & 0xFFFF; // generate I-format output pcmpXstrX_WRK_gen_output_fmt_I( resV, resOSZACP, intRes1, zmaskL, zmaskR, validL, pol, idx ); return True; } return False; } ////////////////////////////////////////////////////////// // // // ISTRI_4A // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_4A ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x4A, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_4A ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x4A, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_4A ( void ) { char* wot = "4A"; UInt(*h)(V128*,V128*) = h_pcmpistri_4A; UInt(*s)(V128*,V128*) = s_pcmpistri_4A; try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaa2aaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaa2aaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaa2aa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaa2aaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaa2aaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaa2a"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "baaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9aaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaa7aaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaa2aaa4aaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "8000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000001", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "0000000000000000"); } ////////////////////////////////////////////////////////// // // // ISTRI_3A // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_3A ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x3A, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_3A ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x3A, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_3A ( void ) { char* wot = "3A"; UInt(*h)(V128*,V128*) = h_pcmpistri_3A; UInt(*s)(V128*,V128*) = s_pcmpistri_3A; try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaa2aaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaa2aaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaa2aa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaa2aaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaa2aaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaa2a"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "baaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9aaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaa7aaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaa2aaa4aaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "8000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000001", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "0000000000000000"); } ////////////////////////////////////////////////////////// // // // ISTRI_0C // // // ////////////////////////////////////////////////////////// __attribute__((noinline)) UInt h_pcmpistri_0C ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res = 0, flags = 0; __asm__ __volatile__( "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x0C, %%xmm2, %%xmm11" "\n\t" //"pcmpistrm $0x0C, %%xmm2, %%xmm11" "\n\t" //"movd %%xmm0, %%ecx" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_0C ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x0C, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_0C ( void ) { char* wot = "0C"; UInt(*h)(V128*,V128*) = h_pcmpistri_0C; UInt(*s)(V128*,V128*) = s_pcmpistri_0C; try_istri(wot,h,s, "111111111abcde11", "00000000000abcde"); try_istri(wot,h,s, "111111111abcde11", "0000abcde00abcde"); try_istri(wot,h,s, "1111111111abcde1", "00000000000abcde"); try_istri(wot,h,s, "11111111111abcde", "00000000000abcde"); try_istri(wot,h,s, "111111111111abcd", "00000000000abcde"); try_istri(wot,h,s, "111abcde1abcde11", "00000000000abcde"); try_istri(wot,h,s, "11abcde11abcde11", "00000000000abcde"); try_istri(wot,h,s, "1abcde111abcde11", "00000000000abcde"); try_istri(wot,h,s, "abcde1111abcde11", "00000000000abcde"); try_istri(wot,h,s, "bcde11111abcde11", "00000000000abcde"); try_istri(wot,h,s, "cde111111abcde11", "00000000000abcde"); try_istri(wot,h,s, "01abcde11abcde11", "00000000000abcde"); try_istri(wot,h,s, "00abcde11abcde11", "00000000000abcde"); try_istri(wot,h,s, "000bcde11abcde11", "00000000000abcde"); try_istri(wot,h,s, "00abcde10abcde11", "00000000000abcde"); try_istri(wot,h,s, "00abcde100bcde11", "00000000000abcde"); try_istri(wot,h,s, "1111111111111234", "0000000000000000"); try_istri(wot,h,s, "1111111111111234", "0000000000000001"); try_istri(wot,h,s, "1111111111111234", "0000000000000011"); try_istri(wot,h,s, "1111111111111234", "1111111111111234"); try_istri(wot,h,s, "a111111111111111", "000000000000000a"); try_istri(wot,h,s, "b111111111111111", "000000000000000a"); try_istri(wot,h,s, "b111111111111111", "0000000000000000"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "123456789abcdef1", "0000000000000000"); try_istri(wot,h,s, "0000000000000000", "123456789abcdef1"); } ////////////////////////////////////////////////////////// // // // ISTRI_08 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_08 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x08, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_08 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x08, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_08 ( void ) { char* wot = "08"; UInt(*h)(V128*,V128*) = h_pcmpistri_08; UInt(*s)(V128*,V128*) = s_pcmpistri_08; try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaa2aaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaa2aaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaa2aa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaa2aaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaa2aaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaa2a"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "baaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9aaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaa7aaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaa2aaa4aaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "8000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000001", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "0000000000000000"); } ////////////////////////////////////////////////////////// // // // ISTRI_18 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_18 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x18, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_18 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x18, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_18 ( void ) { char* wot = "18"; UInt(*h)(V128*,V128*) = h_pcmpistri_18; UInt(*s)(V128*,V128*) = s_pcmpistri_18; try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaa2aaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaa2aaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaa2aa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaa2aaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaa2aaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaa2a"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "baaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9aaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaa7aaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaa2aaa4aaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "8000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000001", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "0000000000000000"); } ////////////////////////////////////////////////////////// // // // ISTRI_1A // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_1A ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x1A, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_1A ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x1A, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_1A ( void ) { char* wot = "1A"; UInt(*h)(V128*,V128*) = h_pcmpistri_1A; UInt(*s)(V128*,V128*) = s_pcmpistri_1A; try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaa2aaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaa2aaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaa2aa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaa2aaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaa2aaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaa2a"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "baaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9aaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaa7aaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaa2aaa4aaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "8000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000001", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "0000000000000000"); } ////////////////////////////////////////////////////////// // // // ISTRI_02 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_02 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x02, %%xmm2, %%xmm11" "\n\t" //"pcmpistrm $0x02, %%xmm2, %%xmm11" "\n\t" //"movd %%xmm0, %%ecx" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_02 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x02, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_02 ( void ) { char* wot = "02"; UInt(*h)(V128*,V128*) = h_pcmpistri_02; UInt(*s)(V128*,V128*) = s_pcmpistri_02; try_istri(wot,h,s, "abcdacbdabcdabcd", "000000000000000a"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000000b"); try_istri(wot,h,s, "abcdabcdabcdabcd", "00000000000000ab"); try_istri(wot,h,s, "abcdabc0abcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0bcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcda0cd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdab0d", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabc0", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000a0cd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000ab0d"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abc0"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000dcba"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000bbbb"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000baba"); try_istri(wot,h,s, "0000abcdabcdabcd", "00000000000baba0"); try_istri(wot,h,s, "0ddc0ffeebadf00d", "00000000cafebabe"); try_istri(wot,h,s, "0ddc0ffeebadfeed", "00000000cafebabe"); } ////////////////////////////////////////////////////////// // // // ISTRI_12 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_12 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x12, %%xmm2, %%xmm11" "\n\t" //"pcmpistrm $0x12, %%xmm2, %%xmm11" "\n\t" //"movd %%xmm0, %%ecx" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_12 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x12, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_12 ( void ) { char* wot = "12"; UInt(*h)(V128*,V128*) = h_pcmpistri_12; UInt(*s)(V128*,V128*) = s_pcmpistri_12; try_istri(wot,h,s, "abcdacbdabcdabcd", "000000000000000a"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000000b"); try_istri(wot,h,s, "abcdabcdabcdabcd", "00000000000000ab"); try_istri(wot,h,s, "abcdabc0abcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0bcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcda0cd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdab0d", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabc0", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000a0cd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000ab0d"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abc0"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000dcba"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000bbbb"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000baba"); try_istri(wot,h,s, "0000abcdabcdabcd", "00000000000baba0"); try_istri(wot,h,s, "0ddc0ffeebadf00d", "00000000cafebabe"); try_istri(wot,h,s, "0ddc0ffeebadfeed", "00000000cafebabe"); } ////////////////////////////////////////////////////////// // // // ISTRI_44 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_44 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x44, %%xmm2, %%xmm11" "\n\t" //"pcmpistrm $0x04, %%xmm2, %%xmm11" "\n\t" //"movd %%xmm0, %%ecx" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_44 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x44, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_44 ( void ) { char* wot = "44"; UInt(*h)(V128*,V128*) = h_pcmpistri_44; UInt(*s)(V128*,V128*) = s_pcmpistri_44; try_istri(wot,h,s, "aaaabbbbccccdddd", "00000000000000bc"); try_istri(wot,h,s, "aaaabbbbccccdddd", "00000000000000cb"); try_istri(wot,h,s, "baaabbbbccccdddd", "00000000000000cb"); try_istri(wot,h,s, "baaabbbbccccdddc", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbb0bbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbb0b", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbb0", "00000000000000cb"); try_istri(wot,h,s, "0000000000000000", "00000000000000cb"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "000000000000000b"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000062cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000002cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000000cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "000000000000000b"); try_istri(wot,h,s, "0123456789abcdef", "000000fecb975421"); try_istri(wot,h,s, "123456789abcdef1", "000000fecb975421"); try_istri(wot,h,s, "0123456789abcdef", "00000000dca86532"); try_istri(wot,h,s, "123456789abcdef1", "00000000dca86532"); try_istri(wot,h,s, "163887ec041a9b72", "fcd75adb9b3e895a"); try_istri(wot,h,s, "fc937cbfbf53f8e2", "0d136bcb024d3fb7"); try_istri(wot,h,s, "2ca34182c29a82ab", "302ebd646775ab54"); try_istri(wot,h,s, "3f2987608c11be6f", "a9ecb661f8e0a8cb"); } ////////////////////////////////////////////////////////// // // // ISTRI_00 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_00 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x00, %%xmm2, %%xmm11" "\n\t" //"pcmpistrm $0x00, %%xmm2, %%xmm11" "\n\t" //"movd %%xmm0, %%ecx" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_00 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x00, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_00 ( void ) { char* wot = "00"; UInt(*h)(V128*,V128*) = h_pcmpistri_00; UInt(*s)(V128*,V128*) = s_pcmpistri_00; try_istri(wot,h,s, "abcdacbdabcdabcd", "000000000000000a"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000000b"); try_istri(wot,h,s, "abcdabcdabcdabcd", "00000000000000ab"); try_istri(wot,h,s, "abcdabc0abcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0bcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcda0cd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdab0d", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabc0", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000a0cd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000ab0d"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abc0"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000dcba"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000bbbb"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000baba"); try_istri(wot,h,s, "0000abcdabcdabcd", "00000000000baba0"); try_istri(wot,h,s, "0ddc0ffeebadf00d", "00000000cafebabe"); try_istri(wot,h,s, "0ddc0ffeebadfeed", "00000000cafebabe"); } ////////////////////////////////////////////////////////// // // // ISTRI_38 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_38 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x38, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_38 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x38, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_38 ( void ) { char* wot = "38"; UInt(*h)(V128*,V128*) = h_pcmpistri_38; UInt(*s)(V128*,V128*) = s_pcmpistri_38; try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaa2aaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaa2aaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaa2aa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaa2aaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaa2aaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaa2a"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "baaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9aaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaaaaaa7aaa"); try_istri(wot,h,s, "b9baaaaaaaaaaaaa", "aaaaaaaa2aaa4aaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaa0aaaaaaa", "aaaaaaaaaaaa0aaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaa0aaa", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "8000000000000000", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000001", "aaaaaaaa0aaaaaaa"); try_istri(wot,h,s, "0000000000000000", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "0000000000000000"); } ////////////////////////////////////////////////////////// // // // ISTRI_46 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_46 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x46, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_46 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x46, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_46 ( void ) { char* wot = "46"; UInt(*h)(V128*,V128*) = h_pcmpistri_46; UInt(*s)(V128*,V128*) = s_pcmpistri_46; try_istri(wot,h,s, "aaaabbbbccccdddd", "00000000000000bc"); try_istri(wot,h,s, "aaaabbbbccccdddd", "00000000000000cb"); try_istri(wot,h,s, "baaabbbbccccdddd", "00000000000000cb"); try_istri(wot,h,s, "baaabbbbccccdddc", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbb0bbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbb0b", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbb0", "00000000000000cb"); try_istri(wot,h,s, "0000000000000000", "00000000000000cb"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "000000000000000b"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000062cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000002cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000000cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "000000000000000b"); try_istri(wot,h,s, "0123456789abcdef", "000000fecb975421"); try_istri(wot,h,s, "123456789abcdef1", "000000fecb975421"); try_istri(wot,h,s, "0123456789abcdef", "00000000dca86532"); try_istri(wot,h,s, "123456789abcdef1", "00000000dca86532"); try_istri(wot,h,s, "163887ec041a9b72", "fcd75adb9b3e895a"); try_istri(wot,h,s, "fc937cbfbf53f8e2", "0d136bcb024d3fb7"); try_istri(wot,h,s, "2ca34182c29a82ab", "302ebd646775ab54"); try_istri(wot,h,s, "3f2987608c11be6f", "a9ecb661f8e0a8cb"); } ////////////////////////////////////////////////////////// // // // ISTRI_30 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_30 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x30, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_30 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x30, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_30 ( void ) { char* wot = "30"; UInt(*h)(V128*,V128*) = h_pcmpistri_30; UInt(*s)(V128*,V128*) = s_pcmpistri_30; try_istri(wot,h,s, "abcdacbdabcdabcd", "000000000000000a"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000000b"); try_istri(wot,h,s, "abcdabcdabcdabcd", "00000000000000ab"); try_istri(wot,h,s, "abcdabc0abcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0bcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcda0cd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdab0d", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabc0", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000a0cd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000ab0d"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abc0"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000dcba"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000bbbb"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000baba"); try_istri(wot,h,s, "0000abcdabcdabcd", "00000000000baba0"); try_istri(wot,h,s, "0ddc0ffeebadf00d", "00000000cafebabe"); try_istri(wot,h,s, "0ddc0ffeebadfeed", "00000000cafebabe"); } ////////////////////////////////////////////////////////// // // // ISTRI_40 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_40 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x40, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_40 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x40, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_40 ( void ) { char* wot = "40"; UInt(*h)(V128*,V128*) = h_pcmpistri_40; UInt(*s)(V128*,V128*) = s_pcmpistri_40; try_istri(wot,h,s, "abcdacbdabcdabcd", "000000000000000a"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000000b"); try_istri(wot,h,s, "abcdabcdabcdabcd", "00000000000000ab"); try_istri(wot,h,s, "abcdabc0abcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0bcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcda0cd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdab0d", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabc0", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000a0cd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000ab0d"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abc0"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000dcba"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000bbbb"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000baba"); try_istri(wot,h,s, "0000abcdabcdabcd", "00000000000baba0"); try_istri(wot,h,s, "0ddc0ffeebadf00d", "00000000cafebabe"); try_istri(wot,h,s, "0ddc0ffeebadfeed", "00000000cafebabe"); } ////////////////////////////////////////////////////////// // // // ISTRI_42 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_42 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x42, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_42 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x42, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_42 ( void ) { char* wot = "42"; UInt(*h)(V128*,V128*) = h_pcmpistri_42; UInt(*s)(V128*,V128*) = s_pcmpistri_42; try_istri(wot,h,s, "abcdacbdabcdabcd", "000000000000000a"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000000b"); try_istri(wot,h,s, "abcdabcdabcdabcd", "00000000000000ab"); try_istri(wot,h,s, "abcdabc0abcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0bcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcda0cd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdab0d", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabc0", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000a0cd"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000ab0d"); try_istri(wot,h,s, "abcdabcdabcdabcd", "000000000000abc0"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000abcd"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000dcba"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000bbbb"); try_istri(wot,h,s, "0000abcdabcdabcd", "000000000000baba"); try_istri(wot,h,s, "0000abcdabcdabcd", "00000000000baba0"); try_istri(wot,h,s, "0ddc0ffeebadf00d", "00000000cafebabe"); try_istri(wot,h,s, "0ddc0ffeebadfeed", "00000000cafebabe"); } ////////////////////////////////////////////////////////// // // // ISTRI_0E // // // ////////////////////////////////////////////////////////// __attribute__((noinline)) UInt h_pcmpistri_0E ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res = 0, flags = 0; __asm__ __volatile__( "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x0E, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_0E ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x0E, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_0E ( void ) { char* wot = "0E"; UInt(*h)(V128*,V128*) = h_pcmpistri_0E; UInt(*s)(V128*,V128*) = s_pcmpistri_0E; try_istri(wot,h,s, "111111111abcde11", "00000000000abcde"); try_istri(wot,h,s, "111111111abcde11", "0000abcde00abcde"); try_istri(wot,h,s, "1111111111abcde1", "00000000000abcde"); try_istri(wot,h,s, "11111111111abcde", "00000000000abcde"); try_istri(wot,h,s, "111111111111abcd", "00000000000abcde"); try_istri(wot,h,s, "111abcde1abcde11", "00000000000abcde"); try_istri(wot,h,s, "11abcde11abcde11", "00000000000abcde"); try_istri(wot,h,s, "1abcde111abcde11", "00000000000abcde"); try_istri(wot,h,s, "abcde1111abcde11", "00000000000abcde"); try_istri(wot,h,s, "bcde11111abcde11", "00000000000abcde"); try_istri(wot,h,s, "cde111111abcde11", "00000000000abcde"); try_istri(wot,h,s, "01abcde11abcde11", "00000000000abcde"); try_istri(wot,h,s, "00abcde11abcde11", "00000000000abcde"); try_istri(wot,h,s, "000bcde11abcde11", "00000000000abcde"); try_istri(wot,h,s, "00abcde10abcde11", "00000000000abcde"); try_istri(wot,h,s, "00abcde100bcde11", "00000000000abcde"); try_istri(wot,h,s, "1111111111111234", "0000000000000000"); try_istri(wot,h,s, "1111111111111234", "0000000000000001"); try_istri(wot,h,s, "1111111111111234", "0000000000000011"); try_istri(wot,h,s, "1111111111111234", "1111111111111234"); try_istri(wot,h,s, "a111111111111111", "000000000000000a"); try_istri(wot,h,s, "b111111111111111", "000000000000000a"); try_istri(wot,h,s, "b111111111111111", "0000000000000000"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "123456789abcdef1", "0000000000000000"); try_istri(wot,h,s, "0000000000000000", "123456789abcdef1"); } ////////////////////////////////////////////////////////// // // // ISTRI_34 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_34 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x34, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_34 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x34, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_34 ( void ) { char* wot = "34"; UInt(*h)(V128*,V128*) = h_pcmpistri_34; UInt(*s)(V128*,V128*) = s_pcmpistri_34; try_istri(wot,h,s, "aaaabbbbccccdddd", "00000000000000bc"); try_istri(wot,h,s, "aaaabbbbccccdddd", "00000000000000cb"); try_istri(wot,h,s, "baaabbbbccccdddd", "00000000000000cb"); try_istri(wot,h,s, "baaabbbbccccdddc", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbb0bbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbb0b", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbb0", "00000000000000cb"); try_istri(wot,h,s, "0000000000000000", "00000000000000cb"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "000000000000000b"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000062cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000002cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000000cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "000000000000000b"); try_istri(wot,h,s, "0123456789abcdef", "000000fecb975421"); try_istri(wot,h,s, "123456789abcdef1", "000000fecb975421"); try_istri(wot,h,s, "0123456789abcdef", "00000000dca86532"); try_istri(wot,h,s, "123456789abcdef1", "00000000dca86532"); try_istri(wot,h,s, "163887ec041a9b72", "fcd75adb9b3e895a"); try_istri(wot,h,s, "fc937cbfbf53f8e2", "0d136bcb024d3fb7"); try_istri(wot,h,s, "2ca34182c29a82ab", "302ebd646775ab54"); try_istri(wot,h,s, "3f2987608c11be6f", "a9ecb661f8e0a8cb"); } ////////////////////////////////////////////////////////// // // // ISTRI_14 // // // ////////////////////////////////////////////////////////// UInt h_pcmpistri_14 ( V128* argL, V128* argR ) { V128 block[2]; memcpy(&block[0], argL, sizeof(V128)); memcpy(&block[1], argR, sizeof(V128)); ULong res, flags; __asm__ __volatile__( "subq $1024, %%rsp" "\n\t" "movdqu 0(%2), %%xmm2" "\n\t" "movdqu 16(%2), %%xmm11" "\n\t" "pcmpistri $0x14, %%xmm2, %%xmm11" "\n\t" "pushfq" "\n\t" "popq %%rdx" "\n\t" "movq %%rcx, %0" "\n\t" "movq %%rdx, %1" "\n\t" "addq $1024, %%rsp" "\n\t" : /*out*/ "=r"(res), "=r"(flags) : "r"/*in*/(&block[0]) : "rcx","rdx","xmm0","xmm2","xmm11","cc","memory" ); return ((flags & 0x8D5) << 16) | (res & 0xFFFF); } UInt s_pcmpistri_14 ( V128* argLU, V128* argRU ) { V128 resV; UInt resOSZACP, resECX; Bool ok = pcmpXstrX_WRK( &resV, &resOSZACP, argLU, argRU, zmask_from_V128(argLU), zmask_from_V128(argRU), 0x14, False/*!isSTRM*/ ); assert(ok); resECX = resV.uInt[0]; return (resOSZACP << 16) | resECX; } void istri_14 ( void ) { char* wot = "14"; UInt(*h)(V128*,V128*) = h_pcmpistri_14; UInt(*s)(V128*,V128*) = s_pcmpistri_14; try_istri(wot,h,s, "aaaabbbbccccdddd", "00000000000000bc"); try_istri(wot,h,s, "aaaabbbbccccdddd", "00000000000000cb"); try_istri(wot,h,s, "baaabbbbccccdddd", "00000000000000cb"); try_istri(wot,h,s, "baaabbbbccccdddc", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbb0bbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbb0b", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbb0", "00000000000000cb"); try_istri(wot,h,s, "0000000000000000", "00000000000000cb"); try_istri(wot,h,s, "0000000000000000", "0000000000000000"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "00000000000000cb"); try_istri(wot,h,s, "bbbbbbbbbbbbbbbb", "000000000000000b"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000062cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000002cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "00000000000000cb"); try_istri(wot,h,s, "b4b4b4b4b4b4b4b4", "000000000000000b"); try_istri(wot,h,s, "0123456789abcdef", "000000fecb975421"); try_istri(wot,h,s, "123456789abcdef1", "000000fecb975421"); try_istri(wot,h,s, "0123456789abcdef", "00000000dca86532"); try_istri(wot,h,s, "123456789abcdef1", "00000000dca86532"); try_istri(wot,h,s, "163887ec041a9b72", "fcd75adb9b3e895a"); try_istri(wot,h,s, "fc937cbfbf53f8e2", "0d136bcb024d3fb7"); try_istri(wot,h,s, "2ca34182c29a82ab", "302ebd646775ab54"); try_istri(wot,h,s, "3f2987608c11be6f", "a9ecb661f8e0a8cb"); } ////////////////////////////////////////////////////////// // // // main // // // ////////////////////////////////////////////////////////// int main ( void ) { istri_4A(); istri_3A(); istri_08(); istri_18(); istri_1A(); istri_02(); istri_0C(); istri_12(); istri_44(); istri_00(); istri_38(); istri_46(); istri_30(); istri_40(); istri_42(); istri_0E(); istri_14(); istri_34(); return 0; }
the_stack_data/28262336.c
/** * Use After Free * https://cwe.mitre.org/data/definitions/416.html */ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char * buffer = (char *) malloc(256); bool error = true; if (error) free(buffer); // [...] if (error) printf("%lu\n", strlen(buffer)); //<- Use after free }
the_stack_data/499564.c
#include <stdio.h> int math_pow(int, int); int main() { int n; scanf("%d", &n); printf("%d\n", math_pow(n, 2)); printf("%d\n", math_pow(n, 3)); return 0; } int math_pow(int number, int power) { int result = number; for(int i = 0; i < power - 1; i++) { result *= number; } return result; }
the_stack_data/18404.c
/* Code for demonstrating Fixed point Method */ #include <stdio.h> #include <time.h> #include <math.h> int main() { float x=0.5, Es = 0.0005, Ea = 10000, e[100]; /* Defining x and errors */ int counter = 0, i; /* Defining Counter for iteration count */ clock_t begin = clock(); /*Clock staring from this line*/ printf("Program to solve Non-linear Equation using Fixed Point Method :\n"); printf("---------------------------------------------------------------\n"); printf("Initial Estimate : %f\n",x); FILE *fptr = fopen("FixedPoint_Error.csv", "w"); /* Opening file for storing errors of Fixed Point Method */ while (fabs(Ea) > Es) { Ea = x; x = pow( 20 + 2*x, 0.4 ) / 4.84936; Ea = x - Ea; e[counter] = fabs(Ea); counter += 1; } fprintf(fptr, "Ea\n"); /* Loop for storing values in file for further plotting */ for (i = 0; i < counter; i++) { fprintf(fptr, "%f\n", e[i]); } fclose(fptr);/* Closing file after storing values */ printf("Solution : %0.5f\n",x); printf("No. of Iteration : %d\n", counter); clock_t end = clock(); /* Clock Ends here */ double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; /* Calculating time taken for code to execute */ printf("Time taken for code execution : %0.6f milli seconds.\n", 1000 * time_spent); /* Printing the time taken */ return 0; }
the_stack_data/98575089.c
/* Author : Arnob Mahmud mail : [email protected] */ #include <stdio.h> #include <math.h> int main(int argc, char const *argv[]) { int i, n, rem, temp, count, sum, arc = 0; scanf("%d", &n); for (i = 1; i <= n; i++) { temp = i; count = 0; while (temp != 0) { temp /= 10; count++; } temp = i; sum = 0; while (temp != 0) { rem = temp % 10; sum += pow(rem, count); temp /= 10; } if (sum == i) { printf("%d ", i); arc++; } } printf("\nTotal armstrong number : %d", arc); return 0; }
the_stack_data/206392946.c
/* Copyright (C) 2002-2019 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 2002. 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 <signal.h> /* These are defined in libc. We want to have only one definition so we "forward" the calls. */ extern int __libc_current_sigrtmin_private(void); extern int __libc_current_sigrtmax_private(void); extern int __libc_allocate_rtsig_private(int high); /* We reserve __SIGRTMIN for use as the cancellation signal and __SIGRTMIN+1 to handle setuid et.al. These signals are used internally. */ int __libc_current_sigrtmin(void) { return __libc_current_sigrtmin_private(); } int __libc_current_sigrtmax(void) { return __libc_current_sigrtmax_private(); } int __libc_allocate_rtsig(int high) { return __libc_allocate_rtsig_private(high); }
the_stack_data/30354.c
/* Copyright (c) 2014-2016, Alexey Frunze 2-clause BSD license. */ #ifdef _WINDOWS asm( "section .kernel32_hints_trailer\n" "dd 0" // make sure the section isn't empty ); asm( "section .kernel32_iat_trailer\n" "dd 0" // make sure the section isn't empty ); asm( "section .dll_imports\n" "extern __start__kernel32_hints\n" "extern __start__kernel32_iat\n" "dd __start__kernel32_hints, 0, 0, __kernel32_dll__, __start__kernel32_iat" ); char _kernel32_dll__[] = "kernel32.dll"; // win32 functions will pull this file by this symbol extern char _dll_imports; static char* pimports = &_dll_imports; // pull the header & trailer for the dll imports table (section .dll_imports) #endif // _WINDOWS
the_stack_data/17412.c
#include <stdio.h> #include <stdlib.h> int main() { int i, n = 5; int* v = NULL; printf("&i = %p, i = %d\n", &i, i); printf("&n = %p, n = %d\n", &n, n); printf("&v = %p, v = %p\n\n", &v, v); v = (int*) malloc(n * sizeof(int)); printf("&v = %p, v = %p\n\n", &v, v); for (i = 0; i < n; i++) { // puts("ANTES"); // printf("&v[%d] = %p, v[%d] = %d\n", // i, &v[i], i, v[i]); // printf("*(v + %d) = *(%p + %d) = *(%p) = %d\n", // i, v, i, (v + i), *(v + i)); v[i] = i; // puts("DEPOIS"); printf("&v[%d] = %p, v[%d] = %d\n", i, &v[i], i, v[i]); printf("*(v + %d) = *(%p + %d) = *(%p) = %d\n", i, v, i, (v + i), *(v + i)); puts(""); } free(v); v = NULL; return 0; }
the_stack_data/247019263.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { /* This buffer is used for IO interactions with a user. */ char ioBuffer[128]; /* This would be a dynamically allocated buffer for internal storage of user's input. */ char* stringBuffer; /* Prompt for user input. */ printf("Enter your name: "); /* This is the core of the problem */ gets(ioBuffer); /* Copy user's input into dynamically allocated buffer. */ stringBuffer = (char*)malloc(strlen(ioBuffer) + 1); strcpy(stringBuffer, ioBuffer); /* Show user's input and free local buffer. */ printf("\n\nYour name is: %s\n", stringBuffer); free(stringBuffer); return 0; }
the_stack_data/176869.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: anajmi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/06 17:03:00 by anajmi #+# #+# */ /* Updated: 2021/07/10 13:25:16 by anajmi ### ########.fr */ /* */ /* ************************************************************************** */ int ft_atoi(char *str) { int a; int sign; int nbr; a = 0; nbr = 0; while (str[a] == ' ' || (9 <= str[a] && str[a] <= 13)) a++; sign = 1; while (str[a] == '-' || str[a] == '+') { if (str[a] == '-') sign *= (-1); a++; } while ('0' <= str[a] && str[a] <= '9') { nbr *= 10; nbr += str[a] - '0'; a++; } return (nbr * sign); }
the_stack_data/32951316.c
#include <stdio.h> #ifdef __MSDOS__ void exit(int); #endif #define fetch() (byte = getc( fp )) #define fetcw() (byte = getc(fp),byte +=0x100*getc(fp)) #define fetcd() {l=getc(fp);\ byte_= getc(fp);l+=0x100L*byte_;\ byte_= getc(fp);l+=0x10000L*byte_;\ byte_= getc(fp);l+=0x1000000L*byte_;} main( argc , argv ) int argc; char **argv; { FILE *fp; int byte,i,limit,byte_; long l; if( argc == 1 ) { fprintf(stderr,"odx object debugger.\n"); fprintf(stderr,"Usage odx filaname\n"); exit(1); } #ifdef __MSDOS__ fp = fopen( argv[1] , "rb" ); #else fp = fopen( argv[1] , "r" ); #endif if( !fp ){ fprintf(stderr,"Unable to open the file.\n"); exit(1); } byte = getc(fp); if( byte != 0x55 ){ fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"First magic number missing.\n"); exit(1); } byte = getc( fp ); if( byte != 0xaa ){ fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Second magic number missing.\n"); exit(1); } byte = getc( fp ); while( byte != EOF ){ switch( byte ){ case 0x81:/* CODE */ fetcw(); limit = byte; printf("CODE\n"); fetcd(); printf("ADDRESS=%08lx\n",l); fetch(); printf("Bytes No:%d",byte); if( limit != byte +5 ){ fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Number of the bytes, and the length of the block are inconsistent.\n"); fprintf(stderr,"Block length=%d , Number of bytes = %d\n", limit, byte); fprintf(stderr,"The difference is not 5.\n"); exit(1); } limit = byte; for( i = 0 ; i < limit ; i++ ){ fetch(); if( !(i%8) )printf("\n"); printf("%02X ",byte); if( byte>' ' && byte<128 ) printf("%c,",byte); else printf(" ,"); } printf("\n"); fetch();/*CHKSUM*/ break; case 0x82:/*RELOC */ fetcw(); limit = byte; printf("RELOC\n"); fetch(); printf("No:%d\n",byte); if( limit != byte*5+1 ){ fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Number of the bytes, and the length of the block are inconsistent.\n"); fprintf(stderr,"Block length=%d , Number of bytes = %d\n", limit, byte); fprintf(stderr," %d != %d*5+1\n",limit,byte); exit(1); } limit = byte; for( i = 0 ; i<limit ; i++ ){ fetch(); if( byte == 0 ) printf("WORD "); else if( byte == 0xf0 ) printf("DWORD "); else{ fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Unknown relocation type:%02X\n",byte); exit(1); } fetcd(); printf("%08lX\n",l); } fetch();/*CHKSUM*/ break; case 0x83:/* PUB */ fetcw(); limit = byte; printf("PUB\n"); fetch(); limit--; if( byte == 0 ) printf("N "); else if( byte == 0xf0 ) printf("R "); else{ fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Public relocation information is wrong.\n"); fprintf(stderr,"%02X\n",byte); exit(1); } fetch(); limit --; while( byte ){ printf("%c",byte); fetch(); limit--; } if( limit != 4 ){ fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Number of the bytes, and the length of the block are inconsistent.\n"); fprintf(stderr,"Block length=%d != 4\n", limit); exit(1); } fetcd(); printf(" %08X\n",l); fetch();/*CHKSUM*/ break; case 0x84:/*EXTDEF*/ fetcw(); limit = byte; printf("EXTDEF\n"); fetch(); limit --; while( byte ){ printf("%c",byte); fetch(); limit --; } if( limit != 2 ){ fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Number of the bytes, and the length of the block are inconsistent.\n"); fprintf(stderr,"Block length=%d != 2\n", limit); exit(1); } fetcw(); printf(" No:%d\n",byte); fetch();/*CHKSUM*/ break; case 0x85:/*EXTREF*/ fetcw(); limit = byte; printf("EXTREF\n"); fetch(); if( limit != 1+byte*7 ){ fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Number of the bytes, and the length of the block are inconsistent.\n"); fprintf(stderr,"Block length=%d, Number of items=%d\n", limit,byte); fprintf(stderr,"%d != 1+%d*7\n",limit,byte); exit(1); } limit = byte; for( i = 0 ; i <limit ; i++ ){ fetcw(); printf("No:%d\n",byte); fetch(); switch( byte ){ case 1: printf("BYTE "); break; case 2: printf("WORD "); break; case 4: printf("DWORD "); break; case 0xfe: printf("RBYTE "); break; case 0xfd: printf("RWORD "); break; case 0xfb: printf("RDWORD "); break; default: fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Unknown external type: %02X\n", byte); exit(1); } fetcd(); printf("%08X\n",l); } fetch();/*CHKSUM*/ break; default: fprintf(stderr,"Bad object format!\n"); fprintf(stderr,"Unknown block type: %02X\n",byte); exit(1); } fetch(); } }
the_stack_data/58916.c
/* Copyright 2008-2017 Carsten Elton Sorensen This file is part of ASMotor. ASMotor 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. ASMotor 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 ASMotor. If not, see <http://www.gnu.org/licenses/>. */ #ifdef __VBCC__ #include <devices/timer.h> #include <proto/timer.h> #include <proto/exec.h> #include <stdlib.h> #include "amitime.h" static struct timerequest time_Request; struct Library* TimerBase = NULL; void time_Shutdown(void) { CloseDevice((struct IORequest*)&time_Request); } void time_Init(void) { if(TimerBase == NULL) { if(OpenDevice(TIMERNAME, UNIT_MICROHZ, (struct IORequest*)&time_Request, 0) == 0) { TimerBase = (struct Library*)time_Request.tr_node.io_Device; atexit(time_Shutdown); } } } uint32_t time_GetMicroSeconds(void) { struct timeval tv; time_Init(); GetSysTime(&tv); return tv.tv_secs * 1000000 + tv.tv_micro; } #endif
the_stack_data/95450565.c
/* basename.c */ #include <libgen.h> #include <string.h> char *basename(path) char *path; { size_t len; char *cp; if (path == NULL) return "."; len= strlen(path); if (len == 0) return "."; while (path[len-1] == '/') { if (len == 1) return path; /* just "/" */ len--; path[len]= '\0'; } cp= strrchr(path, '/'); if (cp != NULL) return cp+1; return path; }
the_stack_data/1228055.c
/* This program use Escape sequences, to show*/ /* what kind of problem could occurred*/ /* How to use: Type the name of file on CMD (or another console), and next arguments. Arguments which u can type are escape sequences. U can type as many as u want sequences. Example: hello n r b f t v a hello n b f a ? ' \ Order of parameters is not important, hello a ' \ f r n And u can to replicate the same parameters, hello n r a n r b n r ' Only " u have to type like that: hello """ !! NOT like that : hello " !! */ #include <stdio.h> int main(int amount,char * content[]) { /* All escape sequences \n Represents a newline character (0x0A) \r Represents a carriage return (0x0D) \b Represents a backspace (0x08) \f Represents a form-feed character (0x0C) \t Represents a horizontal tab (0x09) \v Represents a vertical tab (0x0B) \a Inserts a bell (alert) character (0x07) \? Inserts a question mark (?) (0x3F) \" Inserts a double quote (") (0x22) \' Inserts a single quote (') (0x27) \\ Inserts a backslash (\) (0x5C) */ int i; char sec; if(amount<2) { printf("Too few arguments"); return -1; } for(i=0;i<(amount-1);i++) { printf("\n####################################################\n");/*52*/ content++; sec=(char)(*content[0]); switch(sec) { case 'n': sec = '\n'; printf("hex: 0x%X \\n ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",10);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\n text"); break; case 'r': sec = '\r'; printf("hex: 0x%X \\r ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",13);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\r text"); break; case 'b': sec = '\b'; printf("hex: 0x%X \\b ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",8);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\b text"); break; case 'f': sec = '\f'; printf("hex: 0x%X \\f ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",12);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\f text"); break; case 't': sec = '\t'; printf("hex: 0x%X \\t ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",9);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\f text"); break; case 'v': sec = '\v'; printf("hex: 0x%X \\v ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",11);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\v text"); break; case 'a': sec = '\a'; printf("hex: 0x%X \\a ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",7);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\a text"); break; case '?': sec = '\?'; printf("hex: 0x%X \\? ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",63);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\? text"); break; case '\"': /* when u want see this context, u have to write """, u can't just write " like with another cases*/ sec = '\"'; printf("hex: 0x%X \\\" ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",34);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\" text"); break; case '\'': sec = '\''; printf("hex: 0x%X \\\' ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",39);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\' text"); break; case '\\': /* when u want see this context, u have to write """, u can't just write " like with another cases*/ sec = '\\'; printf("hex: 0x%X \\ ",sec);/*first slash is working to next slash, not 'n'*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use from variable: this is%c text",sec); printf("\n----------------------------------------------------\n");/*52*/ printf("use number: this is%c text",92);/*equivalent as number*/ printf("\n----------------------------------------------------\n");/*52*/ printf("use into stream: this is\\ text"); break; default: printf("\nWrong argument\n"); break; }/*switch*/ }/*for*/ printf("\n####################################################\n");/*52*/ printf("\n"); return 0; }
the_stack_data/1068207.c
// SORT int array[] = {10, 5, 1, 77, 12, 34, 55, 67}; int i, j, min_i, temp; int size = 8; void main() { for (i = 0; i < size; i++) printf("%d ", array[i]); putchar(10); for (i = 0; i < size - 1; i++) { // set the initial value of the minimum index min_i = i; // find the index of the minimum element for (j = i + 1; j < size; j++) { if (array[j] < array[min_i]) { min_i = j; } } // swap values temp = array[i]; array[i] = array[min_i]; array[min_i] = temp; } for (i = 0; i < size; i++) printf("%d ", array[i]); }
the_stack_data/232957047.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> int conversion_successes = 0; int conversion_failures = 0; FILE * fortranoutput; void check_conversion(bool criterion) { if ( criterion ) { printf("CONVERSION SUCCESSFULL\n\n"); conversion_successes++; } else { printf("CONVERSION FAILED\n\n"); conversion_failures++; } } int main (int argc, char ** argv) { uint8_t uint8_from_int16_128; uint8_t uint8_from_int16_255; uint8_t uint8_from_int32_128; uint8_t uint8_from_int32_255; uint8_t uint8_from_int64_128; uint8_t uint8_from_int64_255; uint16_t uint16_from_int32_32768; uint16_t uint16_from_int32_65535; uint16_t uint16_from_int64_32768; uint16_t uint16_from_int64_65535; uint32_t uint32_from_int64_2147483648; uint32_t uint32_from_int64_4294967295; fortranoutput = fopen("output_fortran.bin", "r"); if (fortranoutput == NULL) { printf("FAILED TO OPEN THE FORTRAN OUTPUT FILE.\n"); } if (fread( &uint8_from_int16_128, sizeof(uint8_from_int16_128), (size_t) 1, fortranoutput ) == 0 ) exit(EXIT_FAILURE); printf("Expected value for uint8_from_int16_128 : 128\n"); printf("Obtained_result : %hhu \n", uint8_from_int16_128); check_conversion ( uint8_from_int16_128 == (uint8_t) 128 ); if(fread( &uint8_from_int16_255, sizeof(uint8_from_int16_255), (size_t) 1, fortranoutput ) == 0 ) exit(EXIT_FAILURE); printf("Expected value for uint8_from_int16_255 : 255\n"); printf("Obtained_result : %hhu \n", uint8_from_int16_255); check_conversion ( uint8_from_int16_255 == (uint8_t) 255 ); if( fread( &uint8_from_int32_128, sizeof(uint8_from_int32_128), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint8_from_int16_255 : 128\n"); printf("Obtained_result : %hhu \n", uint8_from_int32_128); check_conversion ( uint8_from_int32_128 == (uint8_t) 128 ); if( fread( &uint8_from_int32_255, sizeof(uint8_from_int32_255), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint8_from_int16_255 : 255\n"); printf("Obtained_result : %hhu \n", uint8_from_int32_255); check_conversion ( uint8_from_int32_255 == (uint8_t) 255 ); if( fread( &uint8_from_int64_128, sizeof(uint8_from_int64_128), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint8_from_int64_128 : 128\n"); printf("Obtained_result : %hhu \n", uint8_from_int64_128); check_conversion ( uint8_from_int64_128 == (uint8_t) 128 ); if( fread( &uint8_from_int64_255, sizeof(uint8_from_int64_255), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint8_from_int64_255 : 255\n"); printf("Obtained_result : %hhu \n", uint8_from_int64_255); check_conversion ( uint8_from_int64_255 == (uint8_t) 255 ); if( fread( &uint16_from_int32_32768, sizeof(uint16_from_int32_32768), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint16_from_int32_32768 : 32768\n"); printf("Obtained_result : %hu \n", uint16_from_int32_32768); check_conversion ( uint16_from_int32_32768 == (uint16_t) 32768); if( fread( &uint16_from_int32_65535, sizeof(uint16_from_int32_65535), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint16_from_int32_65535 : 65535\n"); printf("Obtained_result : %hu \n", uint16_from_int32_65535); check_conversion( uint16_from_int32_65535 == (uint16_t) 65535); if( fread( &uint16_from_int64_32768, sizeof(uint16_from_int64_32768), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint16_from_int64_32768 : 32768\n"); printf("Obtained_result : %hu \n", uint16_from_int64_32768); check_conversion ( uint16_from_int64_32768 == (uint16_t) 32768); if( fread( &uint16_from_int64_65535, sizeof(uint16_from_int64_65535), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint16_from_int64_65535 : 65535\n"); printf("Obtained_result : %hu \n", uint16_from_int64_65535); check_conversion ( uint16_from_int64_65535 == (uint16_t) 65535); if( fread( &uint32_from_int64_2147483648, sizeof(uint32_from_int64_2147483648), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint32_from_int64_2147483648 : 2147483648\n"); printf("Obtained_result : %u \n", uint32_from_int64_2147483648); check_conversion ( uint32_from_int64_2147483648 == (uint32_t) 2147483648); if( fread( &uint32_from_int64_4294967295, sizeof(uint32_from_int64_4294967295), (size_t) 1, fortranoutput ) == 0) exit(EXIT_FAILURE); printf("Expected value for uint32_from_int64_4294967295: 4294967295\n"); printf("Obtained_result : %u \n", uint32_from_int64_4294967295); check_conversion ( uint32_from_int64_4294967295 == (uint32_t) 4294967295); fclose(fortranoutput); }
the_stack_data/92324443.c
// // upcase_2.c // ViperNEC // // Created by Dylan Crocker on 6/28/14. // Copyright 2014 Viper Science // // 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. // /** * This function (upcase_2) is a cleaned up version of the function generated by * f2c (upcase_) with some modifications. The main change is the removal of * superfluous variables. The length the input and output buffers should be the * same. * * Original FORTRAN documentation: * UPCASE finds the length of INTEXT and converts it to upper case. * * @param intext The text to be converted. * @param outtxt The buffer to which the converted text is stored. * @param length The length of the text to be converted. Note: the output buffer * must at minimum contain room for length+1 characters. * @since v1.0 */ void upcase_2(char *intext, char *outtxt, int length) { char j; for (int index = 0; index < length; ++index) { j = intext[index]; if (j >= 96) { j += -32; } outtxt[index] = j; } }
the_stack_data/100140421.c
# 1 "benchmarks/ds-08-impl2.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "/usr/include/stdc-predef.h" 1 3 4 # 1 "<command-line>" 2 # 1 "benchmarks/ds-08-impl2.c" # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 1 # 20 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/definitions.h" 1 # 132 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/definitions.h" int X_SIZE_VALUE = 0; int overflow_mode = 1; int rounding_mode = 0; # 155 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/definitions.h" typedef struct { double a[100]; int a_size; double b[100]; int b_size; double sample_time; double a_uncertainty[100]; double b_uncertainty[100]; } digital_system; typedef struct { double A[4][4]; double B[4][4]; double C[4][4]; double D[4][4]; double states[4][4]; double outputs[4][4]; double inputs[4][4]; double K[4][4]; unsigned int nStates; unsigned int nInputs; unsigned int nOutputs; } digital_system_state_space; typedef struct { int int_bits; int frac_bits; double max; double min; int default_realization; double delta; int scale; double max_error; } implementation; typedef struct { int push; int in; int sbiw; int cli; int out; int std; int ldd; int subi; int sbci; int lsl; int rol; int add; int adc; int adiw; int rjmp; int mov; int sbc; int ld; int rcall; int cp; int cpc; int ldi; int brge; int pop; int ret; int st; int brlt; int cpi; } instructions; typedef struct { long clock; int device; double cycle; instructions assembly; } hardware; typedef struct{ float Ap, Ar, Ac; float wp, wc, wr; int type; }filter_parameters; # 21 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 1 # 17 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" # 1 "/usr/include/stdlib.h" 1 3 4 # 25 "/usr/include/stdlib.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 1 3 4 # 33 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 3 4 # 1 "/usr/include/features.h" 1 3 4 # 461 "/usr/include/features.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4 # 452 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4 # 453 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/long-double.h" 1 3 4 # 454 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4 # 462 "/usr/include/features.h" 2 3 4 # 485 "/usr/include/features.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 1 3 4 # 10 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/gnu/stubs-64.h" 1 3 4 # 11 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 2 3 4 # 486 "/usr/include/features.h" 2 3 4 # 34 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 2 3 4 # 26 "/usr/include/stdlib.h" 2 3 4 # 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 1 3 4 # 209 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 3 4 # 209 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 3 4 typedef long unsigned int size_t; # 321 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 3 4 typedef int wchar_t; # 32 "/usr/include/stdlib.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/waitflags.h" 1 3 4 # 52 "/usr/include/x86_64-linux-gnu/bits/waitflags.h" 3 4 typedef enum { P_ALL, P_PID, P_PGID } idtype_t; # 40 "/usr/include/stdlib.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/waitstatus.h" 1 3 4 # 41 "/usr/include/stdlib.h" 2 3 4 # 55 "/usr/include/stdlib.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/floatn.h" 1 3 4 # 120 "/usr/include/x86_64-linux-gnu/bits/floatn.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/floatn-common.h" 1 3 4 # 24 "/usr/include/x86_64-linux-gnu/bits/floatn-common.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/long-double.h" 1 3 4 # 25 "/usr/include/x86_64-linux-gnu/bits/floatn-common.h" 2 3 4 # 121 "/usr/include/x86_64-linux-gnu/bits/floatn.h" 2 3 4 # 56 "/usr/include/stdlib.h" 2 3 4 typedef struct { int quot; int rem; } div_t; typedef struct { long int quot; long int rem; } ldiv_t; __extension__ typedef struct { long long int quot; long long int rem; } lldiv_t; # 97 "/usr/include/stdlib.h" 3 4 extern size_t __ctype_get_mb_cur_max (void) __attribute__ ((__nothrow__ , __leaf__)) ; extern double atof (const char *__nptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; extern int atoi (const char *__nptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; extern long int atol (const char *__nptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; __extension__ extern long long int atoll (const char *__nptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; extern double strtod (const char *__restrict __nptr, char **__restrict __endptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern float strtof (const char *__restrict __nptr, char **__restrict __endptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern long double strtold (const char *__restrict __nptr, char **__restrict __endptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); # 176 "/usr/include/stdlib.h" 3 4 extern long int strtol (const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern unsigned long int strtoul (const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); __extension__ extern long long int strtoq (const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); __extension__ extern unsigned long long int strtouq (const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); __extension__ extern long long int strtoll (const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); __extension__ extern unsigned long long int strtoull (const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); # 385 "/usr/include/stdlib.h" 3 4 extern char *l64a (long int __n) __attribute__ ((__nothrow__ , __leaf__)) ; extern long int a64l (const char *__s) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ; # 1 "/usr/include/x86_64-linux-gnu/sys/types.h" 1 3 4 # 27 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types.h" 1 3 4 # 27 "/usr/include/x86_64-linux-gnu/bits/types.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4 # 28 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/timesize.h" 1 3 4 # 29 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4 typedef unsigned char __u_char; typedef unsigned short int __u_short; typedef unsigned int __u_int; typedef unsigned long int __u_long; typedef signed char __int8_t; typedef unsigned char __uint8_t; typedef signed short int __int16_t; typedef unsigned short int __uint16_t; typedef signed int __int32_t; typedef unsigned int __uint32_t; typedef signed long int __int64_t; typedef unsigned long int __uint64_t; typedef __int8_t __int_least8_t; typedef __uint8_t __uint_least8_t; typedef __int16_t __int_least16_t; typedef __uint16_t __uint_least16_t; typedef __int32_t __int_least32_t; typedef __uint32_t __uint_least32_t; typedef __int64_t __int_least64_t; typedef __uint64_t __uint_least64_t; typedef long int __quad_t; typedef unsigned long int __u_quad_t; typedef long int __intmax_t; typedef unsigned long int __uintmax_t; # 141 "/usr/include/x86_64-linux-gnu/bits/types.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/typesizes.h" 1 3 4 # 142 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/time64.h" 1 3 4 # 143 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4 typedef unsigned long int __dev_t; typedef unsigned int __uid_t; typedef unsigned int __gid_t; typedef unsigned long int __ino_t; typedef unsigned long int __ino64_t; typedef unsigned int __mode_t; typedef unsigned long int __nlink_t; typedef long int __off_t; typedef long int __off64_t; typedef int __pid_t; typedef struct { int __val[2]; } __fsid_t; typedef long int __clock_t; typedef unsigned long int __rlim_t; typedef unsigned long int __rlim64_t; typedef unsigned int __id_t; typedef long int __time_t; typedef unsigned int __useconds_t; typedef long int __suseconds_t; typedef int __daddr_t; typedef int __key_t; typedef int __clockid_t; typedef void * __timer_t; typedef long int __blksize_t; typedef long int __blkcnt_t; typedef long int __blkcnt64_t; typedef unsigned long int __fsblkcnt_t; typedef unsigned long int __fsblkcnt64_t; typedef unsigned long int __fsfilcnt_t; typedef unsigned long int __fsfilcnt64_t; typedef long int __fsword_t; typedef long int __ssize_t; typedef long int __syscall_slong_t; typedef unsigned long int __syscall_ulong_t; typedef __off64_t __loff_t; typedef char *__caddr_t; typedef long int __intptr_t; typedef unsigned int __socklen_t; typedef int __sig_atomic_t; # 30 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 typedef __u_char u_char; typedef __u_short u_short; typedef __u_int u_int; typedef __u_long u_long; typedef __quad_t quad_t; typedef __u_quad_t u_quad_t; typedef __fsid_t fsid_t; typedef __loff_t loff_t; typedef __ino_t ino_t; # 59 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4 typedef __dev_t dev_t; typedef __gid_t gid_t; typedef __mode_t mode_t; typedef __nlink_t nlink_t; typedef __uid_t uid_t; typedef __off_t off_t; # 97 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4 typedef __pid_t pid_t; typedef __id_t id_t; typedef __ssize_t ssize_t; typedef __daddr_t daddr_t; typedef __caddr_t caddr_t; typedef __key_t key_t; # 1 "/usr/include/x86_64-linux-gnu/bits/types/clock_t.h" 1 3 4 typedef __clock_t clock_t; # 127 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/clockid_t.h" 1 3 4 typedef __clockid_t clockid_t; # 129 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/time_t.h" 1 3 4 typedef __time_t time_t; # 130 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/timer_t.h" 1 3 4 typedef __timer_t timer_t; # 131 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 # 144 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4 # 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 1 3 4 # 145 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 typedef unsigned long int ulong; typedef unsigned short int ushort; typedef unsigned int uint; # 1 "/usr/include/x86_64-linux-gnu/bits/stdint-intn.h" 1 3 4 # 24 "/usr/include/x86_64-linux-gnu/bits/stdint-intn.h" 3 4 typedef __int8_t int8_t; typedef __int16_t int16_t; typedef __int32_t int32_t; typedef __int64_t int64_t; # 156 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 typedef __uint8_t u_int8_t; typedef __uint16_t u_int16_t; typedef __uint32_t u_int32_t; typedef __uint64_t u_int64_t; typedef int register_t __attribute__ ((__mode__ (__word__))); # 176 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4 # 1 "/usr/include/endian.h" 1 3 4 # 24 "/usr/include/endian.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/endian.h" 1 3 4 # 35 "/usr/include/x86_64-linux-gnu/bits/endian.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/endianness.h" 1 3 4 # 36 "/usr/include/x86_64-linux-gnu/bits/endian.h" 2 3 4 # 25 "/usr/include/endian.h" 2 3 4 # 35 "/usr/include/endian.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/byteswap.h" 1 3 4 # 33 "/usr/include/x86_64-linux-gnu/bits/byteswap.h" 3 4 static __inline __uint16_t __bswap_16 (__uint16_t __bsx) { return __builtin_bswap16 (__bsx); } static __inline __uint32_t __bswap_32 (__uint32_t __bsx) { return __builtin_bswap32 (__bsx); } # 69 "/usr/include/x86_64-linux-gnu/bits/byteswap.h" 3 4 __extension__ static __inline __uint64_t __bswap_64 (__uint64_t __bsx) { return __builtin_bswap64 (__bsx); } # 36 "/usr/include/endian.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/uintn-identity.h" 1 3 4 # 32 "/usr/include/x86_64-linux-gnu/bits/uintn-identity.h" 3 4 static __inline __uint16_t __uint16_identity (__uint16_t __x) { return __x; } static __inline __uint32_t __uint32_identity (__uint32_t __x) { return __x; } static __inline __uint64_t __uint64_identity (__uint64_t __x) { return __x; } # 37 "/usr/include/endian.h" 2 3 4 # 177 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/sys/select.h" 1 3 4 # 30 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/select.h" 1 3 4 # 22 "/usr/include/x86_64-linux-gnu/bits/select.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4 # 23 "/usr/include/x86_64-linux-gnu/bits/select.h" 2 3 4 # 31 "/usr/include/x86_64-linux-gnu/sys/select.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/sigset_t.h" 1 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/__sigset_t.h" 1 3 4 typedef struct { unsigned long int __val[(1024 / (8 * sizeof (unsigned long int)))]; } __sigset_t; # 5 "/usr/include/x86_64-linux-gnu/bits/types/sigset_t.h" 2 3 4 typedef __sigset_t sigset_t; # 34 "/usr/include/x86_64-linux-gnu/sys/select.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/struct_timeval.h" 1 3 4 struct timeval { __time_t tv_sec; __suseconds_t tv_usec; }; # 38 "/usr/include/x86_64-linux-gnu/sys/select.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/struct_timespec.h" 1 3 4 # 10 "/usr/include/x86_64-linux-gnu/bits/types/struct_timespec.h" 3 4 struct timespec { __time_t tv_sec; __syscall_slong_t tv_nsec; # 26 "/usr/include/x86_64-linux-gnu/bits/types/struct_timespec.h" 3 4 }; # 40 "/usr/include/x86_64-linux-gnu/sys/select.h" 2 3 4 typedef __suseconds_t suseconds_t; typedef long int __fd_mask; # 59 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4 typedef struct { __fd_mask __fds_bits[1024 / (8 * (int) sizeof (__fd_mask))]; } fd_set; typedef __fd_mask fd_mask; # 91 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4 # 101 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4 extern int select (int __nfds, fd_set *__restrict __readfds, fd_set *__restrict __writefds, fd_set *__restrict __exceptfds, struct timeval *__restrict __timeout); # 113 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4 extern int pselect (int __nfds, fd_set *__restrict __readfds, fd_set *__restrict __writefds, fd_set *__restrict __exceptfds, const struct timespec *__restrict __timeout, const __sigset_t *__restrict __sigmask); # 126 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4 # 180 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 typedef __blksize_t blksize_t; typedef __blkcnt_t blkcnt_t; typedef __fsblkcnt_t fsblkcnt_t; typedef __fsfilcnt_t fsfilcnt_t; # 227 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 1 3 4 # 23 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/thread-shared-types.h" 1 3 4 # 44 "/usr/include/x86_64-linux-gnu/bits/thread-shared-types.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes-arch.h" 1 3 4 # 21 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes-arch.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4 # 22 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes-arch.h" 2 3 4 # 45 "/usr/include/x86_64-linux-gnu/bits/thread-shared-types.h" 2 3 4 typedef struct __pthread_internal_list { struct __pthread_internal_list *__prev; struct __pthread_internal_list *__next; } __pthread_list_t; typedef struct __pthread_internal_slist { struct __pthread_internal_slist *__next; } __pthread_slist_t; # 74 "/usr/include/x86_64-linux-gnu/bits/thread-shared-types.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/struct_mutex.h" 1 3 4 # 22 "/usr/include/x86_64-linux-gnu/bits/struct_mutex.h" 3 4 struct __pthread_mutex_s { int __lock; unsigned int __count; int __owner; unsigned int __nusers; int __kind; short __spins; short __elision; __pthread_list_t __list; # 53 "/usr/include/x86_64-linux-gnu/bits/struct_mutex.h" 3 4 }; # 75 "/usr/include/x86_64-linux-gnu/bits/thread-shared-types.h" 2 3 4 # 87 "/usr/include/x86_64-linux-gnu/bits/thread-shared-types.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/struct_rwlock.h" 1 3 4 # 23 "/usr/include/x86_64-linux-gnu/bits/struct_rwlock.h" 3 4 struct __pthread_rwlock_arch_t { unsigned int __readers; unsigned int __writers; unsigned int __wrphase_futex; unsigned int __writers_futex; unsigned int __pad3; unsigned int __pad4; int __cur_writer; int __shared; signed char __rwelision; unsigned char __pad1[7]; unsigned long int __pad2; unsigned int __flags; # 55 "/usr/include/x86_64-linux-gnu/bits/struct_rwlock.h" 3 4 }; # 88 "/usr/include/x86_64-linux-gnu/bits/thread-shared-types.h" 2 3 4 struct __pthread_cond_s { __extension__ union { __extension__ unsigned long long int __wseq; struct { unsigned int __low; unsigned int __high; } __wseq32; }; __extension__ union { __extension__ unsigned long long int __g1_start; struct { unsigned int __low; unsigned int __high; } __g1_start32; }; unsigned int __g_refs[2] ; unsigned int __g_size[2]; unsigned int __g1_orig_size; unsigned int __wrefs; unsigned int __g_signals[2]; }; # 24 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 2 3 4 typedef unsigned long int pthread_t; typedef union { char __size[4]; int __align; } pthread_mutexattr_t; typedef union { char __size[4]; int __align; } pthread_condattr_t; typedef unsigned int pthread_key_t; typedef int pthread_once_t; union pthread_attr_t { char __size[56]; long int __align; }; typedef union pthread_attr_t pthread_attr_t; typedef union { struct __pthread_mutex_s __data; char __size[40]; long int __align; } pthread_mutex_t; typedef union { struct __pthread_cond_s __data; char __size[48]; __extension__ long long int __align; } pthread_cond_t; typedef union { struct __pthread_rwlock_arch_t __data; char __size[56]; long int __align; } pthread_rwlock_t; typedef union { char __size[8]; long int __align; } pthread_rwlockattr_t; typedef volatile int pthread_spinlock_t; typedef union { char __size[32]; long int __align; } pthread_barrier_t; typedef union { char __size[4]; int __align; } pthread_barrierattr_t; # 228 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4 # 395 "/usr/include/stdlib.h" 2 3 4 extern long int random (void) __attribute__ ((__nothrow__ , __leaf__)); extern void srandom (unsigned int __seed) __attribute__ ((__nothrow__ , __leaf__)); extern char *initstate (unsigned int __seed, char *__statebuf, size_t __statelen) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))); extern char *setstate (char *__statebuf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); struct random_data { int32_t *fptr; int32_t *rptr; int32_t *state; int rand_type; int rand_deg; int rand_sep; int32_t *end_ptr; }; extern int random_r (struct random_data *__restrict __buf, int32_t *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern int srandom_r (unsigned int __seed, struct random_data *__buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))); extern int initstate_r (unsigned int __seed, char *__restrict __statebuf, size_t __statelen, struct random_data *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4))); extern int setstate_r (char *__restrict __statebuf, struct random_data *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern int rand (void) __attribute__ ((__nothrow__ , __leaf__)); extern void srand (unsigned int __seed) __attribute__ ((__nothrow__ , __leaf__)); extern int rand_r (unsigned int *__seed) __attribute__ ((__nothrow__ , __leaf__)); extern double drand48 (void) __attribute__ ((__nothrow__ , __leaf__)); extern double erand48 (unsigned short int __xsubi[3]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern long int lrand48 (void) __attribute__ ((__nothrow__ , __leaf__)); extern long int nrand48 (unsigned short int __xsubi[3]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern long int mrand48 (void) __attribute__ ((__nothrow__ , __leaf__)); extern long int jrand48 (unsigned short int __xsubi[3]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern void srand48 (long int __seedval) __attribute__ ((__nothrow__ , __leaf__)); extern unsigned short int *seed48 (unsigned short int __seed16v[3]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern void lcong48 (unsigned short int __param[7]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); struct drand48_data { unsigned short int __x[3]; unsigned short int __old_x[3]; unsigned short int __c; unsigned short int __init; __extension__ unsigned long long int __a; }; extern int drand48_r (struct drand48_data *__restrict __buffer, double *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern int erand48_r (unsigned short int __xsubi[3], struct drand48_data *__restrict __buffer, double *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern int lrand48_r (struct drand48_data *__restrict __buffer, long int *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern int nrand48_r (unsigned short int __xsubi[3], struct drand48_data *__restrict __buffer, long int *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern int mrand48_r (struct drand48_data *__restrict __buffer, long int *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern int jrand48_r (unsigned short int __xsubi[3], struct drand48_data *__restrict __buffer, long int *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern int srand48_r (long int __seedval, struct drand48_data *__buffer) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))); extern int seed48_r (unsigned short int __seed16v[3], struct drand48_data *__buffer) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern int lcong48_r (unsigned short int __param[7], struct drand48_data *__buffer) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))); extern void *malloc (size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__alloc_size__ (1))) ; extern void *calloc (size_t __nmemb, size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__alloc_size__ (1, 2))) ; extern void *realloc (void *__ptr, size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__)) __attribute__ ((__alloc_size__ (2))); extern void *reallocarray (void *__ptr, size_t __nmemb, size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__)) __attribute__ ((__alloc_size__ (2, 3))); extern void free (void *__ptr) __attribute__ ((__nothrow__ , __leaf__)); # 1 "/usr/include/alloca.h" 1 3 4 # 24 "/usr/include/alloca.h" 3 4 # 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 1 3 4 # 25 "/usr/include/alloca.h" 2 3 4 extern void *alloca (size_t __size) __attribute__ ((__nothrow__ , __leaf__)); # 569 "/usr/include/stdlib.h" 2 3 4 extern void *valloc (size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__alloc_size__ (1))) ; extern int posix_memalign (void **__memptr, size_t __alignment, size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ; extern void *aligned_alloc (size_t __alignment, size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__alloc_size__ (2))) ; extern void abort (void) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__)); extern int atexit (void (*__func) (void)) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern int at_quick_exit (void (*__func) (void)) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern int on_exit (void (*__func) (int __status, void *__arg), void *__arg) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern void exit (int __status) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__)); extern void quick_exit (int __status) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__)); extern void _Exit (int __status) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__)); extern char *getenv (const char *__name) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ; # 647 "/usr/include/stdlib.h" 3 4 extern int putenv (char *__string) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern int setenv (const char *__name, const char *__value, int __replace) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))); extern int unsetenv (const char *__name) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); extern int clearenv (void) __attribute__ ((__nothrow__ , __leaf__)); # 675 "/usr/include/stdlib.h" 3 4 extern char *mktemp (char *__template) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); # 688 "/usr/include/stdlib.h" 3 4 extern int mkstemp (char *__template) __attribute__ ((__nonnull__ (1))) ; # 710 "/usr/include/stdlib.h" 3 4 extern int mkstemps (char *__template, int __suffixlen) __attribute__ ((__nonnull__ (1))) ; # 731 "/usr/include/stdlib.h" 3 4 extern char *mkdtemp (char *__template) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ; # 784 "/usr/include/stdlib.h" 3 4 extern int system (const char *__command) ; # 800 "/usr/include/stdlib.h" 3 4 extern char *realpath (const char *__restrict __name, char *__restrict __resolved) __attribute__ ((__nothrow__ , __leaf__)) ; typedef int (*__compar_fn_t) (const void *, const void *); # 820 "/usr/include/stdlib.h" 3 4 extern void *bsearch (const void *__key, const void *__base, size_t __nmemb, size_t __size, __compar_fn_t __compar) __attribute__ ((__nonnull__ (1, 2, 5))) ; extern void qsort (void *__base, size_t __nmemb, size_t __size, __compar_fn_t __compar) __attribute__ ((__nonnull__ (1, 4))); # 840 "/usr/include/stdlib.h" 3 4 extern int abs (int __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) ; extern long int labs (long int __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) ; __extension__ extern long long int llabs (long long int __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) ; extern div_t div (int __numer, int __denom) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) ; extern ldiv_t ldiv (long int __numer, long int __denom) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) ; __extension__ extern lldiv_t lldiv (long long int __numer, long long int __denom) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) ; # 872 "/usr/include/stdlib.h" 3 4 extern char *ecvt (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4))) ; extern char *fcvt (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4))) ; extern char *gcvt (double __value, int __ndigit, char *__buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3))) ; extern char *qecvt (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4))) ; extern char *qfcvt (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4))) ; extern char *qgcvt (long double __value, int __ndigit, char *__buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3))) ; extern int ecvt_r (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign, char *__restrict __buf, size_t __len) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4, 5))); extern int fcvt_r (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign, char *__restrict __buf, size_t __len) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4, 5))); extern int qecvt_r (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign, char *__restrict __buf, size_t __len) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4, 5))); extern int qfcvt_r (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign, char *__restrict __buf, size_t __len) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4, 5))); extern int mblen (const char *__s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)); extern int mbtowc (wchar_t *__restrict __pwc, const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)); extern int wctomb (char *__s, wchar_t __wchar) __attribute__ ((__nothrow__ , __leaf__)); extern size_t mbstowcs (wchar_t *__restrict __pwcs, const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)); extern size_t wcstombs (char *__restrict __s, const wchar_t *__restrict __pwcs, size_t __n) __attribute__ ((__nothrow__ , __leaf__)); extern int rpmatch (const char *__response) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ; # 957 "/usr/include/stdlib.h" 3 4 extern int getsubopt (char **__restrict __optionp, char *const *__restrict __tokens, char **__restrict __valuep) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2, 3))) ; # 1003 "/usr/include/stdlib.h" 3 4 extern int getloadavg (double __loadavg[], int __nelem) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))); # 1013 "/usr/include/stdlib.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/stdlib-float.h" 1 3 4 # 1014 "/usr/include/stdlib.h" 2 3 4 # 1023 "/usr/include/stdlib.h" 3 4 # 18 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 2 # 1 "/usr/include/assert.h" 1 3 4 # 66 "/usr/include/assert.h" 3 4 extern void __assert_fail (const char *__assertion, const char *__file, unsigned int __line, const char *__function) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__)); extern void __assert_perror_fail (int __errnum, const char *__file, unsigned int __line, const char *__function) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__)); extern void __assert (const char *__assertion, const char *__file, int __line) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__)); # 19 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 2 # 1 "/usr/include/stdio.h" 1 3 4 # 27 "/usr/include/stdio.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 1 3 4 # 28 "/usr/include/stdio.h" 2 3 4 # 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 1 3 4 # 34 "/usr/include/stdio.h" 2 3 4 # 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stdarg.h" 1 3 4 # 40 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stdarg.h" 3 4 typedef __builtin_va_list __gnuc_va_list; # 37 "/usr/include/stdio.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/__fpos_t.h" 1 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/__mbstate_t.h" 1 3 4 # 13 "/usr/include/x86_64-linux-gnu/bits/types/__mbstate_t.h" 3 4 typedef struct { int __count; union { unsigned int __wch; char __wchb[4]; } __value; } __mbstate_t; # 6 "/usr/include/x86_64-linux-gnu/bits/types/__fpos_t.h" 2 3 4 typedef struct _G_fpos_t { __off_t __pos; __mbstate_t __state; } __fpos_t; # 40 "/usr/include/stdio.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/__fpos64_t.h" 1 3 4 # 10 "/usr/include/x86_64-linux-gnu/bits/types/__fpos64_t.h" 3 4 typedef struct _G_fpos64_t { __off64_t __pos; __mbstate_t __state; } __fpos64_t; # 41 "/usr/include/stdio.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/__FILE.h" 1 3 4 struct _IO_FILE; typedef struct _IO_FILE __FILE; # 42 "/usr/include/stdio.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/FILE.h" 1 3 4 struct _IO_FILE; typedef struct _IO_FILE FILE; # 43 "/usr/include/stdio.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/types/struct_FILE.h" 1 3 4 # 35 "/usr/include/x86_64-linux-gnu/bits/types/struct_FILE.h" 3 4 struct _IO_FILE; struct _IO_marker; struct _IO_codecvt; struct _IO_wide_data; typedef void _IO_lock_t; struct _IO_FILE { int _flags; char *_IO_read_ptr; char *_IO_read_end; char *_IO_read_base; char *_IO_write_base; char *_IO_write_ptr; char *_IO_write_end; char *_IO_buf_base; char *_IO_buf_end; char *_IO_save_base; char *_IO_backup_base; char *_IO_save_end; struct _IO_marker *_markers; struct _IO_FILE *_chain; int _fileno; int _flags2; __off_t _old_offset; unsigned short _cur_column; signed char _vtable_offset; char _shortbuf[1]; _IO_lock_t *_lock; __off64_t _offset; struct _IO_codecvt *_codecvt; struct _IO_wide_data *_wide_data; struct _IO_FILE *_freeres_list; void *_freeres_buf; size_t __pad5; int _mode; char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)]; }; # 44 "/usr/include/stdio.h" 2 3 4 # 52 "/usr/include/stdio.h" 3 4 typedef __gnuc_va_list va_list; # 84 "/usr/include/stdio.h" 3 4 typedef __fpos_t fpos_t; # 133 "/usr/include/stdio.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/stdio_lim.h" 1 3 4 # 134 "/usr/include/stdio.h" 2 3 4 extern FILE *stdin; extern FILE *stdout; extern FILE *stderr; extern int remove (const char *__filename) __attribute__ ((__nothrow__ , __leaf__)); extern int rename (const char *__old, const char *__new) __attribute__ ((__nothrow__ , __leaf__)); extern int renameat (int __oldfd, const char *__old, int __newfd, const char *__new) __attribute__ ((__nothrow__ , __leaf__)); # 173 "/usr/include/stdio.h" 3 4 extern FILE *tmpfile (void) ; # 187 "/usr/include/stdio.h" 3 4 extern char *tmpnam (char *__s) __attribute__ ((__nothrow__ , __leaf__)) ; extern char *tmpnam_r (char *__s) __attribute__ ((__nothrow__ , __leaf__)) ; # 204 "/usr/include/stdio.h" 3 4 extern char *tempnam (const char *__dir, const char *__pfx) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) ; extern int fclose (FILE *__stream); extern int fflush (FILE *__stream); # 227 "/usr/include/stdio.h" 3 4 extern int fflush_unlocked (FILE *__stream); # 246 "/usr/include/stdio.h" 3 4 extern FILE *fopen (const char *__restrict __filename, const char *__restrict __modes) ; extern FILE *freopen (const char *__restrict __filename, const char *__restrict __modes, FILE *__restrict __stream) ; # 279 "/usr/include/stdio.h" 3 4 extern FILE *fdopen (int __fd, const char *__modes) __attribute__ ((__nothrow__ , __leaf__)) ; # 292 "/usr/include/stdio.h" 3 4 extern FILE *fmemopen (void *__s, size_t __len, const char *__modes) __attribute__ ((__nothrow__ , __leaf__)) ; extern FILE *open_memstream (char **__bufloc, size_t *__sizeloc) __attribute__ ((__nothrow__ , __leaf__)) ; extern void setbuf (FILE *__restrict __stream, char *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__)); extern int setvbuf (FILE *__restrict __stream, char *__restrict __buf, int __modes, size_t __n) __attribute__ ((__nothrow__ , __leaf__)); extern void setbuffer (FILE *__restrict __stream, char *__restrict __buf, size_t __size) __attribute__ ((__nothrow__ , __leaf__)); extern void setlinebuf (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)); extern int fprintf (FILE *__restrict __stream, const char *__restrict __format, ...); extern int printf (const char *__restrict __format, ...); extern int sprintf (char *__restrict __s, const char *__restrict __format, ...) __attribute__ ((__nothrow__)); extern int vfprintf (FILE *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg); extern int vprintf (const char *__restrict __format, __gnuc_va_list __arg); extern int vsprintf (char *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __attribute__ ((__nothrow__)); extern int snprintf (char *__restrict __s, size_t __maxlen, const char *__restrict __format, ...) __attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 4))); extern int vsnprintf (char *__restrict __s, size_t __maxlen, const char *__restrict __format, __gnuc_va_list __arg) __attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 0))); # 379 "/usr/include/stdio.h" 3 4 extern int vdprintf (int __fd, const char *__restrict __fmt, __gnuc_va_list __arg) __attribute__ ((__format__ (__printf__, 2, 0))); extern int dprintf (int __fd, const char *__restrict __fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))); extern int fscanf (FILE *__restrict __stream, const char *__restrict __format, ...) ; extern int scanf (const char *__restrict __format, ...) ; extern int sscanf (const char *__restrict __s, const char *__restrict __format, ...) __attribute__ ((__nothrow__ , __leaf__)); extern int fscanf (FILE *__restrict __stream, const char *__restrict __format, ...) __asm__ ("" "__isoc99_fscanf") ; extern int scanf (const char *__restrict __format, ...) __asm__ ("" "__isoc99_scanf") ; extern int sscanf (const char *__restrict __s, const char *__restrict __format, ...) __asm__ ("" "__isoc99_sscanf") __attribute__ ((__nothrow__ , __leaf__)) ; # 432 "/usr/include/stdio.h" 3 4 extern int vfscanf (FILE *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __attribute__ ((__format__ (__scanf__, 2, 0))) ; extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg) __attribute__ ((__format__ (__scanf__, 1, 0))) ; extern int vsscanf (const char *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__format__ (__scanf__, 2, 0))); extern int vfscanf (FILE *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vfscanf") __attribute__ ((__format__ (__scanf__, 2, 0))) ; extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vscanf") __attribute__ ((__format__ (__scanf__, 1, 0))) ; extern int vsscanf (const char *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vsscanf") __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__format__ (__scanf__, 2, 0))); # 485 "/usr/include/stdio.h" 3 4 extern int fgetc (FILE *__stream); extern int getc (FILE *__stream); extern int getchar (void); extern int getc_unlocked (FILE *__stream); extern int getchar_unlocked (void); # 510 "/usr/include/stdio.h" 3 4 extern int fgetc_unlocked (FILE *__stream); # 521 "/usr/include/stdio.h" 3 4 extern int fputc (int __c, FILE *__stream); extern int putc (int __c, FILE *__stream); extern int putchar (int __c); # 537 "/usr/include/stdio.h" 3 4 extern int fputc_unlocked (int __c, FILE *__stream); extern int putc_unlocked (int __c, FILE *__stream); extern int putchar_unlocked (int __c); extern int getw (FILE *__stream); extern int putw (int __w, FILE *__stream); extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream) ; # 603 "/usr/include/stdio.h" 3 4 extern __ssize_t __getdelim (char **__restrict __lineptr, size_t *__restrict __n, int __delimiter, FILE *__restrict __stream) ; extern __ssize_t getdelim (char **__restrict __lineptr, size_t *__restrict __n, int __delimiter, FILE *__restrict __stream) ; extern __ssize_t getline (char **__restrict __lineptr, size_t *__restrict __n, FILE *__restrict __stream) ; extern int fputs (const char *__restrict __s, FILE *__restrict __stream); extern int puts (const char *__s); extern int ungetc (int __c, FILE *__stream); extern size_t fread (void *__restrict __ptr, size_t __size, size_t __n, FILE *__restrict __stream) ; extern size_t fwrite (const void *__restrict __ptr, size_t __size, size_t __n, FILE *__restrict __s); # 673 "/usr/include/stdio.h" 3 4 extern size_t fread_unlocked (void *__restrict __ptr, size_t __size, size_t __n, FILE *__restrict __stream) ; extern size_t fwrite_unlocked (const void *__restrict __ptr, size_t __size, size_t __n, FILE *__restrict __stream); extern int fseek (FILE *__stream, long int __off, int __whence); extern long int ftell (FILE *__stream) ; extern void rewind (FILE *__stream); # 707 "/usr/include/stdio.h" 3 4 extern int fseeko (FILE *__stream, __off_t __off, int __whence); extern __off_t ftello (FILE *__stream) ; # 731 "/usr/include/stdio.h" 3 4 extern int fgetpos (FILE *__restrict __stream, fpos_t *__restrict __pos); extern int fsetpos (FILE *__stream, const fpos_t *__pos); # 757 "/usr/include/stdio.h" 3 4 extern void clearerr (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)); extern int feof (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ; extern int ferror (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ; extern void clearerr_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)); extern int feof_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ; extern int ferror_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ; extern void perror (const char *__s); # 1 "/usr/include/x86_64-linux-gnu/bits/sys_errlist.h" 1 3 4 # 26 "/usr/include/x86_64-linux-gnu/bits/sys_errlist.h" 3 4 extern int sys_nerr; extern const char *const sys_errlist[]; # 782 "/usr/include/stdio.h" 2 3 4 extern int fileno (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ; extern int fileno_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ; # 800 "/usr/include/stdio.h" 3 4 extern FILE *popen (const char *__command, const char *__modes) ; extern int pclose (FILE *__stream); extern char *ctermid (char *__s) __attribute__ ((__nothrow__ , __leaf__)); # 840 "/usr/include/stdio.h" 3 4 extern void flockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)); extern int ftrylockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ; extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)); # 858 "/usr/include/stdio.h" 3 4 extern int __uflow (FILE *); extern int __overflow (FILE *, int); # 873 "/usr/include/stdio.h" 3 4 # 20 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 2 # 21 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" void __DSVERIFIER_assume(_Bool expression){ __CPROVER_assume(expression); } void __DSVERIFIER_assert(_Bool expression){ # 36 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 3 4 ((void) sizeof (( # 36 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" expression # 36 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 36 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" expression # 36 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 3 4 ) ; else __assert_fail ( # 36 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" "expression" # 36 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h", 36, __extension__ __PRETTY_FUNCTION__); })) # 36 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" ; } void __DSVERIFIER_assert_msg(_Bool expression, char * msg){ printf("%s", msg); # 41 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 3 4 ((void) sizeof (( # 41 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" expression # 41 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 41 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" expression # 41 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 3 4 ) ; else __assert_fail ( # 41 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" "expression" # 41 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h", 41, __extension__ __PRETTY_FUNCTION__); })) # 41 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/compatibility.h" ; } # 22 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/fixed-point.h" 1 # 27 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/fixed-point.h" # 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stdint.h" 1 3 4 # 9 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stdint.h" 3 4 # 1 "/usr/include/stdint.h" 1 3 4 # 26 "/usr/include/stdint.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 1 3 4 # 27 "/usr/include/stdint.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/wchar.h" 1 3 4 # 29 "/usr/include/stdint.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4 # 30 "/usr/include/stdint.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/stdint-uintn.h" 1 3 4 # 24 "/usr/include/x86_64-linux-gnu/bits/stdint-uintn.h" 3 4 # 24 "/usr/include/x86_64-linux-gnu/bits/stdint-uintn.h" 3 4 typedef __uint8_t uint8_t; typedef __uint16_t uint16_t; typedef __uint32_t uint32_t; typedef __uint64_t uint64_t; # 38 "/usr/include/stdint.h" 2 3 4 typedef __int_least8_t int_least8_t; typedef __int_least16_t int_least16_t; typedef __int_least32_t int_least32_t; typedef __int_least64_t int_least64_t; typedef __uint_least8_t uint_least8_t; typedef __uint_least16_t uint_least16_t; typedef __uint_least32_t uint_least32_t; typedef __uint_least64_t uint_least64_t; typedef signed char int_fast8_t; typedef long int int_fast16_t; typedef long int int_fast32_t; typedef long int int_fast64_t; # 71 "/usr/include/stdint.h" 3 4 typedef unsigned char uint_fast8_t; typedef unsigned long int uint_fast16_t; typedef unsigned long int uint_fast32_t; typedef unsigned long int uint_fast64_t; # 87 "/usr/include/stdint.h" 3 4 typedef long int intptr_t; typedef unsigned long int uintptr_t; # 101 "/usr/include/stdint.h" 3 4 typedef __intmax_t intmax_t; typedef __uintmax_t uintmax_t; # 10 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stdint.h" 2 3 4 # 28 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/fixed-point.h" 2 # 1 "/usr/include/inttypes.h" 1 3 4 # 34 "/usr/include/inttypes.h" 3 4 typedef int __gwchar_t; # 266 "/usr/include/inttypes.h" 3 4 typedef struct { long int quot; long int rem; } imaxdiv_t; # 290 "/usr/include/inttypes.h" 3 4 extern intmax_t imaxabs (intmax_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern imaxdiv_t imaxdiv (intmax_t __numer, intmax_t __denom) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern intmax_t strtoimax (const char *__restrict __nptr, char **__restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)); extern uintmax_t strtoumax (const char *__restrict __nptr, char ** __restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)); extern intmax_t wcstoimax (const __gwchar_t *__restrict __nptr, __gwchar_t **__restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)); extern uintmax_t wcstoumax (const __gwchar_t *__restrict __nptr, __gwchar_t ** __restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__)); # 432 "/usr/include/inttypes.h" 3 4 # 29 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/fixed-point.h" 2 # 30 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/fixed-point.h" extern implementation impl; typedef int64_t fxp_t; fxp_t _fxp_one; fxp_t _fxp_half; fxp_t _fxp_minus_one; fxp_t _fxp_min; fxp_t _fxp_max; double _dbl_max; double _dbl_min; fxp_t _fxp_fmask; fxp_t _fxp_imask; static const double scale_factor[31] = { 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0, 4096.0, 8192.0, 16384.0, 32768.0, 65536.0, 131072.0, 262144.0, 524288.0, 1048576.0, 2097152.0, 4194304.0, 8388608.0, 16777216.0, 33554432.0, 67108864.0, 134217728.0, 268435456.0, 536870912.0, 1073741824.0 }; static const double scale_factor_inv[31] = { 1.0, 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625, 0.001953125, 0.0009765625, 0.00048828125, 0.000244140625, 0.0001220703125, 0.00006103515625, 0.000030517578125, 0.000015258789063, 0.000007629394531, 0.000003814697266, 0.000001907348633, 0.000000953674316, 0.000000476837158, 0.000000238418579, 0.000000119209290, 0.000000059604645, 0.000000029802322, 0.000000014901161, 0.000000007450581, 0.000000003725290, 0.000000001862645, 0.000000000931323 }; static const float rand_uni[10000] = { -0.486240329978498f, -0.0886462298529236f, -0.140307596103306f, 0.301096597450952f, 0.0993171079928659f, 0.971751769763271f, 0.985173975730828f, 0.555993645184930f, 0.582088652691427f, -0.153377496651175f, 0.383610009058905f, -0.335724126391271f, 0.978768141636516f, -0.276250018648572f, 0.390075705739569f, -0.179022404038782f, 0.690083827115783f, -0.872530132490992f, -0.970585763293203f, -0.581476053441704f, -0.532614615674888f, -0.239699306693312f, -0.678183014035494f, 0.349502640932782f, -0.210469890686263f, 0.841262085391842f, -0.473585465151401f, 0.659383565443701f, -0.651160036945754f, -0.961043527561335f, -0.0814927639199137f, 0.621303110569702f, -0.784529166943541f, 0.0238464770757800f, 0.392694728594110f, 0.776848735202001f, 0.0870059709310509f, 0.880563655271790f, 0.883457036977564f, -0.249235082877382f, -0.691040749216870f, 0.578731120064320f, -0.973932858000832f, -0.117699105431720f, -0.723831748151088f, -0.483149657477524f, -0.821277691383664f, -0.459725618100875f, 0.148175952221864f, 0.444306875534854f, -0.325610376336498f, 0.544142311404910f, -0.165319440455435f, 0.136706800705517f, 0.543312481350682f, 0.467210959764607f, -0.349266618228534f, -0.660110730565862f, 0.910332331495431f, 0.961049802789367f, -0.786168905164629f, 0.305648402726554f, 0.510815258508885f, 0.0950733260984060f, 0.173750645487898f, 0.144488668408672f, 0.0190031984466126f, -0.299194577636724f, 0.302411647442273f, -0.730462524226212f, 0.688646006554796f, 0.134948379722118f, 0.533716723458894f, -0.00226300779660438f, -0.561340777806718f, 0.450396313744017f, -0.569445876566955f, 0.954155246557698f, -0.255403882430676f, -0.759820984120828f, -0.855279790307514f, -0.147352581758156f, -0.302269055643746f, -0.642038024364086f, -0.367405981107491f, 0.491844011712164f, -0.542191710121194f, -0.938294043323732f, 0.683979894338020f, 0.294728290855287f, 0.00662691839443919f, -0.931040350582855f, 0.152356209974418f, 0.678620860551457f, -0.534989269238408f, 0.932096367913226f, -0.0361062818028513f, -0.847189697149530f, -0.975903030160255f, 0.623293205784014f, -0.661289688031659f, 0.724486055119603f, 0.307504095172835f, 0.00739266163731767f, -0.393681596442097f, 0.0313739422974388f, 0.0768157689673350f, -0.652063346886817f, 0.864188030044388f, -0.588932092781034f, 0.496015896758580f, -0.872858269231211f, 0.978780599551039f, -0.504887732991147f, -0.462378791937628f, 0.0141726829338038f, 0.769610007653591f, 0.945233033188923f, -0.782235375325016f, -0.832206533738799f, 0.745634368088673f, -0.696969510157151f, -0.0674631869948374f, -0.123186450806584f, -0.359158959141949f, -0.393882649464391f, 0.441371446689899f, -0.829394270569736f, -0.301502651277431f, -0.996215501187289f, 0.934634037393066f, -0.282431114746289f, -0.927550795619590f, -0.437037530043415f, -0.360426812995980f, 0.949549724575862f, 0.502784616197919f, 0.800771681422909f, -0.511398929004089f, 0.309288504642554f, -0.207261227890933f, 0.930587995125773f, -0.777029876696670f, -0.489329175755640f, -0.134595132329858f, 0.285771358983518f, 0.182331373854387f, -0.544110494560697f, 0.278439882883985f, -0.556325158102182f, 0.579043806545889f, 0.134648133801916f, 0.602850725479294f, -0.151663563868883f, 0.180694361855878f, -0.651591295315595f, 0.281129147768056f, -0.580047306475484f, 0.687883075491433f, 0.279398670804288f, -0.853428128249503f, -0.532609367372680f, -0.821156786377917f, -0.181273229058573f, -0.983898569846882f, -0.0964374318311501f, 0.880923372124250f, 0.102643371392389f, 0.893615387135596f, -0.259276649383649f, 0.699287743639363f, 0.402940604635828f, -0.110721596226581f, 0.0846246472582877f, 0.820733021865405f, 0.795578903285308f, -0.495144122011537f, 0.273150029257472f, -0.268249949701437f, 0.231982193341980f, 0.694211299124074f, 0.859950868718233f, 0.959483382623794f, -0.422972626833543f, -0.109621798738360f, 0.433094703426531f, 0.694025903378851f, 0.374478987547435f, -0.293668545105608f, -0.396213864190828f, -0.0632095887099047f, -0.0285139536748673f, 0.831794132192390f, -0.548543088139238f, 0.791869201724680f, 0.325211484201845f, 0.155274810721772f, -0.112383643064821f, -0.674403070297721f, 0.642801068229810f, -0.615712048835242f, -0.322576771285566f, -0.409336818836595f, 0.548069973193770f, -0.386353709407947f, -0.0741664985357784f, 0.619639599324983f, -0.815703814931314f, 0.965550307223862f, 0.623407852683828f, -0.789634372832984f, 0.736750050047572f, -0.0269443926793700f, 0.00545706093721488f, -0.315712479832091f, -0.890110021644720f, -0.869390443173846f, -0.381538869981866f, -0.109498998005949f, 0.131433952330613f, -0.233452413139316f, 0.660289822785465f, 0.543381186340023f, -0.384712418750451f, -0.913477554164890f, 0.767102957655267f, -0.115129944521936f, -0.741161985822647f, -0.0604180020782450f, -0.819131535144059f, -0.409539679760029f, 0.574419252943637f, -0.0440704617157433f, 0.933173744590532f, 0.261360623390448f, -0.880290575543046f, 0.329806293425492f, 0.548915621667952f, 0.635187167795234f, -0.611034070318967f, 0.458196727901944f, 0.397377226781023f, 0.711941361933987f, 0.782147744383368f, -0.00300685339552631f, 0.384687233450957f, 0.810102466029521f, 0.452919847968424f, -0.183164257016897f, -0.755603185485427f, -0.604334477365858f, -0.786222413488860f, -0.434887500763099f, -0.678845635625581f, -0.381200370488331f, -0.582350534916068f, -0.0444427346996734f, 0.116237247526397f, -0.364680921206275f, -0.829395404347498f, -0.258574590032613f, -0.910082114298859f, 0.501356900925997f, 0.0295361922006900f, -0.471786618165219f, 0.536352925101547f, -0.316120662284464f, -0.168902841718737f, 0.970850119987976f, -0.813818666854395f, -0.0861183123848732f, 0.866784827877161f, 0.535966478165739f, -0.806958669103425f, -0.627307415616045f, -0.686618354673079f, 0.0239165685193152f, 0.525427699287402f, 0.834079334357391f, -0.527333932295852f, 0.130970034225907f, -0.790218350377199f, 0.399338640441987f, 0.133591886379939f, -0.181354311053254f, 0.420121912637914f, -0.625002202728601f, -0.293296669160307f, 0.0113819513424340f, -0.882382002895096f, -0.883750159690028f, 0.441583656876336f, -0.439054135454480f, 0.873049498123622f, 0.660844523562817f, 0.0104240153103699f, 0.611420248331623f, -0.235926309432748f, 0.207317724918460f, 0.884691834560657f, 0.128302402592277f, -0.283754448219060f, 0.237649901255856f, 0.610200763264703f, -0.625035441247926f, -0.964609592118695f, -0.323146562743113f, 0.961529402270719f, -0.793576233735450f, -0.843916713821003f, 0.314105102728384f, -0.204535560653294f, 0.753318789613803f, 0.160678386635821f, -0.647065919861379f, -0.202789866826280f, 0.648108234268198f, -0.261292621025902f, 0.156681828732770f, 0.405377351820066f, 0.228465381497500f, 0.972348516671163f, 0.288346037401522f, -0.0799068604307178f, 0.916939290109587f, -0.279220972402209f, -0.203447523864279f, -0.533640046855273f, 0.543561961674653f, 0.880711097286889f, -0.549683064687774f, 0.0130107219236368f, -0.554838164576024f, -0.379442406201385f, -0.00500104610043062f, 0.409530122826868f, -0.580423080726061f, 0.824555731914455f, -0.254134502966922f, 0.655609706875230f, 0.629093866184236f, -0.690033250889974f, -0.652346551677826f, 0.169820593515952f, 0.922459552232043f, 0.351812083539940f, 0.876342426613034f, -0.513486005850680f, -0.626382302780497f, -0.734690688861027f, 0.245594886018314f, -0.875740935105191f, -0.388580462918006f, 0.0127041754106421f, -0.0330962560066819f, -0.425003146474193f, 0.0281641353527495f, 0.261441358666622f, 0.949781327102773f, 0.919646340564270f, 0.504503377003781f, 0.0817071051871894f, 0.319968570729658f, 0.229065413577318f, -0.0512608414259468f, -0.0740848540944785f, -0.0974457038582892f, 0.532775710298005f, -0.492913317622840f, 0.492871078783642f, -0.289562388384881f, 0.229149968879593f, 0.697586903105899f, 0.900855243684925f, 0.969700445892771f, -0.618162745501349f, -0.533241431614228f, -0.937955908995453f, 0.886669636523452f, 0.498748076602594f, 0.974106016180519f, -0.199411214757595f, 0.725270392729083f, -0.0279932700005097f, -0.889385821767448f, -0.452211028905500f, -0.487216271217731f, -0.577105004471439f, 0.777405674160298f, 0.390121144627092f, -0.595062864225581f, -0.844712795815575f, -0.894819796738658f, 0.0556635002662202f, 0.200767245646242f, 0.481227096067452f, -0.0854169009474664f, 0.524532943920022f, -0.880292014538901f, -0.127923833629789f, -0.929275628802356f, 0.233276357260949f, -0.776272194935070f, 0.953325886548014f, -0.884399921036004f, -0.504227548828417f, -0.546526107689276f, 0.852622421886067f, 0.947722695551154f, -0.668635552599119f, 0.768739709906834f, 0.830755876586102f, -0.720579994994166f, 0.761613532216491f, 0.340510345777526f, 0.335046764810816f, 0.490102926886310f, -0.568989013749608f, -0.296018470377601f, 0.979838924243657f, 0.624231653632879f, 0.553904401851075f, -0.355359451941014f, 0.267623165480721f, 0.985914275634075f, -0.741887849211797f, 0.560479100333108f, -0.602590162007993f, -0.874870765077352f, -0.0306218773384892f, 0.963145768131215f, 0.544824028787036f, -0.133990816021791f, 0.0679964588712787f, -0.156401335214901f, -0.0802554171832672f, 0.856386218492912f, 0.143013580527942f, 0.403921859374840f, -0.179029058044097f, 0.770723540077919f, -0.183650969350452f, -0.340718434629824f, 0.217166124261387f, -0.171159949445977f, 0.127493767348173f, -0.649649349141405f, -0.0986978180993434f, 0.301786606637125f, 0.942172200207855f, 0.0323236270151113f, -0.579853744301016f, -0.964413060851558f, 0.917535782777861f, 0.442144649483292f, -0.684960854610878f, -0.418908715566712f, 0.617844265088789f, 0.897145578082386f, 0.235463167636481f, 0.0166312355859484f, 0.948331447443040f, -0.961085640409103f, -0.0386086809179784f, -0.949138997977665f, 0.738211385880427f, 0.613757309091864f, -0.606937832993426f, 0.825253298062192f, 0.932609757667859f, -0.169023247637751f, -0.411237965787391f, 0.550590803600950f, -0.0561729280137304f, -0.559663108323671f, -0.718592671237337f, 0.885889621415361f, -0.364207826334344f, -0.839614660327507f, 0.265502694339344f, 0.394329270534417f, -0.270184577808578f, -0.865353487778069f, -0.528848754655393f, -0.179961524561963f, 0.571721065613544f, -0.774363220756696f, 0.251123315200792f, -0.217722762975159f, 0.0901359910328954f, -0.329445470667965f, 0.366410356722994f, -0.777512662632715f, 0.654844363477267f, -0.882409911562713f, -0.613612530795153f, -0.926517759636550f, 0.111572665207194f, 0.0729846382226607f, 0.789912813274098, 0.784452109264882f, -0.949766989295825f, 0.318378232675431f, 0.732077593075111f, 0.786829143208386f, -0.134682559823644f, 0.733164743374965f, 0.978410877665941f, 0.992008491438409f, -0.319064303035495f, 0.958430683602029f, 0.514518212363212f, 0.101876224417090f, 0.642655735778237f, -0.170746516901312f, 0.252352078365623f, -0.761327278132210f, 0.724119717129199f, 0.889374997869224f, -0.785987369200692f, -0.594670344572584f, 0.805192297495935f, -0.990523259595814f, 0.483998949026664f, 0.747350619254878f, -0.824845161088780f, 0.543009506581798f, -0.208778528683094f, -0.314149951901368f, 0.943576771177672f, -0.102633559170861f, -0.947663019606703f, -0.557033071578968f, 0.419150797499848f, 0.251214274356296f, 0.565717763755325f, 0.126676667925064f, -0.0213369479214840f, 0.342212953426240f, -0.288015274572288f, 0.121313363277304f, 0.452832374494206f, 0.545420403121955f, -0.616024063400938f, -0.0320352392995826f, -0.400581850938279f, 0.0642433474653812f, -0.673966224453150f, 0.951962939602010f, -0.241906012952983f, 0.0322060960995099f, -0.449185553826233f, -0.709575766146540f, 0.0283340814242898f, 0.234237103593580f, -0.285526615094797f, -0.793192668153991f, -0.437130485497140f, -0.956132143306919f, 0.601158367473616f, 0.238689691528783f, 0.173709925321432f, 0.437983847738997f, 0.397380645202102f, 0.432093344086237f, -0.0338869881121104f, -0.966303269542493f, 0.875351570183604f, -0.0584554089652962f, 0.294207497692552f, 0.200323088145182f, 0.826642387259759f, 0.284806025494260f, -0.00660991970522007f, 0.682493772727303f, -0.151980775670668f, 0.0470705546940635f, -0.236378427235531f, -0.844780853112247f, 0.134166207564174f, -0.586842667384924f, 0.0711866699414370f, 0.311698821368897f, -0.361229767252053f, 0.750924311039976f, 0.0764323989785694f, 0.898463708247144f, 0.398232179543916f, -0.515644913011399f, -0.189067061520362f, -0.567430593060929f, -0.641924269747436f, -0.0960378699625619f, -0.792054031692334f, 0.803891878854351f, -0.233518627249889f, -0.892523453249154f, 0.707550017996875f, -0.782288435525895f, -0.156166443894764f, -0.543737876329167f, 0.565637809380957f, -0.757689989749326f, -0.612543942167974f, -0.766327195073259f, 0.587626843767440f, -0.280769385897397f, -0.457487372245825f, 0.0862799426622438f, -0.616867284053547f, 0.121778903484808f, -0.451988651573766f, -0.618146087265495f, -0.285868777534354f, 0.108999472244014f, -0.620755183347358f, -0.268563184810196f, -0.721678169615489f, -0.146060198874409f, -0.661506858070617f, 0.901707853998409f, 0.222488776533930f, 0.679599685031679f, 0.974760448601209f, 0.535485953830496f, -0.562345697123585f, 0.369219363331071f, -0.0282801684694869f, -0.0734880727832297f, 0.733216287314358f, -0.514352095765627f, -0.850813063545195f, 0.642458447327163f, 0.118661521915783f, -0.907015526838341f, 0.789277766886329f, -0.719864125961721f, 0.274329068829509f, 0.830124687647056f, 0.719352367261587f, -0.821767317737384f, -0.840153496829227f, 0.650796781936517f, 0.381065387870166f, 0.341870564586224f, -0.00174423702285131f, -0.216348832349188f, 0.678010477635713f, -0.748695103596683f, -0.819659325555269f, 0.620922373008647f, 0.471659250504894f, 0.417848292160984f, -0.990577315445198f, -0.509842007818877f, 0.705761459091187f, 0.723072116074702f, -0.606476484252158f, -0.871593699865195f, -0.662059658667501f, -0.207267692377271f, -0.274706370444270f, 0.317047325063391f, 0.329780707114887f, -0.966325651181920f, -0.666131009799803f, 0.118609206658210f, 0.232960448350140f, -0.139134616436389f, -0.936412642687343f, -0.554985387484625f, -0.609914445911143f, -0.371023087262482f, -0.461044793696911f, 0.0277553171809701f, -0.241589304772568f, -0.990769995548029f, 0.114245771600061f, -0.924483328431436f, 0.237901450206836f, -0.615461633242452f, 0.201497106528945f, -0.599898812620374f, 0.982389910778332f, 0.125701388874024f, -0.892749115498369f, 0.513592673006880f, 0.229316745749793f, 0.422997355912517f, 0.150920221978738f, 0.447743452078441f, 0.366767059168664f, -0.605741985891581f, 0.274905013892524f, -0.861378867171578f, -0.731508622159258f, 0.171187057183023f, 0.250833501952177f, -0.609814068526718f, -0.639397597618127f, -0.712497631420166f, -0.539831932321101f, -0.962361328901384f, 0.799060001548069f, 0.618582550608426f, -0.603865594092701f, -0.750840334759883f, -0.432368099184739f, -0.581021252111797f, 0.134711953024238f, 0.331863889421602f, -0.172907726656169f, -0.435358718118896f, -0.689326993725649f, 0.415840315809038f, -0.333576262820904f, 0.279343777676723f, -0.0393098862927832f, 0.00852090010085194f, -0.853705195692250f, 0.526006696633762f, -0.478653377052437f, -0.584840261391485f, 0.679261003071696f, 0.0367484618219474f, -0.616340335633997f, -0.912843423145420f, -0.221248732289686f, -0.477921890680232f, -0.127369625511666f, 0.865190146410824f, 0.817916456258544f, 0.445973590438029f, -0.621435280140991f, -0.584264056171687f, 0.718712277931876f, -0.337835985469843f, 0.00569064504159345f, -0.546546294846311f, 0.101653624648361f, -0.795498735829364f, -0.249043531299132f, -0.112839395737321f, -0.350305425122331f, -0.910866368205041f, 0.345503177966105f, -0.549306515692918f, 0.711774722622726f, 0.283368922297518f, 0.0401988801224620f, 0.269228967910704f, 0.408165826013612f, -0.306571373865680f, 0.937429053394878f, 0.992154362395068f, 0.679431847774404f, 0.660561953302554f, 0.903254489326130f, -0.939312119455540f, -0.211194531611303f, 0.401554296146757f, -0.0373187111351370f, -0.209143098987164f, -0.483955198209448f, -0.860858509666882f, 0.847006442151417f, 0.287950263267018f, 0.408253171937961f, -0.720812569529331f, 0.623305171273525f, 0.543495760078790f, -0.364025150023839f, -0.893335585394842f, -0.757545415624741f, -0.525417020183382f, -0.985814550271000f, -0.571551008375522f, 0.930716377819686f, -0.272863385293023f, 0.982334910750391f, 0.297868844366342f, 0.922428080219044f, 0.917194773824871f, 0.846964493212884f, 0.0641834146212110f, 0.279768184306094f, 0.591959126556958f, 0.355630573995206f, 0.839818707895839f, 0.219674727597944f, -0.174518904670883f, 0.708669864813752f, -0.224562931791369f, 0.677232454840133f, -0.904826802486527f, -0.627559033402838f, 0.263680517444611f, 0.121902314059156f, -0.704881790282995f, 0.242825089229032f, -0.309373554231866f, -0.479824461459095f, -0.720536286348018f, -0.460418173937526f, 0.774174710513849f, 0.452001499049874f, -0.316992092650694f, 0.153064869645527f, -0.209558599627989f, 0.685508351648252f, -0.508615450383790f, 0.598109567185095f, 0.391177475074196f, 0.964444988755186f, 0.336277292954506f, -0.0367817159101076f, -0.668752640081528f, 0.169621732437504f, -0.440925495294537f, 0.352359477392856f, 0.300517139597811f, 0.464188724292127f, 0.342732840629593f, -0.772028689116952f, 0.523987886508557f, 0.920723209445309f, 0.325634245623597f, 0.999728757965472f, -0.108202444213629f, -0.703463061246440f, -0.764321104361266f, 0.153478091277821f, 0.400776808520781f, 0.0362608595686520f, 0.602660289034871f, -0.00396673312072204f, 0.296881393918662f, 0.563978362789779f, 0.849699999703012f, 0.699481370949461f, -0.517318771826836f, 0.488696839410786f, -0.863267084031406f, 0.0353144039838211f, 0.346060763700543f, 0.964270355001567f, 0.354899825242107f, 0.806313705199543f, 0.675286452110240f, 0.0873918818789949f, -0.595319879813140f, 0.768247284622921f, 0.424433552458434f, -0.308023836359512f, 0.802163480612923f, -0.348151008192881f, -0.889061130591849f, -0.593277042719599f, -0.669426232128590f, 0.758542808803890f, 0.515943031751579f, -0.359688459650311f, 0.568175936707751f, 0.741304023515212f, 0.260283681057109f, 0.957668849401749f, -0.665096753421305f, 0.769229664798946f, -0.0871019488695104f, -0.362662093346394f, -0.411439775739547f, 0.700347493632751f, 0.593221225653487f, 0.712841887456470f, 0.413663813878195f, -0.868002281057698f, -0.704419248587642f, 0.497097875881516f, -0.00234623694758684f, 0.690202361192435f, -0.850266199595343f, 0.315244026446767f, 0.709124123964306f, 0.438047076925768f, 0.798239617424585f, 0.330853072912708f, 0.581059745965701f, 0.449755612947191f, -0.462738032798907f, 0.607731925865227f, 0.0898348455002427f, -0.762827831849901f, 0.895598896497952f, -0.752254194382105f, -0.0916186048978613f, -0.906243795607547f, 0.229263971313788f, 0.401148319671400f, -0.699999035942240f, 0.949897297168705f, 0.442965954562621f, -0.836602533575693f, 0.960460356865877f, -0.588638958628591f, -0.826876652501322f, 0.358883606332526f, 0.963216314331105f, -0.932992215875777f, -0.790078242370583f, 0.402080896170037f, -0.0768348888017805f, 0.728030138891631f, -0.259252300581205f, -0.239039520569651f, -0.0343187629251645f, -0.500656851699075f, 0.213230170834557f, -0.806162554023268f, -0.346741158269134f, 0.593197383681288f, -0.874207905790597f, 0.396896283395687f, -0.899758892162590f, 0.645625478431829f, 0.724064646901595f, 0.505831437483414f, -0.592809028527107f, 0.191058921738261f, 0.329699861086760f, 0.637747614705911f, 0.228492417185859f, 0.350565075483143f, 0.495645634191973f, 0.0378873636406241f, -0.558682871042752f, -0.0463515226573312f, -0.699882077624744f, -0.727701564368345f, -0.185876979038391f, 0.969357227041006f, -0.0396554302826258f, 0.994123321254905f, -0.103700411263859f, -0.122414150286554f, -0.952967253268750f, -0.310113557790019f, 0.389885130024049f, 0.698109781822753f, -0.566884614177461f, -0.807731715569885f, 0.295459359747620f, 0.353911434620388f, -0.0365360121873806f, -0.433710246410727f, -0.112374658849445f, -0.710362620548396f, -0.750188568899340f, -0.421921409270312f, -0.0946825033112555f, -0.207114343395422f, -0.712346704375406f, -0.762905208265238f, 0.668705185793373f, 0.874811836887758f, 0.734155331047614f, 0.0717699959166771f, -0.649642655211151f, 0.710177200600726f, -0.790892796708330f, -0.609051316139055f, 0.158155751049403f, 0.273837117392194f, 0.101461674737037f, -0.341978434311156f, 0.358741707078855f, 0.415990974906378f, 0.760270133083538f, 0.164383469371383f, 0.559847879549422f, 0.209104118141764f, -0.265721227148806f, 0.165407943936551f, 0.611035396421350f, -0.626230501208063f, -0.116714293310250f, -0.696697517286888f, 0.0545261414014888f, 0.440139257477096f, 0.202311640602444f, -0.369311356303593f, 0.901884565342531f, 0.256026357399272f, -0.673699547202088f, 0.108550667621349f, -0.961092940829968f, -0.254802826645023f, 0.553897912330318f, 0.110751075533042f, -0.587445414043347f, 0.786722059164009, 0.182042556749386f, 0.398835909383655f, 0.431324012457533f, 0.587021142157922f, -0.644072183989352f, 0.187430090296218f, 0.516741122998546f, -0.275250933267487f, -0.933673413249875f, -0.767709448823879f, 0.00345814033609182f, -0.585884382069128f, 0.463549040471035f, 0.666537178805293f, -0.393605927315148f, -0.260156573858491f, -0.298799291489529f, -0.246398415746503f, 0.970774181159203f, -0.485708631308223f, -0.456571313115555f, -0.264210030877189f, -0.442583504871362f, 0.0585567697312368f, 0.955769232723545f, 0.651822742221258f, 0.667605490119116f, -0.178564750516287f, 0.744464599638885f, -0.0962758978504710f, -0.538627454923738f, -0.844634654117462f, 0.109151162611125f, -0.862255427201396f, -0.478955305843323f, 0.645965860697344f, 0.345569271369828f, 0.930605011671297f, -0.195523686135506f, 0.927940875293964f, 0.0529927450986318f, -0.537243314646225f, 0.0815400161801159f, -0.528889663721737f, -0.0803965087898244f, 0.722188412643543f, -0.115173100460772f, 0.391581967064874f, 0.609102624309301f, -0.726409099849031f, -0.924071529212721f, -0.424370859730340f, -0.932399086010354f, -0.679903916227243f, 0.398593637781810f, -0.395942610474455f, 0.911017267923838f, 0.830660098751580f, 0.485689056693942f, -0.634874052918746f, 0.558342102044082f, 0.153345477027740f, -0.418797532948752f, -0.962412446404476f, 0.499334884055701f, 0.772755578982235f, 0.486905718186221f, -0.680415982465391f, -0.983589696155766f, 0.0802707365440833f, -0.108186099494932f, 0.272227706025405f, 0.651170828846750f, -0.804713753056757f, 0.778076504684911f, 0.869094633196957f, -0.213764089899489f, -0.289485853647921f, -0.248376169846176f, -0.273907386272412f, -0.272735585352615f, -0.851779302143109f, 0.777935500545070f, 0.610526499062369f, -0.825926925832998f, -0.00122853287679647f, -0.250920102747366f, -0.0333860483260329f, 0.562878228390427f, 0.685359102189134f, 0.909722844787783f, -0.686791591637469f, 0.700018932525581f, -0.975597558640926f, 0.111273045778084f, 0.0313167229308478f, -0.185767397251192f, -0.587922465203314f, -0.569364866257444f, -0.433710470415537f, 0.744709870476354f, 0.812284989338678f, -0.835936210940005f, 0.409175739115410f, 0.364745324015946f, -0.526496413512530f, -0.0949041293633228f, -0.710914623019602f, -0.199035360261516f, 0.249903358254580f, 0.799197892184193f, -0.974131439735146f, -0.962913228246770f, -0.0584067290846062f, 0.0678080882131218f, 0.619989552612058f, 0.600692636138022f, -0.325324145536173f, 0.00758797937831957f, -0.133193608214778f, -0.312408219890363f, -0.0752971209304969f, 0.764751638735404f, 0.207290375565515f, -0.965680055629168f, 0.526346325957267f, 0.365879948128040f, -0.899713698342006f, 0.300806506284083f, 0.282047017067903f, -0.464418831301796f, -0.793644005532544f, -0.338781149582286f, 0.627059412508279f, -0.624056896643864f, -0.503708045945915f, 0.339203903916317f, -0.920899287490514f, -0.753331218450680f, -0.561190137775443f, 0.216431106588929f, -0.191601189620092f, 0.613179188721972f, 0.121381145781083f, -0.477139741951367f, 0.606347924649253f, 0.972409497819530f, 0.00419185232258634f, 0.786976564006247f, 0.716984027373809f, -0.577296880358192f, 0.336508364109364f, -0.837637061538727f, -0.706860533591818f, 0.655351330285695f, -0.799458036429467f, 0.804951754011505f, 0.405471126911303f, 0.485125485165526f, 0.0354103156047567f, 0.774748847269929f, 0.396581375869036f, 0.420464745452802f, -0.544531741676535f, -0.779088258182329f, -0.129534599431145f, 0.228882319223921f, 0.669504936432777f, -0.158954596495398f, -0.171927546721685f, 0.675107968066445f, -0.201470217862098f, -0.185894687796509f, 0.244174688826684f, 0.310288210346694f, -0.0674603586289346f, 0.138103839181198f, 0.269292861340219f, 0.121469813317732f, 0.168629748875041f, 0.581112629873687f, 0.499508530746584f, -0.741772433024897f, -0.311060071316150f, -0.263697352439521f, 0.180487383518774f, -0.800786488742242f, -0.949903966987338f, 0.134975524166410f, 0.213364683193138f, -0.684441197699222f, -0.254697287796379f, -0.260521050814253f, -0.757605554637199f, -0.134324873215927f, -0.699675596579060f, 0.136000646890289f, 0.355272520354523f, -0.712620797948690f, -0.729995036352282f, 0.323100037780915f, -0.718364487938777f, 0.807709622188084f, 0.289336059472722f, -0.558738026311145f, -0.591811756545896f, -0.894952978489225f, -0.354996929975694f, -0.142213103464027f, -0.651950180085633f, 0.182694586161578f, -0.193492058009904f, -0.540079537334588f, -0.300927433533712f, 0.119585035086049f, 0.895807833710939f, -0.413843745301811f, -0.209041322713332f, 0.808094803654324f, 0.0792829008489782f, 0.314806980452270f, 0.502591873175427f, -0.0474189387090473f, -0.407131047818007f, 0.797117088440354f, 0.902395237588928f, -0.783327055804990f, -0.591709085168646f, 0.628191184754911f, -0.454649879692076f, -0.588819444306752f, 0.250889716959370f, -0.582306627010669f, -0.145495766591841f, -0.634137346823528f, 0.667934845545285f, 0.873756470938530f, 0.425969845715827f, -0.779543910541245f, -0.265210219994391f, 0.781530681845886f, 0.304461599274577f, 0.211087853085430f, 0.281022407596766f, 0.0701313665097776f, 0.342337400087349f, -0.0618264046031387f, 0.177147380816613f, 0.751693209867024f, -0.279073264607508f, 0.740459307255654f, -0.352163564204507f, -0.726238685136937f, -0.565819729501492f, -0.779416133306559f, -0.783925450697670f, 0.542612245021260f, -0.810510148278478f, -0.693707081804938f, 0.918862988543900f, -0.368717045271828f, 0.0654919784331340f, -0.438514219239944f, -0.923935138084824f, 0.913316783811291f, -0.961646539574340f, 0.734888382653474f, -0.464102713631586f, -0.896154678819649f, 0.349856565392685f, 0.646610836502422f, -0.104378701809970f, 0.347319102015858f, -0.263947819351090f, 0.343722186197186f, 0.825747554146473f, 0.0661865525544676f, 0.918864908112419f, -0.999160312662909f, -0.904953244747070f, 0.246613032125664f, 0.123426960800262f, -0.294364203503845f, -0.150056966431615f, 0.904179479721301f, 0.517721252782648f, 0.661473373608678f, -0.784276966825964f, -0.984631287069650f, 0.239695484607744f, -0.499150590123099f, 0.00153518224500027f, -0.817955534401114f, 0.221240310713583f, 0.114442325207070f, -0.717650856748245f, -0.722902799253535f, -0.962998380704103f, 0.214092155997873f, -0.226370691123970f, 0.536806140446569f, 0.111745807092858f, 0.657580594136395f, -0.239950592200226f, 0.0981270621736083f, -0.173398466414235f, 0.414811672195735f, 0.147604904291238f, -0.649219724907210f, 0.907797399703411f, -0.496097071857490f, -0.0958082520749422f, -0.700618145301611f, 0.238049932994406f, 0.946616020659334f, 0.143538494511824f, 0.0641076718667677f, 0.377873848622552f, -0.413854028741624f, -0.838831021130186f, 0.0208044297354626f, 0.476712667979210f, 0.850908020233298f, 0.0692454021020814f, 0.841788714865238f, -0.251777041865926f, 0.512215668857165f, 0.827988589806208f, -0.399200428030715f, 0.999219950547600f, -0.00465542086542259f, 0.279790771964531f, -0.683125623289052f, 0.988128867315143f, 0.00697090775456410f, -0.409501680375786f, -0.190812202162744f, -0.154565639467601f, 0.305734586628079f, -0.922825484202279f, -0.0622811516391562f, -0.502492855870975f, 0.358550513844403f, 0.678271216185703f, -0.940222215291861f, 0.568581934651071f, 0.953835466578938f, -0.476569789986603f, 0.0141049472573418f, 0.722262461730185f, -0.128913572076972f, -0.583948340870808f, -0.254358587904773f, -0.390569309413304f, -0.0495119137883056f, -0.486356443935695f, -0.112768011009410f, -0.608763417511343f, -0.145843822867367f, 0.767829603838659f, 0.791239479733126f, 0.0208376062066382f, -0.524291005204912f, -0.200159553848628f, -0.835647719235620f, -0.222774380961612f, 0.0617292533934060f, 0.233433696650208f, -0.543969878951657f, -0.628168009147650f, -0.725602523060817f, -0.273904472034828f, 0.320527317085229f, -0.556961185821848f, 0.261533413201255f, 0.696617398495973f, 0.200506775746016f, -0.395581923906907f, 0.0196423782530712f, -0.0552577396777472f, -0.594078139517501f, -0.816132673139052f, -0.898431571909616f, 0.879105843430143f, 0.949666380003024f, -0.245578843355682f, 0.528960018663897f, 0.201586039072583f, -0.651684706542954f, 0.596063456431086f, -0.659712784781056f, -0.213702651629353f, -0.629790163054887f, -0.0572029778771013f, 0.645291034768991f, -0.453266855343461f, -0.581253959024410f, 0.632682730071992f, 0.991406037765467f, 0.701390336150136f, -0.879037255220971f, -0.304180069776406f, 0.0969095808767941f, -0.465682778651712f, 0.815108046274786f, -0.532850846043973f, 0.950550134670033f, 0.296008118726089f, -0.198390447541329f, 0.159049143352201f, 0.105169964332594f, -0.482506131358523f, 0.493753482281684f, 0.292058685647414f, 0.283730532860951f, 0.00323819209092657f, 0.765838273699203f, -0.0753176377562099f, -0.679824808630431f, 0.548180003463159f, -0.996048798712591f, 0.782768288046545f, 0.396509190560532f, 0.848686742379558f, 0.750049741585178f, 0.730186188655936f, -0.0220701180542726f, -0.487618042364281f, -0.403562199756249f, -0.0693129490117646f, 0.947019452953246f, -0.731947366410442f, 0.198175872470120f, -0.329413252854837f, -0.641319161749268f, 0.186271826190842f, -0.0739989831663739f, -0.334046268448298f, -0.191676071751509f, -0.632573515889708f, -0.999115061914042f, -0.677989795015932f, 0.289828136337821f, 0.696081747094487f, 0.965765319961706f, -0.203649463803737f, -0.195384468978610f, 0.746979659338745f, 0.701651229142588f, -0.498361303522421f, 0.289120104962302f, 0.270493509228559f, -0.132329670835432f, 0.385545665843914f, -0.265371843427444f, 0.306155119003788f, -0.859790373316264f, -0.0198057838521546f, 0.233572324299025f, 0.426354273793125f, -0.510901479579029f, -0.600001464460011f, -0.972316846268671f, 0.531678082677910f, -0.0543913028234813f, -0.860333915321655f, 0.0717414549918496f, -0.992726205437930f, 0.587189647572868f, -0.710120198811545f, -0.712433353767817f, 0.000905613890617163f, 0.323638959833707f, -0.148002344942812f, 0.422217478090035f, -0.512122539396176f, -0.652032513920892f, -0.0749826795945674f, 0.689725543651565f, 0.00708142459169103f, 0.612282380092436f, -0.182868915402510f, -0.478704046524703f, 0.630078231167476f, -0.201694106935605f, 0.471080354222778f, 0.705764111397718f, 0.504296612895499f, -0.245442802115836f, -0.0255433216413170f, 0.244606720514349f, -0.620852691611321f, 0.130333792055452f, -0.0404066268217753f, 0.533698497858480f, 0.569324696850915f, -0.0208385747745345f, -0.344454279574176f, 0.697793551353488f, 0.223740789443046, 0.0819835387259940f, -0.378565059057637f, 0.265230570199009f, -0.654654047270763f, -0.959845479426107f, -0.524706200047066f, -0.320773238900823f, 0.133125806793072f, 0.204919719422386f, 0.781296208272529f, 0.357447172843949f, -0.295741363322007f, -0.531151992759176f, -0.928760461863525f, -0.492737999698919f, 0.185299312597934f, 0.0308933157463984f, 0.0940868629278078f, -0.223134180713975f, -0.728994909644464f, 0.748645378716214f, 0.602424843862873f, 0.939628558971957f, -0.601577015562304f, -0.178714119359324f, 0.812720866753088f, -0.864296642561293f, 0.448439532249340f, 0.423570043689909f, 0.883922405988390f, -0.121889129001415f, -0.0435604321758833f, -0.823641147317994f, -0.775345608718704f, -0.621149628042832f, 0.532395431283659f, -0.803045105215129f, 0.897460124955135f, 0.432615281777583f, -0.0245386640589920f, -0.822321626075771f, -0.992080038736755f, -0.829220327319793f, 0.125841786813822f, 0.277412627470833f, 0.623989234604340f, -0.207977347981346f, -0.666564975567417f, 0.419758053880881f, -0.146809205344117f, 0.702495819380827f, 0.802212477505035f, 0.161529115911938f, 0.987832568197053f, -0.885776673164970f, -0.608518024629661f, -0.126430573784758f, 0.168260422890915f, -0.517060428948049f, -0.766296586196077f, -0.827624510690858f, -0.149091785188351f, -0.643782325842734f, 0.768634567718711f, 0.815278279059715f, -0.648037361329720f, -0.480742843535214f, 0.983809287193308f, -0.701958358623791f, 0.0797427982273327f, 0.903943825454071f, 0.980486658260621f, 0.207436790541324f, -0.536781321571165f, -0.885473392956838f, -0.626744905152131f, 0.279917970592554f, -0.489532633799085f, 0.402084958261836f, -0.566738134593205f, -0.0990017532286025f, 0.458891753618823f, 0.893734110503312f, 0.541822126435773f, -0.856210577956263f, -0.0354679151809227f, -0.868531503535520f, 0.150589222911699f, 0.611651396802303f, 0.524911319413221f, 0.555472734209632f, -0.723626819813614f, -0.162106613127807f, 0.602405197560299f, 0.903198408993777f, 0.329150411562290f, -0.806468536757339f, -0.671787125844359f, -0.707262852044556f, 0.474934689940169f, -0.379636706541612f, 0.404933387269815f, 0.332303761521238f, 0.394233678536033f, -0.0366067593524413f, 0.904405677123363f, -0.356597686978725f, -0.623034135107067f, 0.572040316921149f, 0.799160684670195f, -0.507817199545094f, -0.533380730448667f, -0.884507921224020f, -0.00424735629746076f, 0.647537115339283f, 0.456309536956504f, -0.766102127867730f, -0.625121831714406f, 0.341487890703535f, -0.360549668352997f, -0.229900108098778f, -0.666760418812903f, 0.813282715359911f, 0.115522674116703f, -0.221360306077384f, 0.0297293679340875f, 0.00682810040637105f, 0.0115235719886584f, 0.887989949086462f, 0.792212187398941f, 0.415172771519484f, -0.600202208047434f, 0.949356119962045f, -0.526700730890731f, 0.946712583567682f, -0.392771116330410f, 0.0144823046999243f, -0.649518061223406f, 0.724776068810104f, 0.00920735790862981f, -0.461670796134611f, 0.217703889787716f, 0.846151165623083f, -0.202702970245097f, 0.314177560430781f, -0.761102867343919f, 0.0528399640076420f, -0.986438508940994f, -0.595548022863232f, -0.430067198426456f, 0.150038004203120f, 0.738795383589380f, -0.605707072657181f, -0.597976219376529f, 0.375792542283657f, -0.321042914446039f, 0.902243988712398f, 0.463286578609220f, -0.739643422607773f, 0.210980536147575f, -0.539210294582617f, 0.405318056313257f, -0.876865698043818f, -0.0883135270940518f, 0.0300580586347285f, -0.657955040210154f, 0.159261648552234f, 0.288659459148804f, 0.274488527537659f, 0.646615145281349f, 0.431532024055095f, -0.982045186676854f, -0.777285361097106f, -0.124875006659614f, 0.503004910525253f, 0.824987340852061f, -0.859357943951028f, -0.894837450578304f, 0.744772864540654f, 0.415263521487854f, 0.337833126081168f, -0.612498979721313f, 0.391475686177086f, 0.573982630935632f, -0.391044576636065f, 0.669493459114130f, -0.763807443372196f, -0.898924075896803f, -0.969897663976237f, -0.266947396046322f, 0.198506503481333f, -0.355803387868922f, 0.787375525807664f, 0.655019979695179f, -0.266247398074148f, -0.665577607941915f, 0.0617617780742654f, -0.303207459096743f, 0.807119242186051f, -0.864431193732911f, 0.711808914065391f, 0.267969697417500f, -0.643939259651104f, -0.723685356192067f, 0.887757759160107f, -0.318420101532538f, -0.984559057628900f, -0.123118506428834f, 0.264872379685241f, 0.258477870902406f, -0.727462993670953f, -0.223845786938221f, 0.683462211502638f, -0.989811504909606f, 0.292644294487220f, -0.926087081411227f, -0.801377664261936f, -0.337757621052903f, 0.356167431525877f, 0.974619379699180f, 0.456124311183874f, 0.664192098344107f, -0.910993234571633f, -0.484097468631090f, -0.128534589958108f, -0.770879324529314f, 0.320053414246682f, 0.249818479771296f, 0.0153345543766990f, 0.696352481669035f, -0.397719804512483f, 0.670333638147646f, -0.678192291329959f, 0.190143924397131f, 0.342035884244954f, -0.350791038317704f, 0.0218450632953668f, 0.437133719806156f, 0.659960895652910f, 0.903378806323159f, 0.855089775229062f, 0.946706092624795f, 0.335540975081955f, 0.838337968455111f, -0.102693592034237f, -0.702102376052106f, 0.409624309223486f, -0.654483499569910f, 0.886576641430416f, -0.200573725141884f, -0.461284656727627f, 0.262661770963709f, 0.867505406245483f, -0.0688648080253220f, -0.707487995489326f, -0.248871627068848f, -0.197869870234198f, -0.243745607075197f, -0.244106806741608f, 0.489848112299788f, -0.0909708869175492f, -0.377678949786167f, 0.0385783576998284f, -0.470361956031595f, 0.802403491439449f, -0.408319987166305f, 0.345170991986463f, -0.433455880962420f, 0.00950587287655291f, -0.441888155900165f, -0.817874450719479f, 0.818308133775667f, 0.931915253798354f, 0.818494801634479f, 0.787941704188320f, 0.882012210451449f, 0.0749985961399193f, 0.259772455233352f, -0.655786948552735f, 0.0824323575519799f, 0.980211564632039f, -0.798619050684746f, 0.496019643929772f, -0.727312997781404f, -0.999839600489443f, 0.625938920414345f, -0.561059012154101f, 0.215650518505246f, 0.121571798563274f, 0.161863493108371f, -0.340322748036792f, 0.521792371708641f, 0.655248389359818f, -0.180967013066484f, 0.936797969156762f, 0.523749660366580f, 0.764744126333943f, 0.384701560810431f, -0.744092118301334f, 0.719721922905938f, 0.365931545158250f, -0.720202871171563f, 0.121662048491076f, -0.355501954289222f, 0.379420491208481f, -0.593818415223405f, -0.433690576121147f, -0.766763563509045f, -0.377445104709670f, -0.955638620720410f, 0.309622585052195f, -0.613767678153186f, 0.0177719922394908f, 0.362917537485277f, -0.297613292472489f, 0.0275561832152067f, -0.962345352767599f, 0.452866577068408f, -0.307485159523065f, 0.931778412136845f, 0.639592220588070f, 0.00782144244951311f, -0.0466407334447796f, -0.134392603781566f, 0.895314655361308f, -0.537785271016286f, 0.663926391064792f, -0.886126633268266f, -0.0975129470189278f, -0.429791706025144f, -0.440337831994928f, -0.00156267573188829f, 0.933113069253665f, -0.560704402651437f, -0.201658150324907f, 0.465819560354530f, 0.0701448781871696f, 0.859597672251104f, -0.525851890358272f, -0.992674038068357f, -0.0846761339576128f, -0.401686794568758f, -0.886069686075370f, -0.480254412625133f, 0.432758053902000f, 0.168651590377605f, -0.453397134906684f, 0.340250287733381f, -0.972972507965963f, 0.0560333167197302f, -0.180812774382952f, -0.689848943619717f, -0.427945332505659f, 0.771841237806370f, 0.329334772795521f, 0.573083591606505f, 0.280711890938316f, -0.265074342340277f, -0.166538165045598f, -0.0612128221482104f, 0.458392746490372f, 0.199475931235870f, 0.681819191997175f, 0.356837960840067f, 0.756968760265553f, 0.763288512531608f, -0.890082643508294f, -0.322752448111365f, 0.799445915816577f, -0.956403501496524f, 0.723055987751969f, 0.943900989848643f, -0.217092255585658f, -0.426893469064855f, 0.834596828462842f, 0.723793256883097f, 0.781491391875921f, 0.928040296363564f, -0.468095417622644f, 0.758584798435784f, 0.589732897992602f, 0.929077658343636f, 0.829643041135239f, 0.0947252609994522f, 0.554884923338572f, -0.513740258764285f, -0.221798194292427f, 0.499855133319165f, -0.0237986912033636f, 0.559618648100625f, -0.509812142428963f, -0.444047241791607f, 0.678274420898738f, -0.983706185790147f, -0.295400077545522f, -0.688769625375228f, 0.729259863393412f, 0.889478872450658f, 0.928277502215167f, -0.429388564745762f, -0.790568684428380f, 0.930220908227667f, -0.796970618648576f, -0.980240003047008f, 0.0372716153521411f, -0.290828043433527f, -0.303854123029680f, 0.160774056645456f, -0.712081432630280f, 0.390787025293754f, 0.981202442873064f, -0.679439021090013f, 0.183053153027806f, 0.665002789261745f, -0.708708782620398f, 0.254574948166343f, 0.0575397183305137f, -0.723713533137924f, -0.732816726186887f, 0.501983534740534f, 0.879998734527489f, 0.825871571001792f, 0.920880943816000f, 0.311565022703289f, -0.788226302840017f, -0.223197800016568f, 0.850662847422425f, -0.365181128095578f, 0.958907951854379f, -0.0421327708909884f, -0.153860389403659f, -0.219620959578892f, -0.469076971423126f, -0.523348925540362f, -0.287762354299832f, -0.913332930679763f, 0.403264134926789f, 0.725849051303960f, 0.743650157693605f, -0.382580349065687f, -0.297138545454038f, -0.480092092629432f, 0.0412697614821378f, -0.396203822475830f, -0.0721078217568973f, 0.979038611510460f, -0.766187876085830f, -0.344262922592081f, 0.943351952071948f, -0.219460259008486f, 0.115393587800227f, -0.342675526066015f, 0.926460460401492f, -0.486133445041596f, 0.0722019534490863f, -0.571069005453629f, -0.0854568609959852f, 0.370182934471805f, -0.554007448618166f, 0.899885956615126f, -0.188476209845590f, -0.548132066932086f, 0.0559544259937872f, -0.161750926638529f, -0.532342080900202f, 0.585205009957713f, -0.374876171959848f, -0.169253952741901f, -0.473665572804341f, 0.942267543457416f, -0.515867520277168f, -0.706362509002908f, -0.320672724679343f, -0.398410016134417f, 0.733774712982205f, 0.449599271169282f, 0.109119420842892f, -0.285090495549516f, 0.0854116107702212f, 0.0603189331827261f, -0.943780826189008f, 0.0679186452322331f, 0.0975973769951632f, -0.870728474197789f, -0.153122881744074f, -0.519939625069588f, -0.633620207951748f, -0.767551214057718f, -0.905802311420298f, -0.841350087901049f, -0.271805404203346f, 0.282221543099561f, -0.0874121080198842f, 0.0634591013505281f, 0.318965595714934f, -0.865047622711268f, -0.401960840475322f, 0.637557181177199f, -0.664578054110050f, -0.871253510227744, -0.893972634695541f, 0.442396058421524f, -0.427901040556135f, -0.740186385510743f, 0.788155411447006f, -0.541278113339818f, 0.509586521956676f, -0.461159620800394f, 0.664671981848839f, 0.880365181842209f, -0.0831685214800200f, 0.952827020902887f, 0.183226454466898f, -0.176729350626920f, 0.851946105206441f, -0.361976142339276f, 0.357209010683668f, 0.982462882042961f, -0.690757734204635f, 0.178681657923363f, -0.0804395784672956f, 0.971787623805611f, 0.875217157810758f, 0.160844021450331f, -0.359951755747351f, 0.0178495935461525f, 0.0203610854761294f, 0.413933338290502f, -0.676038601090005f, -0.111093077131977f, -0.381792206260952f, -0.459903351782575f, 0.308522841938619f, 0.324961267942541f, 0.365201262605939f, 0.732543185546895f, -0.559558093250200f, 0.848266528378337f, -0.185546299813159f, 0.997052205707190f, -0.932554828383249f, -0.106322273904826f, -0.0690562674587807f, 0.919489002936141f, 0.137210930163322f, -0.664517238270193f, -0.985856844408119f, -0.0719443995256963f, -0.602400574547167f, -0.398979518518077f, -0.581117055144305f, -0.0626081333075188f, -0.0372763806643306f, -0.688808592854889f, 0.703980953746103f, -0.480647539644480f, 0.615510592326288f, -0.940226159289884f, -0.953483236094818f, -0.300312284206625f, -0.819419230573751f, 0.657560634657022f, -0.0500336389233971f, 0.628589817614501f, 0.717012803783103f, -0.0315450822394920f, -0.445526173532186f, 0.521475917548504f, -0.479539088650145f, 0.695075897089419f, -0.0365115706205694f, 0.0256264409967832f, -0.0121306374106025f, -0.817618774100623f, 0.375407640753000f, 0.944299492219378f, -0.717119961760812f, -0.120740746804286f, 0.995225399986245f, -0.460846026818625f, 0.904552069467540f, 0.807270804870602f, -0.842962924665094f, -0.923108139392625f, -0.130295037856512f, 0.760624035683226f, 0.986419847047289f, -0.959218334866074f, -0.203345611185410f, -0.474420035241129f, -0.872329912560413f, 0.485994152094788f, -0.515456811755484f, -0.948541161235413f, 0.509659433909651f, 0.783030335970347f, -4.41004028146619e-05f, -0.664795573083349f, 0.917509788523214f, -0.824045573084530f, -0.461857767121051f, -0.667434409929092f, -0.00822974230444418f, 0.825606347148302f, -0.396378080991589f, 0.0161379983198293f, -0.940751675506308f, -0.520997013834332f, -0.239727035024153f, -0.354546027474561f, 0.430652211989940f, -0.557416557692462f, -0.357117274957257f, -0.891975448321656f, -0.0775302131779423f, 0.716775563686830f, -0.903453980341467f, 0.946455001410598f, -0.615060907661003f, 0.964288374469340f, 0.0506144897273089f, 0.720601612869967f, -0.991323837622476f, 0.647403093538608f, -0.400304988135589f, -0.883732066109751f, -0.792060477777513f, 0.710867542231890f, -0.840766000234525f, 0.460362174479788f, -0.834771343071341f, -0.329399142231491f, -0.139853203297018f, -0.760035442359396f, -0.546795911275364f, -0.598172518777125f, 0.244198671304740f, 0.0816980976432087f, -0.978470883754859f, -0.425173722072458f, -0.469868865988971f, 0.847396146045236f, 0.0513388454446360f, -0.545662072513986f, -0.130534232821355f, -0.654100097045099f, 0.0409163969999120f, 0.573001152600502f, 0.706046270983569f, 0.587208280138624f, 0.237670099964068f, 0.848355476872244f, -0.318971649676775f, -0.659343733364940f, 0.321817022392701f, -0.595779268050966f, -0.114109784140171f, 0.998897482902424f, -0.615792624357560f, -0.384232465470235f, 0.156963634764123f, 0.499645454164798f, -0.627603624482829f, 0.169440948996654f, 0.109888994819522f, -0.492231461622548f, -0.463014567947703f, 0.825436145613203f, -0.0271223123229367f, 0.497887971992266f, 0.811868354230459f, -0.192668816770168f, 0.287930938097264f, 0.0283112173817568f, 0.791359470942568f, 0.365100854153897f, -0.566922537281877f, 0.915510517906894f, 0.674211624006981f, 0.505848146007678f, 0.509348889158374f, -0.0477364348461706f, 0.409703628204478f, -0.820970358007873f, -0.565377675052345f, 0.810052924776160f, -0.448904038826591f, -0.830251135876445f, -0.660589978662428f, -0.890196028167542f, 0.130526506200048f, 0.924600157422957f, 0.587215078998604f, 0.727552064386916f, -0.224172021948978f, -0.182984019951690f, 0.308546229024235f, 0.971188035736775f, 0.0229902398155457f, 0.0608728749867729f, -0.0712317776940203f, 0.549832674352445f, -0.600015690750697f, -0.0495103483291919f, -0.564669458296125f, 0.726873201108802f, -0.197851942682556f, -0.983422510445155f, -0.905314463127421f, 0.453289030588920f, 0.792504915504518f, -0.840826310621539f, 0.0979339624518987f, -0.506416975007688f, -0.143310751135128f, -0.451251909709310f, -0.356156486602212f, -0.430777119656356f, -0.593002001098269f, -0.212505135257792f, -0.378005313269430f, 0.516460778234704f, -0.574171750919822f, -0.702870049350445f, 0.190454765104412f, 0.694962035659523f, 0.177498499962424f, -0.00126954773922439f, -0.766110586126502f, -0.769862303237397f, -0.208905136673906f, 0.0728026097773338f, -0.467480087700933f, -0.368839893652514f, -0.608806955889496f, -0.531329879815774f, 0.411920547737697f, -0.407318902586407f, 0.922406353838750f, -0.0272310683929855f, 0.781051179942937f, 0.860271807949640f, -0.703736733439623f, -0.285650334863399f, -0.466904334435873f, -0.716816768536707f, 0.0869377378786880f, -0.280331892461309f, 0.773946156883160f, -0.139856444064730f, 0.575680110908147f, -0.887887626173303f, 0.314286545048942f, 0.673119170729964f, 0.520399233930039f, 0.581347801663144f, 0.731708017815653f, 0.672583525027818f, -0.0534590776637494f, -0.880572908687369f, 0.171150522778545f, -0.377041265530122f, -0.478003213002057f, 0.458602883802583f, 0.836824527658741f, -0.0686622680764437f, -0.301000630566919f, -0.652562984155554f, 0.604631263268903f, 0.791770979838877f, 0.0790491584346489f, 0.812646960034949f, 0.138794042671596f, 0.709411730079774f, 0.226484869016811f, 0.797388098554019f, -0.162225991160828f, -0.0295749256270541f, 0.218242165083417f, 0.442845427695148f, -0.480622209857766f, 0.873464432574125f, -0.868017543466245f, -0.435489784247438f, 0.0589001507244313f, 0.829134536020168f, 0.614063504046069f, -0.0498036542372153f, -0.803122689381969f, -0.495207870035615f, -0.126836582496751f, -0.0715271574335641f, -0.600815700055194f, 0.434993547671690f, -0.891665893518364f, 0.515259516482513f, 0.475325173737397f, -0.716548558025405f, -0.881097306400870f, 0.738462585443836f, -0.244486212870867f, -0.750368936394211f, 0.303496411011494f, -0.602701428305057f, -0.400346153635480f, -0.300002744969481f, -0.518552440201900f, 0.437964598712580f, -0.816689813412280f, -0.814392666138757f, -0.888568091915377f, 0.449416911306476f, -0.231889259488176f, 0.589775175288682f, 0.817224890217553f, 0.518646001325967f, -0.406046689874425f, -0.822100925750380f, 0.0528571826460145f, 0.502410576690672f, -0.795964394123106f, 0.0587614583641718f, -0.960750994569408f, 0.0366871534513058f, 0.723018804498087f, 0.0607565140068052f, 0.337380735516841f, 0.810682513202583f, -0.636743814403438f, 0.287171363373943f, -0.651998050401509f, -0.913606366413836f, 0.642186273694795f, -0.197674788034638f, -0.261253290776174f, 0.696450222503413f, -0.178859131737947f, -0.388167582041093f, -0.0593965887764258f, -0.638517356081890f, 0.804955770174156f, 0.220726627737384f, 0.263712659676167f, -0.214285245576410f, -0.267640297291737f, -0.268009369634837f, -0.957726158424482f, 0.708674977585603f, 0.336764494287156f, -0.985742981232916f, -0.883053422617300f, 0.560301189759340f, -0.692967747323003f, 0.977419052658484f, 0.0749830817523358f, 0.916618822945019f, 0.941660769630849f, 0.454145712080114f, 0.176036352526593f, 0.103229925297037f, 0.936507745325933f, -0.870159095287666f, -0.106465234217744f, 0.684178938709319f, 0.669775326656340f, -0.620857222834950f, 0.939074959093680f, -0.592224920792423f, 0.620706594809134f, 0.0456831422421473f, 0.738727999152789f, -0.751090911501446f, 0.683669216540363f, 0.153825621938168f, -0.255671723273688f, -0.773772764499189f, -0.667753952059522f, 0.887641972124558f, -0.664358118222428f, 0.512196622998674f, -0.0234362604874272f, 0.942878420215240f, -0.406617487191566f, -0.140379594627198f, -0.0587253931185765f, 0.419570878799757f, 0.533674656399007f, 0.108777047479414f, -0.695880604462579f, 0.481525582104998f, 0.511165135231064f, 0.136105196996658f, -0.481918536916982f, 0.757546893769363f, 0.957648176032083f, -0.908743619686586f, -0.395640537583668f, 0.0493439519763970f, 0.293569612893396f, 0.387420368421925f, 0.0928482742403196f, 0.407302666835821f, -0.787979245337637f, -0.968269218296593f, -0.409517247978962f, 0.775076200793689f, -0.217738166217447f, -0.370002483875998f, -0.570975789421316f, 0.844070553036478f, 0.668620483679341f, 0.00139813137293987f, -0.0912495442122028f, -0.0375370940595317f, 0.723007849224616f, 0.369999774115317f, 0.862240371150479f, 0.749525689790910f, 0.742992309993137f, -0.495813719545874f, -0.101947508108870f, -0.152536889610560f, 0.0598123624723883f, -0.436496899502871f, 0.520026918467263f, 0.241005798945400f, 0.970456690492966f, -0.376417224463442f, 0.614223236672359f, 0.336733945081746f, 0.376602027190701f, 0.00373987228923456f, -0.415425448787442f, 0.330560415319813f, -0.277250467297048f, 0.861008806111330f, -0.00655914035278493f, 0.810375656135324f, -0.0113631690466840f, -0.191699616402287f, -0.808952204107388f, 0.813180054552450f, 0.472985418265257f, 0.180147510998781f, -0.262580568975063f, 0.211152909221457f, -0.882514639604489f, -0.575589191561861f, 0.106927561961233f, 0.964591320892138f, 0.738192954342001f, 0.687649298588472f, -0.229142519883570f, -0.354434619656716f, -0.420522788056562f, 0.684638470896597f, -0.608080686160634f, 0.172668231197353f, 0.571295073068563f, -0.202258974457565f, 0.183035733721930f, -0.425589835248751f, -0.181955831301366f, 0.798193178080558f, -0.719799491928433f, -0.376418218727565f, 0.100370714244854f, -0.674685331738723f, -0.528950922374114f, 0.480443520097694f, 0.432497368954013f, 0.887439714903326f, 0.598241701759478f, -0.250064970303242f, -0.743111010477448f, 0.936189907099845f, -0.867383557331633f, 0.852536175309851f, -0.426378707286007f, 0.793838638663137f, 0.856262917294594f, 0.734157059815547f, 0.00452009494051664f, -0.884258713402709f, -0.0835595438259760f, -0.735457210599502f, -0.710727075357488f, 0.858050351034768f, -0.626070522205317f, -0.848201957131499f, 0.0180933910837406f, -0.0350884878366737f, -0.893836321618480f, -0.0682788306189803f, -0.539993219329871f, -0.557660404374917f, 0.268969847256868f, 0.505363999910409f, -0.0464757944714727f, -0.529689906951922, -0.138445378586710f, 0.992531054118938f, 0.974585450054910f, 0.940349645687053f, 0.648085319100986f, -0.410736404028701f, 0.804131759246012f, -0.774897101314247f, 0.178246382655493f, -0.361699623232501f, -0.836093509684016f, 0.806309487627613f, -0.758182371322663f, 0.718410035716663f, -0.213136487421868f, -0.0563465521625497f, 0.0411192849612654f, -0.532497330327019f, -0.0419839515250475f, 0.769432068229678f, 0.253556234192255f, -0.745131216530268f, -0.890639235422577f, -0.140643637034330f, 0.318127074868768f, -0.497415632768561f, -0.383508820416842f, -0.468783454456628f, -0.289531078129000f, -0.0831555730758713f, 0.0107128404847427f, -0.567754537918270f, 0.926366772604370f, -0.600154724486768f, -0.0920759547805206f, 0.889582307602381f, -0.0710437157605615f, -0.182724716112986f, 0.228135065644420f, 0.851015495602628f, 0.653035806598961f, -0.986676404958677f, -0.871714951288816f, -0.824734086356281f, -0.490239304888267f, 0.244318295619814f, -0.923794688606381f, 0.670566388343457f, 0.849438492633058f, -0.225318912425116f, 0.461075616917687f, 0.656436404012820f, -0.416403369651597f, 0.205630417444150f, -0.163509095777762f, -0.0670299490212758f, -0.315561491397908f, -0.0952855008191476f, -0.377993693497066f, 0.860172853824826f, -0.669622978211317f, 0.595058880455053f, -0.425661849490015f, -0.0405359106780283f, 0.129968697438974f, -0.156244199842099f, 0.996996665434629f, -0.888570357356090f, -0.925646614993414f, -0.753998082238076f, 0.714491335460749f, -0.307849905639463f, 0.536274323586448f, -0.462944722411129f, 0.622202376598447f, -0.215582012734053f, -0.115115003363232f, 0.128168110175570f, -0.556263623663708f, 0.921813264386344f, -0.288173574121268f, -0.175054002159610f, 0.0621862747516269f, -0.468862899314091f, 0.976184545317535f, 0.468469061953779f, 0.679394669665911f, -0.0651943232114096f, 0.872740953203360f, -0.917720162541254f, 0.271535917769933f, 0.265441861283112f, 0.542190484993772f, -0.0208550501604048f, 0.983272473294640f, -0.522164666401537f, 0.833823680455458f, 0.414337644113416f, 0.588576354535126f, 0.318369292694380f, 0.870442561030567f, -0.422722224743553f, -0.200185003922166f, -0.770185495487048f, -0.878134057034045f, -0.712873198675798f, 0.647706512601268f, 0.593648188899773f, 0.126171748161942f, -0.189622212946038f, 0.707877641788638f, 0.790070498218410f, 0.698576567863428f, 0.594748885238005f, 0.567439045931572f, -0.591839707769224f, -0.632709967090349f, 0.415471238430617f, 0.115403276784208f, -0.375797954748234f, 0.123611001678020f, -0.864109581464288f, 0.115346512920739f, -0.515581940111704f, 0.880606114362175f, 0.356011740142007f, -0.318112820131587f, 0.765766689783476f, -0.226772670084743f, 0.442067390135885f, 0.348547568069751f, 0.862154389627291f, -0.894863284060244f, 0.475714942110286f, 0.552377629980789f, -0.0838875341374268f, -0.227654706745770f, 0.0998522598030438f, 0.870812229993830f, -0.518250234958224f, -0.0635791579471283f, -0.284101882205902f, -0.454751668241269f, 0.720773434493943f, 0.0756117818245317f, -0.0572317848090118f, -0.692584830354208f, 0.776250173796276f, 0.514052484701885f, 0.00770839936587864f, 0.775668871262837f, 0.933055956393907f, 0.0501713700022097f, -0.922194089981246f, 0.266653852930886f, -0.408584553416038f, 0.797066793752635f, -0.785570848747099f, 0.931403610887599f, 0.660859952465710f, -0.630963871875185f, -0.673000673345695f, 0.518897255252506f, -0.342041914345720f, 0.405613809903414f, -0.373516504843492f, -0.208292396009356f, 0.0510871025610438f, 0.396765368381847f, 0.00537609874241829f, 0.935717099427788f, -0.564801066383885f, -0.907523685862547f, 0.670551481631625f, -0.457309616171932f, 0.364001526470449f, 0.140805524345232f, -0.349945327329409f, -0.0361532758624807f, -0.304268551311720f, 0.618482952755668f, -0.0120110524971313f, 0.106364353621731f, -0.427587198043230f, 0.464249033810121f, -0.808297048471569f, 0.675277128303038f, -0.0663762607268352f, -0.431951364170808f, 0.953951718476660f, -0.725934553905574f, -0.685163723789561f, 0.164132617720945f, 0.934798872032034f, -0.695343627424553f, -0.420317401094920f, -0.689247558220342f, -0.605894279765940f, -0.693832779320227f, 0.455037128281788f, 0.968645000038447f, -0.0839147410947130f, 0.603463489419899f, 0.776913738299999f, -0.491560292499776f, 0.692235227850848f, 0.0824017593921889f, 0.459024952691847f, -0.918050509352710f, -0.777463066447746f, -0.161045596440278f, 0.982603547894360f, 0.700884888820475f, 0.998304481713913f, -0.362488733430088f, 0.171493948866881f, 0.565871153533442f, -0.965620428705067f, -0.835532968802398f, 0.885598629033760f, 0.609604257914327f, 0.725300244775050f, 0.153524048564152f, -0.662541112390878f, 0.912145212201290f, 0.135610445338421f, -0.0813934125800109f, 0.242209063597546f, -0.264886126609115f, -0.335070345839122f, 0.823958964903978f, -0.313110855907701f, -0.354068037633970f, -0.0381190024996405f, 0.117794735211134f, -0.604442743379238f, 0.524930955656444f, -0.754959642694882f, -0.359151666678207f, -0.247910739722172f, 0.573570999369016f, 0.543167570010806f, -0.718553346110069f, 0.202415372555816f, -0.860091438569300f, -0.0125446132328610f, 0.509348782140749f, 0.349261188228469f, 0.424395913611831f, 0.0557092265870811f, 0.740276822496471f, 0.479158001215769f, -0.221873518706244f, -0.744883456979009f, 0.393114117430743f, -0.733203119089531f, -0.506531269498885f, -0.505532097672033f, -0.509440981371663f, 0.666118722468113f, 0.0164067375520756f, -0.530276655546078f, 0.786338654343788f, -0.985008085364936f, 0.479988836226036f, -0.233652481382475f, 0.838641098910395f, -0.407379719374768f, -0.314266358910263f, -0.938033692224531f, -0.627320971378707f, -0.229174127295511f, 0.642505983671691f, -0.387855473250297f, 0.360324209821339f, -0.900766206699468f, 0.176676285751262f, 0.833894117554548f, -0.0207873177403817f, -0.202625183820044f, 0.706644325019314f, -0.817922707040537f, -0.242742059004419f, 0.282109349674866f, 0.0164603911954744f, -0.504625902855950f, 0.0415496120997125f, -0.787777778295785f, 0.362588721999523f, -0.371357162843751f, -0.818375262182416f, 0.727779997467707f, -0.836502839702384f, 0.0423869176265037f, -0.283934686546853f, 0.665864224978728f, -0.0428162304637920f, 0.243534621880753f, -0.803789304599586f, 0.570866852088607f, 0.340615579467880f, -0.323456502239327f, 0.403242371952148f, -0.0679158901587793f, -0.866985651416456f, -0.439873628406335f, -0.246357367033863f, 0.436234859832243f, 0.560714706225535f, -0.632564381913014f, -0.316451076258298f, -0.977122780282003f, 0.0741405862954117f, -0.217862250253606f, 0.887093089232476f, -0.418281865182365f, -0.638553415535034f, -0.262631979211197f, -0.567499176465252f, 0.676178859605923f, 0.933551699581608f, -0.0139735129263516f, -0.610719575803582f, 0.565123751720690f, 0.230672823422021f, 0.323935439339366f, 0.635142215896104f, 0.981184609133698f, 0.883668802319366f, -0.281281673616891f, 0.583204242495555f, 0.150854689098149f, -0.775890223139644f, 0.419951701513177f, -0.565767744791652f, -0.855232478054420f, 0.472188579901153f, -0.501463211798228f, 0.727960518524943f, 0.977187851385321f, 0.908113737694915f, -0.570200931535418f, 0.716036980035073f, 0.147838037485588f, 0.218820342222622f, -0.0673193461152677f, 0.433612519652386f, 0.449601736390411f, 0.556458722303960f, 0.417345590820787f, -0.783345413347895f, 0.858903187230710f, 0.178354025272247f, -0.130619018471658f, 0.858282827806003f, 0.508916167873459f, 0.139535936201634f, 0.240400109521332f, -0.102942705407161f, 0.841682417072375f, -0.696350979494975f, -0.793644449061670f, -0.698273636720141f, -0.228676865074326f, -0.195917865828574f, -0.306483109792438f, -0.865320326812636f, 0.659185969805107f, -0.368847387975239f, 0.337343722359231f, 0.0723822170210744f, 0.907475280998826f, 0.515168301614856f, 0.0790167120323961f, -0.756697420780699f, 0.966477562469936f, -0.663190129982788f, 0.145761851826854f, 0.376079225193173f, 0.631883071958707f, -0.956568110802436f, -0.735990864315730f, -0.795999578321461f, 0.958459465243432f, 0.319180429028702f, -0.907664654881857f, 0.992381284978014f, -0.511208110440365f, -0.714797966909523f, -0.717021870210999f, 0.545775837604423f, -0.0443828768329362f, 0.333311879948434f, 0.617237628406207f, -0.0895192882305207f, 0.506491005527430f, -0.354205929841282f, 0.777993157224477f, -0.667532693120319f, -0.105006112097613f, -0.337191911902220f, -0.337964429160738f, 0.609014812897482f, -0.368922911475613f, 0.889184378947484f, -0.676392242654630f, 0.429716870038086f, 0.916751115281822f, -0.655611878274175f, 0.538928395264007f, 0.382674384886170f, 0.0580742902089004f, -0.0124611362991478f, -0.0240388340005702f, -0.726296501832402f, -0.805701334732693f, 0.945344279474230f, -0.668066000378724f, 0.761436128738929f, -0.314275650172792f, -0.394331510439346f, 0.262887592668013f, 0.155064800148016f, -0.561829218656134f, -0.491542446753775f, 0.922248338472926f, 0.574575887413700f, 0.631722295929094f, -0.368854197209698f, 0.984780657580794f, 0.845286034922662f, -0.965631634115590f, -0.435710392440405f, -0.616488688868478f, 0.885865616625930f, 0.425733070487506f, 0.776721663555227f, -0.0652930284860209f, -0.734431875923792f, 0.725517937762654f, -0.474146253075108f, 0.895357779508529f, -0.0725048758018345f, -0.360185856190223f, 0.559350280666427f, 0.363695103660096f, 0.152231254765544f, 0.698196273442671f, 0.0518001104801953f, -0.139037096279713f, 0.340637636595997f, 0.584243998596814f, -0.442304329829130f, -0.501574294329747f, 0.250155103662225f, 0.320493999001502f, -0.150217982700108f, -0.0381390799255577f, 0.734760815545772f, -0.574574233376749f, 0.593440338163725f, 0.408049858247104f, -0.0845023181203484f, -0.855507806920297f, -0.473198309372409f, 0.331033392104072f, 0.196445364460658f, -0.799745050834061f, -0.973517526224363f, 0.333748727500822f, -0.772356831553232f, -0.430793038424357f, 0.649852557262489f, 0.504357958431509f, 0.779588082810134f, 0.0111847677569461f, -0.995526851285634f, -0.676007517368195f, 0.216774012875664f, -0.618928775636485f, -0.418043155155598f, -0.532063904545563f, -0.566979013994587f, 0.246319907266774f, 0.868651379198082f, -0.0433430896891542f, 0.463004686009427f, -0.162112430964754f, 0.285379745117090f, 0.901512987149549f, -0.706916206313139f, 0.685678130935725f, -0.673017501666538f, 0.0616272859909088f, 0.147532779463338f, -0.0108539826652629f, 0.960841184863269f, -0.950190006701182f, 0.992171414792924f, 0.715577145884581, 0.975908103138584f, -0.769014520827696f, -0.463212420186382f, -0.0761813427220397f, -0.704830850508594f, -0.220579724380686f, 0.840893269946637f, -0.432181989863148f, -0.956790418498701f, 0.122344784859397f, -0.242133592220528f, 0.908514497715246f, 0.303653521236872f, 0.756500828196849f, -0.752207807361831f, 0.367894642791072f, -0.702474131286247f, 0.189226989057138f, 0.401804209353236f, 0.608493473010907f, -0.437378101171900f, -0.158801297891213f, -0.381027984311046f, -0.949403985394057f, 0.370189685252539f, -0.872655295458655f, -0.337934909993878f, -0.0619622888328213f, 0.352094440420005f, 0.128759637109350f, 0.432413186229881f, -0.497474226759161f, 0.552933107875735f, 0.332665936587804f, -0.559261497212156f, -0.886188834336549f, 0.0170548801295034f, 0.192729852728271f, -0.674432365770129f, -0.526014722983374f, 0.425009223123802f, -0.186164676538888f, 0.190362042383007f, -0.0930204201587825f, 0.794188212052413f, -0.243549629178106f, 0.118970185744958f, -0.216230226310237f, 0.412570247218594f, 0.659556685538155f, -0.150540425515543f, -0.850858266540316f, -0.843827815842486f, 0.629298164439457f, 0.944304062363374f, -0.117764731240517f, 0.558568737697335f, 0.731745392387362f, -0.00413812760139165f, -0.251933493011685f, -0.473346352965658f, 0.178783613032362f, 0.547769344759580f, -0.414330113592064f, -0.550251453379012f, -0.925253680779905f, 0.623832825809309f, -0.494251081521428f, 0.0643361026845244f, 0.727107898350051f, 0.814864886916156f, 0.0177325632172460f, 0.749324691554934f, -0.266301024849295f, 0.675202550635588f, -0.0748462128620644f, -0.747853513216831f, -0.222563643557406f, -0.608884446788701f, -0.0374135649675464f, 0.852579123003940f, -0.585927920129879f, 0.604065857569210f, 0.573072924781108f, 0.816831955879520f, 0.723975232584095f, 0.367887024581694f, 0.765292601085641f, 0.836490699448589f, 0.623434131440044f, 0.743568762340577f, 0.140474444458222f, -0.746327891490507f, 0.700496422194197f, 0.549693846244016f, 0.729372970291116f, 0.728185563682229f, -0.614909046853182f, -0.756209631211223f, -0.530222413502955f, -0.312453162783936f, -0.752364704008701f, -0.634475515424180f, -0.133239439768175f, 0.252790153178337f, 0.760626105409900f, -0.838262213452153f, -0.266093046689486f, 0.549339088324875f, -0.278178592347115f, 0.190458706141960f, 0.906814275056971f, -0.579827980376046f, -0.134191470195968f, 0.244720998349483f, 0.795502128014338f, 0.287019836683889f, -0.906277889518234f, -0.817071933038363f, 0.613378274793081f, 0.518208081766432f, -0.388902790616382f, -0.785778461147273f, 0.574976429920521f, -0.283168065839246f, -0.857322381041868f, 0.424932015236353f, 0.919756642423073f, 0.412896759578072f, -0.976511020897041f, 0.157825653359643f, -0.0606591903280758f, 0.508438714729350f, -0.513115001652116f, 0.881391940997543f, -0.129708782033534f, 0.382462819411800f, -0.538751535594113f, 0.816770663497783f, 0.869013288394013f, -0.728381721932439f, -0.956736333819522f, -0.839107107637575f, 0.394821058517234f, 0.721983518815999f, -0.0847231453556103f, 0.0206545030491683f, 0.414707730497861f, 0.246591855656934f, -0.546187573590839f, -0.578957978692654f, 0.162844799084821f, 0.493731081270802f, -0.765815587549615f, 0.151613093585910f, -0.112883397239635f, 0.879319928900002f, 0.295375250614654f, -0.505370201033860f, -0.635319167339584f, -0.309818465920078f, 0.768627024018538f, -0.544374452091825f, 0.758974060573473f, -0.106050973670013f, 0.508616501970226f, -0.207224226211215f, 0.616842248601645f, 0.688381226662374f, 0.643728558619948f, -0.906982649598668f, 0.526262112978799f, -0.666644270400075f, 0.314806313630502f, -0.292000096972562f, -0.358353880616007f, 0.156344541906829f, 0.637606941586786f, -0.199572501073669f, -0.669369278061572f, 0.237513395315133f, -0.576741807179552f, 0.0750117203638310f, -0.633877533594996f, 0.829285089669934f, 0.622345234313277f, -0.892617583855908f, -0.280449892200797f, 0.241147361581176f, -0.0784016295955696f, 0.414945819313502f, 0.287238318044040f, -0.691458270387106f, 0.597656137422422f, 0.549022082569726f, -0.590776624040652f, 0.666740423918019f, -0.743115212424850f, 0.164036350785269f, -0.229427480781113f, 0.283602991107853f, -0.533993445778340f, 0.185806116700093f, -0.317953364055307f, 0.140412503708198f, 0.280706883979940f, 0.0439806827213221f, 0.176471515460512f, -0.614144204292693f, 0.314194083857125f, 0.519572839644130f, -0.850547081260782f, -0.515460990713008f, 0.353087995032390f, -0.0241014119925820f, 0.269453276643829f, -0.608515317887958f, -0.777818225534647f, -0.834277444316067f, -0.842707175235771f, -0.929547602540323f, -0.884691870945475f, 0.710591809809692f, 0.143423776629673f, 0.797136471728128f, 0.233311155245426f, -0.923169961754164f, 0.627911916101674f, -0.338187201367212f, 0.211044396110784f, -0.443699655795038f, 0.256593551969761f, -0.406688684034041f, 0.364900889856600f, 0.900530571350288f, -0.160476177153537f, 0.0634217008071056f, 0.709241599309354f, -0.789562037599596f, 0.00891621061029158f, 0.801674768895422f, -0.704378031949125f, 0.430576706378041f, 0.796937507044124f, -0.193348850174576f, -0.493924902919358f, -0.935781577118986f, 0.468142331108629f, 0.00965840085728753f, 0.0834398764999438f, 0.599712941235232f, -0.735675950275295f, 0.200152501800787f, -0.751603779675650f, 0.0697488403240092f, 0.300634243862625f, -0.901969784333300f, -0.958816237033024f, -0.754976119377363f, 0.719702182489622f, -0.338038642556184f, -0.703280944186943f, -0.579148694005994f, 0.556115731092296f, -0.920710928208685f, -0.278178108839470f, -0.793795308512285f, 0.916547680808212f, 0.419467216101691f, 0.177932177026735f, 0.682833725334600f, -0.926849803428705f, 0.179045225389745f, -0.209414969718359f, -0.889551871881532f, 0.961659420127890f, -0.250341627298645f, 0.105606170554974f, -0.547860346689080f, 0.845704098204057f, 0.886892635683680f, 0.768134466622042f, -0.954777823503721f, -0.718106389777233f, -0.580779231998609f, -0.0241800476518665f, 0.815063484178525f, -0.351971452344303f, 0.770369263680192f, 0.520886146470712f, -0.236456125482696f, 0.0900173391919312f, -0.00610611501589697f, 0.0986788038317752f, 0.277083194173223f, 0.0877085076786761f, 0.695814138412262f, 0.281021332783082f, -0.701468161850407f, -0.785496560046616f, -0.805623403379156f, -0.0524204125046179f, 0.0836418099696601f, 0.467252832788807f, 0.148967572323544f, 0.314141193557124f, -0.722297309069329f, 0.147068590429361f, -0.868307069306109f, 0.118712645744921f, 0.737896544941878f, 0.897526485681248f, 0.842207508585120f, 0.817408479766998f, 0.522315328909182f, -0.409136979179218f, 0.580654760034574f, -0.384701243761730f, -0.769398544059918f, -0.791317178699730f, 0.357020281620118f, -0.235410423267782f, -0.326332500533018f, -0.416891876268284f, -0.863029987000052f, 0.505171215727166f, -0.728709553380428f, 0.554546891580919f, 0.737429989077498f, -0.355088598334119f, 0.911987317939763f, 0.525846127625130f, 0.851549830104189f, -0.772303673276796f, 0.0421942169353806f, -0.521836640530782f, 0.995279650924240f, -0.186831960875832f, 0.421233670121556f, -0.0891583750230474f, 0.661100169663965f, 0.393809652414978f, 0.346165179707090f, 0.384203760628548f, -0.329281932973211f, 0.446133401546675f, -0.748200766224366f, -0.0275154142375615f, 0.771701580845288f, -0.0177829993094090f, 0.406813206251131f, 0.606021648140155f, 0.218435152341115f, 0.236571855064013f, -0.513495776515847f, 0.729086381137554f, -0.137775825035815f, 0.0320966747364262f, -0.313487802206023f, 0.105472520924239f, 0.423606700821375f, -0.231301628369264f, 0.465218832919270f, 0.379671652150568f, -0.00497780485272159f, 0.509290230688327f, 0.467240127182068f, 0.353587964503845f, 0.390455232684039f, 0.721536288927627f, -0.838922323815237f, 0.827628029266859f, 0.768844149796201f, -0.813963144642386f, -0.797054297232628f, -0.933039367361175f, -0.0723957249866136f, -0.664824147893300f, 0.695914840901794f, -0.206071660300270f, 0.879389414398409f, 0.181872681691416f, -0.582831210733033f, 0.624249199449935f, 0.204959730900228f, 0.354831594370532f, 0.337152636438178f, 0.596132114241829f, -0.295619496794481f, -0.443402055665686f, 0.743995051028396f, 0.543706744165365f, 0.825846155044062f, -0.764982315603181f, -0.0355223730700034f, -0.682467026736627f, -0.914037445162109f, -0.222823484413727f, 0.825323277024566f, 0.0769459194171547f, 0.696453968928934f, 0.760786120466962f, -0.525470048583831f, 0.764981036001869f, 0.458525204937000f, -0.612703584870878f, 0.626016142683351f, 0.284799326870320f, -0.130410894642153f, -0.730659587111424f, 0.0251896513929686f, 0.744421417725379f, 0.481278905427271f, -0.718686189713675f, -0.972110566787501f, -0.178005803066219f, -0.761536801353512f, 0.675177569459847f, -0.613068600254845f, -0.854757540148688f, 0.641823580903407f, 0.112536000301536f, 0.201235170163357f, -0.332623522893231f, 0.602028236317460f, 0.487529253813741f, -0.936537443253385f, 0.932862477850079f, -0.0977461167435834f, -0.485449569929182f, -0.575807340541437f, -0.920527242558033f, -0.938208754460503f, 0.890054000488493f, -0.154888511872567f, -0.106629818916523f, 0.323343252623500f, 0.105328135407289f, -0.837197492121459f, 0.497769113944639f, -0.234127101891878f, 0.840922493788059f, -0.994297350473539f, 0.241966031396186f, -0.241143860453769f, -0.598953146106117f, 0.839112451637864f, -0.639567866338402f, -0.219908091959649f, -0.778137266578287f, -0.201424793310289f, -0.486105622640452f, 0.874947034932591f, -0.131437343585340f, -0.674427373037920f, -0.161007203320351f, 0.215285933912207f, -0.963047650748652f, -0.841020847986178f, 0.259702280444602f, -0.165325097679823f, 0.572379756389254f, -0.435802768396928f, -0.0776125194906274f, -0.0293182206559168f, -0.847945015803839f, -0.576891917046364f, 0.728544652294888f, 0.110676857648527f, 0.760459056611184f, 0.486936926897001f, 0.680603035572503f, 0.330358411271561f, 0.901153157113818f, -0.893323547516767f, 0.268679990552354f, 0.794615743189695f, 0.221637368947158f, -0.0207579360252996f, -0.585634995914835f, 0.587646126395593f, -0.317780705107399f, 0.790321547328449f, 0.251610679655279f, -0.0386445267248654f, 0.881542790650722f, -0.469258891944944f, -0.900544881246558f, -0.344978220866601f, -0.271404539202745f, 0.863631450621357f, 0.805892242474368f, -0.325004362330199f, -0.649692260224921f, 0.535815472185538f, 0.427767946389023f, 0.924517987543855f, 0.571059970962007f, 0.549923246060706f, -0.639468249016352, 0.307213071097954f, -0.885892976847170f, -0.526002656640427f, 0.733743042788359f, 0.186919211020217f, 0.322167483598106f, -0.933484010727969f, 0.307181642341518f, -0.391959805653480f, -0.892298105797306f, 0.100065710151584f, -0.932962740784651f, -0.643536993204857f, 0.200747180046148f, 0.310831344540979f, -0.923416823619512f, 0.440768799148345f, -0.666930667413366f, -0.485487251971431f, -0.0627811951952384f, -0.331082293469460f, 0.0335811939608148f, -0.653610782697787f, -0.320586426505716f, 0.559163070852115f, -0.497363452770543f, -0.329886484503569f, -0.146612217140156f, -0.0265272745798242f, -0.288663397675155f, -0.996138396801714f, 0.705746028666908f, 0.634215549629091f, 0.165248482682243f, -0.110791752682943f, -0.0583711657160508f, 0.704663932851230f, 0.105987046073574f, -0.674234600022039f, -0.852792911043127f, 0.779458558047699f, -0.506163961277651f, 0.661431789813829f, 0.362986600662932f, 0.677673397902417f, 0.909704544299484f, -0.678129611146149f, -0.700854916363125f, -0.954905799366644f, 0.819329178422143f, -0.278866438326573f, 0.240572863896085f, -0.597973444252616f, 0.520707363092687f, -0.891796539359942f, -0.0707113684027092f, 0.730270237241197f, -0.202809887987925f, 0.712903235793333f, 0.815918058519912f, -0.619284883130692f, 0.620432327799984f, 0.215462902206797f, 0.913706499476201f, -0.284266999538807f, 0.137669223817851f, -0.320599930994154f, -0.279885143029947f, 0.0759863610502050f, 0.362519848337183f, 0.0897184432777523f, 0.730407126330006f, -0.715664883515070f, -0.964294244830797f, 0.337668374417089f, 0.563780948124681f, 0.534272089774928f, 0.670003495251274f, 0.976582736706313f, -0.576021162432801f, 0.318863740329612f, 0.374838616807691f, 0.437628782275460f, 0.629331465907672f, 0.800673318445353f, -0.964950925853698f, -0.115288102568929f, 0.581179798077059f, 0.892103220665649f, -0.224009831257430f, -0.486848659265476f, 0.768601825625188f, -0.478996958061453f, 0.987216084861456f, -0.00828256241998737f, 0.443388113322642f, -0.209225960405120f, 0.784392408672073f, -0.821157008960409f, 0.169088259578466f, 0.188648958653604f, 0.796321723736402f, 0.804915614204973f, -0.947435972579018f, -0.320368366702004f, -0.0857043727442930f, -0.229914128505395f, -0.802013870592427f, 0.497444368231634f, 0.791040716463223f, 0.586369970276563f, 0.871236424247704f, 0.770091868124107f, -0.458396647683594f, 0.871149873224889f, 0.753895449519495f, 0.295832468734546f, 0.574616471536691f, 0.384408809311353f, -0.978021020306570f, 0.0397482936794495f, 0.628095200786834f, -0.968059492217325f, -0.404306711220928f, 0.659301030460980f, -0.345766174675525f, -0.0517956907600681f, -0.640289082986305f, 0.965202733073502f, 0.909703156044274f, -0.744545066259015f, -0.676836498528477f, 0.0507393165493961f, 0.394673166210436f, 0.250366706754377f, -0.287411651947684f, -0.521760552601739f, 0.214487178617345f, -0.922260536787078f, -0.970217444063294f, -0.632705652784150f, -0.720016326822300f, -0.506393579710801f, 0.774172771450182f, 0.891546338793249f, 0.559706491124446f, -0.513481979527671f, 0.735727350850420f, -0.207760672132971f, 0.956672164225499f, -0.516696999265124f, -0.846015525317730f, -0.199370940530009f, 0.927580907007946f, 0.669786891276299f, -0.208316500739886f, -0.349932032863852f, 0.382722440637189f, -0.455635180187178f, -0.573852668753046f, 0.237990995216907f, -0.00210628303929439f, 0.846035951941252f, 0.921932267818374f, 0.141873820779935f, 0.871317167610738f, -0.632607355185838f, -0.565801401210940f, -0.959881482283947f, -0.732559764685905f, -0.655277252471118f, 0.136770193226314f, 0.206392768880907f, 0.0946932052352707f, -0.147722827344946f, 0.142504821799194f, -0.891443939735724f, -0.660161817562772f, -0.918683225740157f, 0.524851053279394f, -0.841532325411647f, -0.662931925252737f, 0.450018807591706f, 0.157794014139767f, -0.562525486647545f, 0.604051451992330f, 0.859220943805127f, 0.943321402026900f, 0.511188518123118f, -0.332990520726740f, 0.904709059147998f, -0.336911302156504f, -0.0329301811082998f, 0.307263624236174f, -0.640655394434152f, 0.791676792853669f, 0.450137270831791f, 0.746000232170803f, -0.915436267533878f, 0.976514418439799f, 0.828073391112522f, 0.990695018409237f, 0.419713963781614f, -0.286897378037841f, 0.111527193084439f, -0.956913449095442f, 0.263769440437253f, 0.534739246489713f, -0.918314908283506f, 0.680501951418845f, -0.0258330390798596f, -0.696521999550769f, 0.274590593565720f, -0.821334538131451f, 0.104139627465949f, -0.790104923997319f, 0.399265830301725f, 0.118854169469537f, 0.309552488812324f, -0.961100729890863f, -0.665645274594184f, -0.125767140532335f, 0.377154316156289f, -0.971986633153292f, -0.148225730575294f, -0.801072242848910f, 0.735673216754228f, 0.247753694178141f, 0.759093842520115f, -0.529946694334253f, 0.594235069164038f, -0.801015868726278f, 0.141962211231124f, 0.135473683510959f, -0.0431660672944612f, -0.437176231417910f, 0.467008031415084f, 0.324675317141816f, 0.122578305547357f, -0.0351479470228342f, -0.437236315511244f, -0.822621846670407f, 0.989461679354308f, -0.242059902390237f, 0.800837521050356f, -0.387832478851607f, 0.316362161826139f, 0.602440060427024f, 0.890992007298149f, 0.319686042477150f, 0.930326885903916f, -0.170779817104763f, -0.437602177375177f, 0.835764105962134f, 0.522922752459604f, 0.295156847627349f, -0.857646277751538f, -0.451421990712551f, 0.752856133268497f, -0.826193868550830f, -0.906961130052697f, 0.118621494342013f, -0.627099634988204f, 0.163256363060383f, -0.719362770410877f, -0.576563943780491f, -0.369939711177846f, -0.294180430088591f, 0.868430622614485f, 0.945955651201780f, -0.879259966782947f, 0.376142233233261f, -0.549019623646418f, -0.366403875933169f, -0.631308623984507f, -0.398270064613022f, 0.631780765950599f, -0.497821177556814f, -0.0754938097555216f, 0.358298259390762f, -0.438971283619577f, -0.835962846436280f, 0.771544885338102f, 0.132031497593111f, 0.0964144932127649f, -0.171144812197942f, 0.734241841669664f, 0.773828279651661f, 0.591442573315395f, 0.449840299498767f, -0.249196666141921f, 0.910274822633449f, -0.623687862912847f, -0.954398427932048f, 0.700975370671540f, -0.128268698036002f, 0.723971772247224f, -0.239872317271662f, 0.599101633280873f, 0.323504979356466f, 0.726076237951951f, 0.775013638477775f, -0.736157118505210f, 0.681129332563739f, -0.989456914597076f, -0.860559243921100f, -0.652547050354339f, 0.227533741410917f, 0.263244425371628f, -0.412800042549063f, -0.774547399227093f, 0.959749220773555f, 0.0285018454625012f, 0.0260964660594436f, -0.817249773797516f, -0.275510098931589f, -0.957071090655421f, 0.755874233806472f, 0.0601247360044190f, 0.155148678178749f, 0.744458452388040f, 0.206143083045583f, 0.405575258734775f, 0.591273066531951f, -0.286358679634110f, 0.168522523380964f, -0.0740663582251186f, 0.991796969736415f, 0.00304472789286958f, 0.0955103281360055f, 0.595292305224677f, -0.633460800851610f, 0.969720344590438f, -0.788939516987962f, -0.690852963213444f, -0.751849610482179f, -0.454105756229298f, 0.527652178438853f, -0.249156091787771f, -0.395486634371019f, -0.586329259469701f, 0.774216673365643f, 0.000796185912973479f, 0.753872935709907f, 0.691883261316931f, -0.599798140130743f, 0.140718954973018f, 0.400016581571111f, -0.412934563119652f, 0.782683275869451f, -0.837415681080234f, 0.503344297140354f, 0.443222186121185f, -0.869067764953740f, 0.891507832007671f, -0.258782538717313f, -0.592111951047753f, 0.542828422857983f, -0.959476625230936f, -0.373353196174649f, 0.558975637763876f, 0.848608638566440f, -0.861701716955403f, -0.937645215971517f, 0.0456695238513540f, -0.643462752057364f, -0.194887894642735f, 0.576940690214110f, -0.889414400002951f, -0.120401270393403f, 0.581976128201341f, -0.914549817300516f, 0.619675229253819f, -0.446355411157033f, -0.686510097388917f, 0.199022704414501f, 0.0679083509214176f, 0.939286059873160f, 0.919854436895475f, -0.921420499961796f, -0.933865152326639f, -0.173428453947994f, 0.0481843697148709f, 0.282408667923603f, 0.411093542307595f, 0.332739798472214f, -0.539048264159821f, -0.704491312083244f, -0.502163632960363f, 0.955228344617550f, 0.620064399129425f, -0.470222569036376f, 0.754614931250763f, -0.616308595262807f, -0.914574682979899f, 0.624066330640082f, 0.836911269770582f, 0.913639510454430f, 0.653228461676548f, -0.269928008555249f, 0.313006679186127f, 0.984676487220296f, -0.492012769698267f, 0.956868299674771f, 0.291679581317590f, 0.0391808383867289f, 0.572884371819903f, 0.0424011452585180f, 0.955486550514640f, -0.402317209279260f, -0.606465037288902f, 0.547296561663929f, -0.262634118959448f, -0.555413611714328f, -0.328781770154915f, 0.145794994289916f, 0.141260540582646f, -0.451655981927315f, 0.305553535897825f, 0.828724940454557f, 0.263943455052409f, -0.609183422737396f, 0.691170220321907f, -0.372701931956834f, 0.750237424665146f, -0.249353280856890f, 0.379870697565802f, 0.385751069018950f, -0.515117494253264f, 0.716937491491901f, 0.343749563024118f, -0.462962268225808f, -0.542579750084113f, 0.865163879545508f, 0.348358741505572f, -0.309602240547849f, -0.0504864877295679f, -0.822856269672862f, 0.199343960697129f, -0.790668167630170f, -0.0910655952543342f, -0.0243531696455832f, 0.832501734319368f, 0.604933598167068f, 0.899053047900036f, 0.270668041381131f, 0.523691409964688f, -0.0841567002292820f, -0.844392287920523f, -0.910987838261586f, -0.470654231510287f, -0.103828495683496f, 0.253788695977573f, -0.103172947809401f, -0.339896741661867f, -0.447251997825083f, 0.217200476817515f, -0.474840886373359f, 0.227876267254650f, -0.851351819181938f, -0.902078585170911f, 0.445464427415683f, -0.842484493463611f, -0.141606736723087f, 0.104224619207891f, -0.554900879859470f, 0.818556374444811f, -0.832710463532413f, -0.284760316465868f, 0.697962734672817f, 0.235137001970259f, 0.538298155374871f, -0.598477541924834f, -0.833959821954974f, -0.164556670763502f, -0.443902305525605f, 0.484290717235912f, 0.319356252041167f, 0.0834544406255109f, -0.839174383593280f, -0.514784811627172f, 0.466424623987191f, 0.597641402168886f, -0.344706573843316f, 0.346954604803744f, 0.150560726232471f, -0.963838773301094f, -0.210406119881130f, 0.740751216241446f, -0.519896828058978f, 0.882277568799242f, 0.982734995306564f, -0.691486807580351f, -0.120653164608028f, 0.263039860106709f, -0.472131671311566f, -0.469155525952548f, -0.562705921604020f, -0.737502946123759f, 0.151863404645485, -0.367233093688652f, 0.149585386378220f, -0.152980596399920f, 0.572826412281344f, -0.498718037086228f, -0.0794332639424211f, 0.659760386972575f, -0.574814983564964f, 0.451329484188896f, 0.473066930128670f, -0.135151886005125f, 0.379571405476121f, -0.308712078323501f, -0.136843563834117f, 0.395667583713552f, 0.196238140324408f, 0.588147058383512f, 0.770505301611929f, -0.865188840370228f, 0.266437694165002f, -0.428134513764013f, 0.661967260527446f, -0.752421375452379f, -0.556389852423621f, 0.424944298468302f, -0.480554454112605f, 0.916159659428765f, -0.112147362457396f, 0.363475545209813f, 0.698805683596358f, -0.862382341730295f, -0.489415523853276f, 0.453056404353730f, -0.606183761884457f, -0.00869682692408680f, -0.288739722701460f, 0.487988005841341f, 0.566870040344668f, 0.0894575138005909f, 0.887832293799319f, -0.0981274237649674f, -0.279935090781560f, 0.506891141525948f, 0.952901245338457f, 0.458002767525373f, -0.569410776125351f, 0.849518291873527f, -0.585020953514368f, 0.676037258640625f, 0.299076264841081f, 0.911385441491479f, -0.954959555659035f, -0.681285607891366f, 0.631368118385947f, 0.522268523899537f, 0.900701101674748f, -0.647701850365577f, 0.567960815808216f, -0.138958982219446f, 0.267024801687456f, -0.975771109955874f, 0.314682157086949f, -0.378801381286130f, 0.665990927256163f, -0.573674360032848f, -0.860450785684384f, 0.516581474078532f, -0.190844183471714f, -0.451971355445856f, -0.808113003973650f, 0.860446168028895f, 0.377778958059242f, 0.126949039950121f, -0.892203650250330f, 0.572503460980517f, 0.975224974978800f, -0.202312370945465f, 0.500665599343084f, -0.0510413720986291f, 0.353231752436633f, -0.805555931906752f, -0.199761377956955f, -0.829487282239605f, 0.0282459088867508f, 0.814545057118991f, 0.557652277921578f, 0.613951716518862f, -0.678811366342345f, 0.896500288318877f, -0.627622562398925f, 0.802545092571611f, 0.211382709497062f, -0.979380222642662f, 0.826784411456488f, -0.670689878657734f, 0.788878029765924f, 0.137070906151783f, 0.901907287859132f, -0.526217367070263f, -0.545043827128876f, 0.494756249972086f, 0.236657948774128f, 0.156603327087660f, 0.516397244064118f, -0.325837179590292f, 0.460683385171580f, -0.196022953760504f, -0.441996357332195f, -0.808932369852494f, 0.291980108741838f, -0.833583979826152f, 0.365574438479475f, -0.797139524158001f, -0.0649288183732912f, -0.000696491493834994f, 0.100125393693922f, 0.598035350719377f, -0.312548404453564f, 0.0414605409182345f, -0.675913083156432f, 0.236245026389435f, 0.550464243484224f, 0.193366907856750f, -0.903654015709839f, -0.00993172527377806f, 0.0180900754210873f, 0.880678290110106f, 0.166539520562349f, -0.984509466189118f, 0.810283124477894f, -0.925371921448173f, 0.193528916069728f, -0.748644561903135f, 0.534508666819454f, 0.364436869280188f, -0.386979667637943f, 0.427958998441480f, 0.362750270039032f, 0.420886957715891f, 0.0300301961707390f, -0.655220626875711f, 0.0504522662127427f, 0.472640818703213f, -0.417745816013639f, 0.0689992794158720f, 0.461232479061866f, -0.483517586427718f, -0.411463769964024f, 0.622740736364726f, 0.659687134578680f, 0.243900134982579f, -0.684356227282321f, -0.688699031115733f, -0.316032121634021f, -0.644296362948831f, -0.236133265458216f, 0.880259454885881f, -0.956880609581177f, 0.737775899964131f, -0.529059297472703f, 0.794119601436042f, -0.375698158660466f, 0.493447663117292f, -0.752511119115434f, -0.941143365329844f, 0.610101048864035f, 0.253791011658991f, -0.369994602049336f, -0.697364270085742f, -0.681360550250048f, -0.571943442128960f, -0.749697324128684f, 0.611997629275096f, 0.892727938106141f, -0.440225399106758f, 0.00196047981855352f, 0.951252158369648f, 0.0351885308766962f, -0.471806546113710f, -0.657231535594911f, -0.0873481442406481f, -0.0341288006282565f, 0.579184398564974f, -0.224334624306026f, -0.298557652719061f, -0.509401519638379f, 0.188853505083675f, -0.321619146497229f, -0.613159956450671f, 0.570042044631281f, 0.699213203307007f, 0.537439231469861f, 0.529440733283839f, -0.744527226912905f, 0.362949055807175f, 0.529758698714545f, -0.114804719889245f, 0.991089489396930f, -0.186716454683287f, -0.218189173574106f, -0.0493780858124198f, -0.928812411399224f, -0.101855573638590f, 0.454268528366586f, 0.617591620012079f, -0.197519518988231f, 0.0973277590468935f, -0.185672509894105f, 0.649922648337967f, -0.896862900376972f, 0.594999589349510f, -0.746978997769556f, 0.590642952628647f, 0.935109901616311f, -0.293310684054096f, 0.783281817912060f, -0.189898897214222f, 0.414859016240278f, -0.0858574647662298f, 0.0810260863380805f, -0.633024441577653f, 0.248442861097829f, 0.984586601784679f, 0.982811638387854f, 0.547456083836220f, 0.476239638753291f, -0.897709902882279f, -0.208045489357872f, -0.860637131636973f, -0.496740558564284f, -0.944185351410090f, 0.157610983944341f, 0.975214099838643f, 0.550265718083095f, -0.630360326400067f, 0.672420341653334f, -0.897139264107564f, -0.670556423663785f, 0.298764071000339f, -0.310465384759529f, -0.978153640586955f, 0.189785151994709f, 0.929291975296760f, 0.758271912876084f, 0.806829662560108f, -0.472787451147715f, -0.802032434276146f, 0.455809631085663f, 0.985520713417984f, 0.739637167649794f, 0.311705106454777f, -0.120539152808323f, 0.977785717545631f, -0.848554870988208f, -0.281179241544089f, 0.931102239520177f, -0.255243432382956f, -0.284952242030900f, -0.189341152192864f, 0.647573166562597f, -0.474203015584843f, -0.545915610099538f, 0.672696420688916f, -0.239274489717776f, 0.956544960216021f, -0.0858024073600807f, -0.758223415922611f, -0.00817763648068581f, -0.500893489164054f, -0.669386983409311f, -0.344450617815217f, -0.728051392792875f, 0.804121117816188f, 0.00718436691280910f, 0.195237363230272f, -0.472485206728796f, 0.642070241911164f, -0.272384993247314f, -0.731715323915071f, -0.791266589031733f, 0.0339783427570857f, 0.0696513783219659f, -0.894169486972683f, 0.00234016305501483f, -0.0403382685361653f, -0.943600572111266f, -0.788181603936192f, 0.851406365407377f, -0.100015982664501f, 0.145502229793638f, -0.528736628076536f, -0.0313760382570432f, -0.662221611141088f, -0.885722031379862f, -0.744257140212482f, 0.524976313116033f, 0.186092035304635f, 0.181669793648209f, -0.606482674165339f, 0.849303544554227f, 0.226118051135263f, -0.690025550727719f, -0.256543384397548f, -0.207714017766381f, -0.447913202664626f, 0.375270273897879f, -0.884312586292038f, -0.0838720085819762f, 0.969898436757285f, -0.736808033249456f, 0.668875150485586f, -0.599937439969920f, 0.470077288925414f, 0.903135367105719f, -0.895619185450694f, -0.637694108244489f, 0.572669535020987f, -0.696211470281632f, -0.820577518545193f, 0.937364674938455f, 0.422458818039761f, -0.593964370461091f, -0.586264791612426f, 0.0282373486927521f, 0.298051147134121f, 0.592825359583763f, 0.716195674857467f, -0.684008410968338f, -0.167523841045924f, -0.370794208549223f, 0.768054740581884f, 0.997835641681024f, -0.366262133888883f, -0.523114034556271f, -0.457946740456489f, -0.530941146838744f, 0.298744841822404f, 0.390761228562591f, 0.0871171594445448f, 0.764002674223649f, 0.233966808661423f, -0.116573523634048f, 0.426118986433559f, -0.255934695328716f, 0.302314199650152f, -0.254971729124577f, -0.330865677738578f, -0.0840307537517577f, -0.711910586170446f, 0.622585361690409f, 0.367595248366733f, 0.422102667722561f, 0.269580206097961f, 0.707083822001774f, 0.625367208198523f, -0.729594790471199f, 0.708679674727951f, 0.00355767003560614f, 0.379158300246371f, -0.688791438249760f, 0.261637457245975f, 0.704008781391790f, -0.917586017594177f, 0.886443038824615f, -0.923559496787343f, 0.360365726214756f, 0.547058288460181f, -0.279853192856989f, -0.996331953899586f, -0.323735921605962f, -0.618788277975037f, 0.314597206161166f, 0.106380963133907f, -0.235044228453968f, 0.0406899091091886f, 0.687339428801573f, 0.344837805924860f, 0.123214914005620f, -0.735264225932133f, 0.0396243248944774f, 0.270602083588730f, -0.316104623194235f, 0.201800731173529f, -0.348987679395254f, 0.994312100135549f, -0.986073454140000f, -0.787571177818193f, 0.508460947811657f, -0.443663972776222f, 0.800303477136838f, 0.712158443474503f, 0.958364684407633f, -0.0512343510942759f, -0.391095518504938f, -0.291911155637644f, 0.721770656984705f, -0.163541232110535f, 0.0366644501980513f, 0.700853097239887f, -0.508089885354834f, -0.375072588159867f, 0.161585369564288f, 0.686325557438797f, -0.113188612544717f, 0.859354598908873f, -0.723198679696606f, 0.398879124170303f, 0.139357627051752f, 0.484780500073663f, -0.0437501438537016f, -0.868783676783105f, -0.147865612288567f, -0.116480069295514f, -0.986846049950927f, -0.859405305954576f, -0.631359938031082f, -0.0310065270390489f, -0.288382201791710f, -0.500960878568203f, -0.805633068309090f, -0.837604329816134f, 0.0325253228618525f, -0.538953832190091f, 0.913844038280417f, 0.681967460199437f, -0.656775429658090f, 0.922492558885196f, -0.689527254640680f, 0.688263898240070f, -0.225450858342925f, 0.0287239965989763f, -0.407744573364816f, -0.477326718671529f, -0.780374037627418f, 0.500400378743065f, -0.532646941279704f, 0.999679272201893f, 0.136003002234441f, -0.811267727922649f, -0.585019862511894f, 0.125465493193590f, 0.203160759437510f, -0.101322607820275f, 0.543784310894398f, 0.630139383695983f, 0.775322422120693f, 0.229262447827729f, -0.656821799421711f, 0.795940998463793f, 0.263281283116320f, -0.377237794697631f, -0.714267543277316f, -0.161924029976839f, 0.804294011825499f, -0.500488029613262f, 0.716655543045374f, -0.709565530287520f, -0.260746944768714f, -0.496886497176178f, -0.896154699339640f, -0.891352204187934f, 0.0589172685048254f, -0.952496908556348f, -0.543314015084183f, 0.0724005345282401f, -0.132089156895576f, 0.694937364018361f, -0.884509342587775f, -0.944587795707932f, 0.346949362800262f, -0.587900264454839f, 0.531217960795664f, 0.404240620498887f, 0.182769547944683f, 0.804826966991636f, 0.601398794220406f, -0.767933817870427f, -0.329693990599177f, -0.880648189418561f, 0.0370834298504716f, -0.405270662847564f, -0.551993194163015f, 0.357335885219159f, -0.442910616174561f, -0.978355051725551f, -0.638907517841606f, 0.266841057307734f, 0.778698832906031f, -0.967180516636130f, -0.772940622039654f, -0.268706136695081f, -0.326082261974967f, 0.0386785617389067f, 0.576293286973562f, 0.446884000380730f, 0.396703264915684f, -0.718633572608705f, 0.586041202195072f, -0.791039546767268f, 0.556638124682382, 0.728711593864679f, -0.576551104247230f, 0.690227524206044f, 0.0451432373341216f, -0.0569690667958747f, 0.877674150343795f, -0.268602876493051f, -0.770720641807978f, 0.630269600593677f, 0.801702094819180f, 0.177071915997341f, -0.0764831522886398f, -0.476930347674815f, 0.0196833210809626f, -0.566188434097295f, 0.309890567123613f, -0.642682312350471f, -0.645839718540077f, -0.985031719881713f, 0.153028235575708f, -0.446724738384881f, -0.616280949001367f, -0.306418078463084f, 0.313048512921978f, 0.944732667717825f, -0.292311689238647f, 0.263616032352334f, 0.776777395064071f, -0.529182830991988f, -0.418996105801001f, 0.286960890623362f, 0.588336822287104f, 0.268219370126612f, -0.696727535489037f, 0.806089151192541f, 0.0396168299208206f, -0.613570658239778f, 0.358002315998429f, -0.0576147175733950f, -0.859664908314368f, 0.930793190364908f, -0.108955403960031f, 0.640347446939098f, 0.0301817512477458f, 0.508435547839785f, -0.774928250619894f, 0.254548271045827f, -0.192551571812315f, -0.401867317012389f, -0.136220787532581f, -0.480363308055205f, 0.146599399729624f, 0.225767301672040f, -0.207158678688912f, 0.763491487133281f, 0.161192803873192f, -0.574968151683314f, -0.454043408746924f, 0.427131132989065f, 0.170648543751820f, 0.0690597676805780f, 0.0360172652133248f, -0.244429817416531f, -0.973014074152018f, -0.172642279134011f, -0.798684796670922f, -0.622626145444778f, -0.743408670602069f, -0.316057396003030f, 0.908608689971065f, 0.948356574904685f, 0.573858539226522f, 0.457065605245418f, -0.246203048690671f, -0.750525340546383f, 0.612971646035183f, 0.951528788403619f, -0.529776510809815f, 0.0886901849846271f, -0.0254136796699882f, 0.978897595553096f, 0.293893753097695f, 0.620217642132267f, 0.862352989549627f, -0.379040515436326f, 0.790157871471479f, 0.147151952442201f, 0.688271487774812f, -0.897847532497188f, -0.0355337105008888f, -0.850253422176695f, -0.0354384862653523f, -0.625796807949394f, 0.851730076897135f, 0.294773618291289f, 0.834287219330433f, 0.0758749738551283f, 0.912613321307355f, -0.326698079590551f, -0.844748577890143f, -0.685263599922107f, -0.197029963909655f, 0.591416614029013f, -0.130921826828109f, -0.524292687689084f, 0.356220524225632f, -0.150091552835503f, -0.935232109847821f, -0.302103008478127f, -0.998557516519010f, -0.477012685701094f, -0.882343341754284f, 0.210797034143964f, -0.963566378978947f, -0.855600913755685f, -0.790231379847513f, -0.625235937382084f, 0.106405105589857f, -0.760544427202586f, 0.0103124858505332f, -0.610157345750845f, 0.968354521575116f, 0.602472069136318f, -0.216458111191680f, 0.935180184275450f, -0.369261245032360f, -0.289325139062185f, -0.772389696964545f, -0.345513639348744f, 0.135539262008296f, -0.747409495863324f, -0.849724942811800f, -0.739393030129744f, -0.0301380087411172f, 0.373808817820448f, 0.760444548005323f, -0.365739960428504f, 0.121859476627292f, -0.719257541809299f, -0.136914676340304f, -0.178479405732130f, -0.336676444507223f, -0.795056125367297f, -0.0872862684496700f, -0.950510559362909f, -0.395266512078238f, 0.636773305385949f, -0.150667208767723f, 0.534401287220298f, -0.349371424663528f, -0.784729313810243f, -0.0510904599006878f, -0.938702345462904f, 0.616929636007953f, -0.228578318449040f, 0.239101663221907f, 0.0390879233281141f, -0.294705782740043f, -0.847928516841798f, -0.0480433695823821f, 0.487351505367245f, -0.820736333448301f, 0.128692585024021f, -0.305133215914817f, 0.344900079505924f, -0.764316168982242f, 0.717529584295197f, 0.655848670831377f, 0.479849611138232f, -0.107624564628078f, -0.345816374073252f, 0.0822414215758816f, -0.0120870567528208f, 0.475870901669481f, -0.00594923432583361f, 0.869227669945672f, -0.262862047504512f, 0.272430399676396f, -0.734262318791166f, 0.980593493214018f, 0.110413869658192f, -0.732486564250777f, 0.470756873196238f, 0.897133387901917f, -0.151953973158384f, -0.591296220619271f, -0.113167158942796f, -0.103020520738423f, 0.220384226627647f, -0.0570027879342681f, 0.0923157145066511f, -0.523010309215342f, 0.385053964060568f, -0.223938668105458f, -0.0566497019068211f, 0.636390081595965f, -0.753651530578004f, -0.765450358896516f, 0.790370075460245f, 0.622949415286967f, -0.0947634056426396f, 0.122381201893998f, -0.138573523511105f, -0.544298107235542f, 0.535416341314523f, -0.341107295330707f, 0.266262786345860f, 0.620108481133049f, 0.190424987800150f, 0.978559599202704f, -0.925772919482004f, -0.300038300695816f, 0.963372836978511f, -0.501235224357981f, 0.828375446308031f, -0.595716120481773f, -0.889271354193173f, -0.389843123593065f, 0.659433696092409f, -0.633476165557619f, -0.708607689555741f, -0.737738480460783f, 0.985245299432648f, 0.976853985813928f, -0.863072444190232f, -0.785830171723126f, 0.309433061520758f, 0.166813366328975f, -0.552916412621405f, 0.0385101740167735f, 0.445866961855263f, 0.222557362424800f, 0.0710515871571971f, -0.368563489700928f, 0.317406114361191f, 0.326902000037272f, 0.868261309598320f, -0.897838476369198f, 0.664364291232529f, -0.373333343843574f, -0.599809263387549f, -0.411236387818613f, -0.118186587264933f, 0.544960929851182f, 0.395925813072269f, 0.337332244255533f, -0.0195528742963547f, -0.580383437020279f, 0.0779554182143842f, -0.902635825594202f, -0.821554429188969f, 0.869996816042779f, 0.646142135585380f, -0.0824693320525758f, 0.643317857725100f, -0.903892480205129f, -0.457595546004975f, 0.540461917564665f, -0.467530238695992f, 0.107497588388074f, -0.122360487746121f, -0.276968072230331f, -0.436413500733568f, 0.0719555518906898f, -0.794937479672675f, -0.641344733876686f, -0.934734152781945f, -0.0610463967348016f, -0.302623058375597f, 0.281116298309257f, 0.557459622053789f, -0.350054779110337f, 0.681853624031498f, -0.0454067482892435f, -0.897204174835461f, 0.0289327275291300f, 0.664312739864751f, -0.368814604980581f, -0.576946854776660f, -0.187886132141311f, 0.424385580259236f, 0.257994303715228f, -0.567650112011742f, -0.0453371545575014f, -0.362909825264387f, 0.450095578912812f, -0.713870209574945f, -0.956583539581944f, -0.969891699048729f, -0.417755773448598f, -0.230738535348142f, -0.153353095644968f, 0.539368458440622f, 0.591116036659417f, 0.779095541288385f, -0.578525766017613f, -0.587777137316663f, -0.301051260910212f, -0.319655538885669f, -0.343495369437935f, 0.908167583226333f, 0.764220052027033f, 0.0536418758245909f, -0.0529753241803754f, 0.249066042857931f, -0.840152142252005f, -0.529971459254312f, -0.449462194610696f, 0.467144819001113f, -0.500103828192601f, -0.758390449663076f, 0.369740436821770f, 0.189153926151852f, -0.188283227959439f, -0.427563759945909f, -0.186773725840825f, -0.00989853573399446f, -0.783648829817413f, -0.626450875837851f, -0.328015817185970f, 0.760383401930071f, -0.00804531008117837f, -0.982799468341000f, 0.392730506677802f, 0.117799138097530f, 0.351088974844522f, -0.259750164530173f, 0.776495358243216f, -0.703059519879109f, -0.362866233240751f, -0.421345310205860f, -0.818968876330675f, 0.936887497269786f, 0.713300632813635f, 0.916608801523944f, -0.147818975792564f, 0.317064988534009f, 0.885779227314381f, -0.897706599297367f, 0.685423132064732f, 0.907830438936990f, 0.0636614655685575f, -0.423018627861747f, 0.411565657893159f, 0.911060408474647f, -0.617833142759668f, -0.709543522964145f, -0.817633731247023f, -0.252433983274424f, 0.160456393103956f, -0.160765428576997f, -0.622001061437904f, -0.470257555319641f, 0.790643274059634f, -0.648181378655916f, -0.828694900506363f, -0.0234091767546987f, -0.562865077760768f, 0.369299949506391f, -0.423850142805423f, 0.520699811923658f, -0.877662359466779f, -0.739844704434180f, 0.300520939787139f, 0.0655718600121620f, 0.970843358712180f, -0.634231195336845f, 0.324880041395596f, -0.479089635857354f, -0.196422753715449f, 0.568762754402869f, 0.699215376070842f, 0.445741923102597f, 0.679868900756090f, 0.107609859752086f, -0.980983474461865f, -0.788419140653730f, 0.0696289436185713f, 0.00330944186568516f, 0.392265626672398f, 0.803469542460994f, 0.131029913648810f, -0.845408454497170f, -0.754797811352229f, -0.824208086798235f, 0.510072775586974f, -0.809491727769575f, -0.0228491196350333f, 0.920014947791232f, 0.441066319826495f, 0.969846842038360f, -0.199024726691046f, 0.886564290041856f, 0.203997575245743f, 0.481547443573126f, -0.637742489331117f, 0.0664642070998316f, 0.109187062068770f, -0.952676759642045f, 0.309247049771982f, 0.880534651306060f, -0.269363005485603f, 0.280012695899358f, 0.853031642671923f, -0.216236966392235f, 0.903180305900435f, 0.837949615815047f, 0.748563816043584f, 0.266735542018788f, -0.685176037557414f, 0.505893787666761f, 0.977721983069541f, -0.667151469253569f, -0.451774081267849f, -0.385755850727233f, 0.681037251596535f, 0.550130384863457f, 0.704080312734731f, 0.519624533199220f, 0.789651392050294f, 0.176325856625025f, 0.684011432098839f, -0.469125761119035f, -0.841814129063957f, -0.901473334652527f, -0.117747872709914f, -0.608533033968273f, 0.199709646080986f, -0.349430401438670f, -0.435162733168206f, -0.368150014673779f, 0.699084004342174f, -0.446068942643995f, 0.197420740774886f, 0.524893584115327f, 0.706475758890142f, 0.912020785879679f, -0.820472223153770f, -0.334742316079635f, -0.851724976994477f, -0.702164662784812f, -0.649654462810552f, 0.411435475616403f, -0.0438368033650360f, 0.799231452421757f, 0.713371883779316f, 0.252437083518609f, -0.685658163265283f, 0.0734649179831324f, -0.400549431226783f, -0.415602545578540f, 0.233864615718965f, 0.828846528739923f, 0.606577491175688f, -0.266016048272811f, -0.619106744484090f, -0.690853262778644f, -0.503499724631377f, -0.409761822901473f, 0.0576293548519007f, 0.551582021066584f, 0.132631452787255f, -0.838228405334512f, -0.107475742619267f, -0.875306852866273f, -0.184700469068763f, -0.317074087896838f, -0.580912620700556f, 0.453916157844897f, 0.690470988649940f, 0.712835197480083f, 0.314786689622726f, 0.759835688452120f, -0.671090442836235f, -0.408277610289776f, -0.815988422173708f, 0.227854929660384f, -0.0482646895577266f, 0.968141192561708f, 0.373896367655818f, 0.820435826598941f, 0.817746838197885f, -0.0970819110331989f, 0.679170154451559f, -0.577986561676471f, -0.0523570914231941f, -0.776930151133931f, -0.560456597170701f, 0.927747720961181f, 0.0350177837302503f, 0.844938034137843f, 0.00849044473190053f, 0.325089161670337f, -0.851825175889265f, 0.835251667623832f, -0.266397917890485f, 0.108463887056499f, -0.817868888235156f, 0.590399913800720f, 0.699274619715208, 0.200782223352391f, -0.936155874445214f, 0.218471971175575f, -0.890402779861849f, 0.268496441855317f, 0.881231954583528f, 0.279360358017994f, -0.492400368838405f, -0.894376670076375f, 0.585129064098519f, 0.340135248071744f, 0.455880107692993f, -0.861081993524584f, -0.303321115935151f, -0.562781799622214f, -0.526041750296426f, 0.999581943964160f, 0.249814139040315f, -0.0537475603822974f, -0.845239239849439f, -0.874024176808607f, 0.997751771128387f, -0.861617607547820f, 0.671357923629889f, -0.687974310115279f, -0.969462039056016f, -0.448304961870341f, 0.713064428261850f, -0.00718668165564318f, -0.450608596544700f, -0.106059234376561f, -0.591961308554238f, 0.588633089685867f, -0.755341317752403f, -0.542715401462936f, 0.759199260356047f, 0.0297710796506234f, -0.997343196630657f, 0.574076752994254f, -0.696719940193256f, -0.852227517176613f, 0.906332566627663f, -0.171801252847090f, -0.925131151948528f, -0.0212194634560026f, -0.940316444070044f, 0.262965279952363f, 0.902198615594563f, -0.265057066430189f, 0.161983092277652f, 0.0181345459457500f, 0.467973650469608f, 0.857351800575040f, -0.889882538061811f, 0.728868283859490f, 0.671187732362764f, -0.296882575397444f, -0.793099233276668f, 0.335561922676737f, 0.0671874495572633f, -0.0857142329385701f, -0.352870876674233f, -0.119927139078065f, 0.814127111105761f, -0.323910302649634f, -0.313495077982818f, 0.0690526899468447f, 0.877155536890319f, 0.768040884649443f, 0.158910636324140f, -0.824414709871474f, 0.00718921022841235f, -0.868917281154898f, -0.564967532196669f, 0.206261416621150f, -0.0699574404456100f, -0.0547095858591442f, 0.811674902353136f, -0.562993920383635f, 0.441212008804309f, 0.917951119557396f, 0.915571961092301f, 0.0901952529553498f, 0.614118141118295f, 0.760473529905706f, -0.566505475760865f, 0.00880029006400429f, 0.975626259597421f, 0.370738159620831f, -0.0242162976348563f, 0.828887690189252f, -0.665240810020082f, 0.00123256686221063f, 0.184020074202841f, 0.829917510366750f, -0.447854906466885f, 0.529356328938248f, -0.995192699858126f, -0.843748622724646f, -0.422765372440245f, -0.386179414096638f, 0.206325400140261f, -0.369817591904938f, 0.266933785902425f, 0.892617584642659f, 0.740018647415220f, -0.481907279471296f, 0.248268418729551f, -0.382770749117505f, 0.974424303757207f, -0.879320252286332f, -0.0294961755317245f, 0.638693329623790f, -0.765127178629299f, -0.160881380476610f, -0.725001019123526f, 0.00294709357263234f, -0.701949969294570f, -0.708933381768328f, -0.463893635537772f, 0.476650147791524f, -0.206043208566879f, 0.223011684523516f, -0.258637160422673f, 0.206325908651728f, -0.432336904344548f, 0.921979975841259f, -0.944396630315761f, -0.00680582426415510f, 0.319263487872783f, -0.836389324192867f, 0.111532890274445f, -0.938142383682239f, -0.637288670131655f, -0.834211558255576f, 0.251969378874330f, -0.970874587083192f, 0.831662411079802f, -0.446568187924869f, -0.659109068071113f, -0.877869176622375f, -0.890670252448197f, 0.477602927742628f, 0.324737705007923f, -0.147513413112549f, -0.186594638422632f, -0.282864808082840f, 0.745093922271927f, 0.915500859154332f, 0.0421588655873384f, -0.483320910754088f, 0.00503734690385604f, 0.555792895688253f, 0.129412601050279f, -0.229347983583150f, -0.680101211823600f, -0.866063899229274f, 0.437769924839021f, 0.133958234316391f, 0.589233411145099f, -0.498053917701437f, 0.180863681584405f, 0.525955777469479f, -0.581250985307273f, -0.327934857804250f, 0.482381204171926f, -0.867703472610278f, 0.833733008515087f, -0.607761820334944f, -0.758512235503178f, 0.0380785706067470f, 0.719862150842292f, 0.651283470517919f, -0.614218162858801f, -0.239754124815405f, -0.733992057859951f, -0.422541764223845f, 0.951215428883086f, 0.882569470276544f, 0.937054481646402f, 0.184532408731968f, -0.104097666585483f, 0.693277433170057f, 0.800241936558839f, -0.998230532922071f, 0.259835639125661f, 0.562745639592536f, 0.220441127510705f, 0.313735993201991f, 0.330940415696351f, -0.602872424656300f, 0.841677792852844f, 0.749701489563795f, 0.266727039860087f, 0.696379094133993f, -0.430719144952456f, -0.276768289732264f, -0.0872580230244173f, -0.722033206227688f, -0.837309584159114f, -0.629739366225350f, -0.185692585028452f, -0.110619837317415f, 0.515881116042359f, -0.105875685978079f, -0.513700186568578f, 0.961245417898430f, 0.655513716233953f, -0.0921704793645632f, -0.694925472850399f, -0.872174817305748f, 0.0307133806779607f, 0.531120672076921f, 0.965271277398122f, -0.00974420246777163f, -0.497322783064087f, 0.693565685926388f, 0.546918707342947f, -0.230039497490898f, -0.316024461029338f, 0.684231559582941f, -0.306362794944468f, 0.861366189035942f, 0.378922635334764f, 0.259443877770437f, -0.838617128408830f, -0.205350631644011f, -0.139772960377519f, -0.192918167939180f, 0.602404904043886f, -0.537407583974730f, -0.877007125624351f, 0.361539942609439f, -0.732030207831016f, -0.488792995226420f, 0.612591017966442f, 0.567185560938756f, 0.195543595335781f, -0.428955670554558f, -0.666590144318038f, -0.702467396810860f, -0.894350832807439f, -0.0620405855731709f, -0.583114546325259f, -0.482155957064968f, 0.212152442925647f, 0.112603107288251f, 0.0683986906619714f, 0.639176340917929f, 0.642610005510521f, -0.708605273163374f, 0.739594669131005f, -0.492786220480274f, -0.308196102291547f, 0.918748221553053f, 0.186736140989674f, 0.438437026242591f, 0.638769573344929f, 0.928896220524135f, 0.579945520523175f, 0.218608554904045f, -0.526070140579576f, -0.140303420071590f, 0.304347769360423f, 0.488123173638490f, 0.987207018313181f, -0.536397951752998f, -0.553296120219359f, 0.184294880372153f, -0.101502970339396f, 0.287041514309517f, 0.658172721877726f, -0.270141883431914f, -0.0196021946303913f, 0.000779126872975988f, -0.0500294515684538f, -0.588505226599557f, 0.550916571982769f, 0.703271386531766f, 0.982335628009701f, 0.942133544852489f, 0.690741953320684f, 0.0466423349204477f, -0.941178278727504f, 0.121655023640973f, 0.777925151322362f, 0.132430336075323f, -0.114812120408198f, -0.694094073965245f, -0.441397675924967f, -0.187253074701348f, -0.672248118097589f, -0.688869123609503f, -0.0723581859661586f, 0.553779536791160f, 0.380610143087564f, -0.392032089052147f, -0.709403552653908f, -0.607184251637473f, 0.698227587629545f, -0.272885954851784f, 0.0736609147840435f, 0.687106303730018f, -0.230362931709251f, 0.393640839382244f, -0.846905732907407f, 0.0727598538725249f, -0.0119849190815611f, 0.470122652313157f, -0.171681529301612f, -0.329268850654460f, -0.433013841687086f, -0.943499527192280f, -0.123404693276305f, -0.0861435714812342f, -0.228816973160929f, 0.0531549757963279f, 0.901446101051298f, 0.470738280922993f, 0.238383552115632f, 0.292841887198914f, -0.617423653544601f, -0.865786115828523f, 0.586332203179351f, 0.267618252846898f, 0.888575002575769f, -0.0220649407038027f, -0.946385428026066f, 0.317436113017866f, -0.277195072909682f, -0.207326502081016f, 0.735387675940421f, 0.961386190882120f, -0.564038045970629f, 0.840007249305217f, -0.262593952346269f, -0.556378761937190f, -0.346529850864238f, 0.00895460576800877f, -0.695431082536551f, -0.105261635693881f, -0.658342101938401f, -0.631093613961188f, 0.601639903111316f, 0.886830692209879f, -0.600591324826329f, -0.350296019796741f, 0.294348102011741f, 0.555826495708193f, 0.216370653207427f, -0.672654026881445f, -0.572202359802723f, 0.202776438466314f, -0.490708964058038f, 0.0148723360197853f, -0.799031226692943f, -0.221164759306209f, 0.0323674121757880f, -0.130290693568615f, 0.613592603765503f, 0.372755498065474f, -0.540502917956863f, -0.740021877141017f, 0.652888612951242f, -0.666157898478327f, 0.476156241264794f, -0.632081251666311f, -0.538341981270842f, -0.275717185193560f, 0.332983363477103f, -0.989659450166330f, 0.212868816589688f, -0.238985653168422f, -0.453005976359810f, -0.805975530848911f, -0.948192632970312f, -0.291329963979224f, 0.549811667826684f, 0.291147979443248f, 0.909805561757383f, 0.0728533843443158f, 0.737767652888933f, 0.605331616290165f, 0.274826946403577f, 0.710517586349601f, 0.666670055891909f, 0.522059053677516f, -0.553398792071804f, -0.406610321679562f, -0.893232547853708f, 0.549587730399741f, 0.714498083720551f, 0.281833380830291f, 0.652788061587949f, 0.825163748516741f, 0.381299333971584f, -0.485549061474930f, -0.881961689917888f, 0.308937809723222f, -0.524542880617761f, 0.329114405956449f, 0.434631551667457f, -0.894732322264538f, -0.831528385961058f, 0.669760583803638f, -0.674650675537928f, -0.373119878846435f, 0.456602566684508f, 0.387804792569985f, -0.556983911869482f, 0.000826745899317194f, 0.687973801099889f, 0.0471935422816141f, 0.0768302380434509f, 0.317557055919800f, -0.823316513699125f, 0.394699119350099f, 0.609556161256400f, -0.0413041171293194f, -0.244100882405517f, -0.939678976894569f, 0.403390183804743f, -0.933567523933859f, -0.331149894636631f, -0.0265881324103010f, 0.224249195386459f, 0.888271870759308f, -0.119845268644579f, -0.357275416804345f, -0.597001288429956f, -0.486847206619720f, -0.181232488650601f, 0.115441291842326f, -0.599055795186955f, 0.213179364205327f, -0.205238322081458f, -0.373942142629613f, -0.610680997090469f, -0.495737765362772f, -0.257634306994249f, 0.583708320566486f, -0.372047136603982f, 0.953878668619925f, -0.632595987923462f, 0.452049761997455f, 0.166602807787896f, 0.773555002555059f, -0.277154387560832f, -0.557129156714301f, -0.985242402457283f, -0.441173064787937f, 0.561221765682284f, -0.352004972295446f, 0.970292440826449f, 0.855523836321424f, -0.528113079339624f, 0.685454746939680f, 0.322200261898966f, 0.953249967336372f, 0.825673980624808f, 0.177229970128320f, -0.728281956776614f, -0.479030792350269f, -0.00697019557862144f, 0.851652517094715f, 0.853865750362844f, 0.514736989335681f, -0.943509205199198f, -0.0524009027225623f, -0.0798997671509367f, -0.355414349557791f, -0.366273957594958f, -0.565729285138989f, -0.931573923976439f, 0.345119269147864f, 0.638375370217726f, 0.711524360229150f, 0.331664704859388f, -0.986788646426241f, 0.521200596781614f, 0.656290865944842f, -0.436907564088290f, 0.305075696150381f, -0.848337345127939f, 0.354044695448027f, 0.690691708552038f, 0.900352213238582f, 0.475181192463882f, 0.219103309687964f, 0.885437995493547f, 0.421455288320496f, -0.879874221804522f, 0.893371290952196f, -0.545214090169942f, 0.800731783168682f, 0.249421864783476f, 0.0766192343033301f, -0.745747520609971f, -0.613575150364454f, -0.700199720327423, 0.0694373671332735f, 0.759953164582251f, -0.0973030480378387f, -0.298615297250225f, 0.0176506580013247f, -0.269562553201540f, -0.405489169051539f, -0.00491991297033256f, -0.0327449030548885f, -0.688168836745951f, 0.703014457338754f, -0.0909491575673764f, 0.738417882180070f, 0.202377973915515f, 0.338436193625848f, -0.408790267504483f, 0.611776208408261f, -0.711043784659083f, 0.841495665411188f, -0.0445715899008592f, -0.127281559164749f, -0.778797832908623f, 0.210344625249896f, 0.287086540530447f, -0.703702357088620f, -0.151146112491418f, -0.785180444786487f, 0.427963227387140f, 0.873814130606035f, -0.344356753075357f, -0.755726746591465f, 0.846013365191461f, 0.126678120904524f, 0.166687962199295f, -0.148273386834835f, -0.770559345875477f, -0.999129219024862f, -0.223692721084046f, -0.652712854614213f, 0.468054498362978f, -0.911782175948953f, 0.555084850374905f, 0.103972972463380f, -0.414021910330282f, 0.938793897617340f, 0.515461292224815f, -0.127677414947037f, 0.510661477088580f, 0.898409443447962f, 0.528096097102698f, -0.444620870908750f, -0.275909952832928f, -0.516074838791812f, 0.110104492330694f, -0.293114842926621f, -0.596621371059734f, 0.152807456749103f, -0.592864305196648f, 0.948295231208874f, -0.575278847840010f, -0.312463646261757f, 0.664597237604897f, -0.177619554099550f, -0.932259652303036f, -0.295074750863924f, 0.731539128777660f, 0.860409131570119f, -0.0947206503071862f, 0.106073387018718f, -0.235389180430490f, -0.494787189603633f, -0.536357147973158f, -0.680862001049455f, 0.618979489665256f, 0.613893487415732f, -0.308605775713246f, 0.694789556987429f, -0.440049894326668f, 0.908690328690240f, 0.233612239829512f, -0.190662564463532f, -0.344799878911344f, -0.185877286582818f, -0.553543917790750f, -0.859543533414720f, -0.996044831818542f, 0.0388505104043095f, 0.650508591477642f, -0.425233346101631f, -0.576839967180874f, 0.378730359294024f, 0.531713629917424f, 0.506096660522796f, 0.854779196325727f, 0.725302682547051f, -0.414685510902716f, 0.654208477287561f, 0.580368151427426f, -0.000356066597174687f, -0.897393734991154f, -0.845565244312410f, 0.615044057364182f, 0.0434592638759266f, 0.342119048500289f, -0.696414680186901f, -0.713269554140146f, -0.580866925323696f, -0.290886355957456f, -0.473082507703548f, 0.517942229000179f, -0.846159512055215f, -0.715410253368047f, -0.526272663742330f, 0.114004124940380f, -0.207397773975621f, -0.920379649009572f, -0.277970833475531f, -0.636533427057722f, -0.972531734576472f, -0.687000156900366f, 0.872752357637196f, 0.617872391924648f, -0.835274231587444f, -0.383282792481497f, 0.399233665040770f, -0.191230601890140f, 0.620222785371960f, 0.106379326744619f, 0.987222511696630f, 0.219022023664391f, 0.179689082166371f, -0.961619514581522f, 0.570178582343486f, -0.811091514477978f, 0.924484469376845f, 0.744507591138529f, 0.272936430096096f, 0.0646316580619510f, 0.314005111302676f, 0.558833629327024f, -0.329744916784918f, -0.544045568909541f, 0.895769679770795f, 0.798125821580789f, 0.877473384028199f, 0.616163339432501f, 0.441057381106904f, -0.642498173762053f, 0.989059595616979f, -0.374771110304453f, 0.480877593471524f, 0.904941689893360f, 0.428742160807762f, -0.430483645585549f, 0.0830560957640680f, 0.694220841170708f, -0.602964792788891f, -0.522672782287498f, 0.717494777479591f, -0.918002255923909f, -0.454075191574169f, -0.378662039464110f, 0.221482629450150f, 0.750918040362614f, -0.636211037178780f, -0.254529141198887f, -0.944623201010144f, -0.720775773991847f, -0.674641067104323f, -0.208243950413264f, -0.959488786545901f, -0.619966503980330f, 0.599486634018692f, -0.0955439064236721f, -0.458181000169795f, 0.736914498713083f, -0.176789993854223f, 0.676652697410790f, -0.967275583857650f, 0.319377813603719f, -0.427030468653864f, 0.0670640089595258f, 0.769945699222976f, 0.767923203047440f, 0.985790354694142f, -0.207111795449682f, 0.219134401666738f, 0.548513609112215f, 0.977227384558063f, -0.198131173309759f, 0.914163808432723f, 0.178214485462450f, -0.240590252223318f, 0.356128697574950f, 0.453093488702627f, -0.0401152114159198f, 0.818060948361957f, -0.880551400213416f, 0.631519794065582f, 0.658832307703964f, -0.179752451562622f, -0.237844011105596f, 0.739834592198990f, 0.711355594921083f, 0.774856912009109f, 0.321864249971600f, 0.470574585274056f, 0.261964793641569f, -0.634481134262705f, 0.461363065389595f, 0.0879014163867016f, 0.698353456328335f, 0.0611830044908546f, 0.918599000791453f, -0.147822590771951f, -0.208296009525534f, 0.775436805889909f, 0.0380914463017457f, -0.954468558268744f, -0.620451283908529f, -0.770251739379244f, 0.772246778681563f, 0.326462458587915f, 0.417738473564738f, 0.0942643452092895f, 0.486153909005530f, -0.720202618855819f, 0.0172425211828453f, -0.460430186764708f, -0.582933725313246f, -0.439721219285309f, -0.694337374508112f, 0.493516461453915f, -0.993527345413430f, -0.562763570629586f, -0.0644937992008268f, 0.741476357523546f, -0.668588797988340f, 0.594184164979780f, -0.605220767543645f, 0.110074204567278f, -0.599398769115359f, 0.723882026196765f, 0.678747828159456f, -0.608589528492249f, -0.881419419882399f, -0.139357674240927f, 0.873828011683502f, 0.314798068434754f, -0.457017849147976f, -0.526003289738433f, -0.411404919696823f, -0.792254466556923f, -0.299635866135236f, 0.0102316480137963f, 0.161921266554201f, 0.981427028530907f, -0.647351555346480f, -0.183312260273700f, -0.348651484808239f, -0.198142718294920f, 0.589869434168343f, -0.201926511662287f, 0.0337896878721506f, -0.0276515055864679f, 0.236943449722327f, -0.473103622922213f, 0.954358213176107f, -0.536519478008862f, -0.603363977756898f, 0.776267386457251f, 0.780662223932714f, 0.289187291033147f, -0.439954328280331f, 0.0429585232791456f, 0.457321950803212f, 0.236810565417317f, 0.167393310927116f, 0.634521586990289f, 0.154409349572581f, -0.750588956901316f, 0.862647670558265f, 0.800182258889404f, -0.342011510602950f, -0.102697321575297f, -0.797254530582515f, -0.718599505627591f, -0.729105921762328f, -0.152424255231618f, -0.702781451563249f, -0.0212710413372206f, 0.961258625954530f, -0.598484979483616f, 0.188043416567111f, -0.511990501189325f, -0.437449883017104f, -0.352443017251219f, 0.0991554004559394f, -0.663282401319921f, -0.835139403797870f, 0.587602722898819f, -0.939771062270554f, 0.613878515061637f, -0.523857415147229f, 0.444842501987166f, -0.297001528475358f, -0.914581150341453f, 0.554844832376064f, -0.816400014706997f, 0.823726509832068f, 0.704425080572720f, -0.819397910034912f, 0.999003444973468f, -0.968751535943602f, 0.0311500939174130f, 0.247867291448898f, 0.835560943875924f, 0.169794916341582f, -0.302041142019408f, 0.289549413666482f, 0.672141268085176f, 0.947060095876251f, 0.324754171403184f, 0.800014020753458f, -0.785428883146460f, -0.463092135879982f, 0.659192831110219f, 0.118301326248760f, -0.542297334341874f, -0.335957421787428f, 0.794808066256455f, 0.625133567458879f, 0.227917183877260f, 0.533557157748932f, -0.948877884679630f, 0.186417887458649f, 0.859592912781013f, -0.0183320237921572f, 0.967066787435574f, -0.141349529637213f, 0.958107445094614f, 0.264359167622140f, -0.631325355674829f, 0.684598042547604f, -0.527467468151933f, 0.294659298854560f, -0.439220168509424f, 0.391038218778621f, 0.0155669207052447f, -0.681384294454809f, 0.146739459198561f, -0.756404876084652f, 0.381192113543008f, 0.442850940158445f, 0.964002016096921f, -0.0507253848694798f, 0.563462880019551f, 0.190980650425415f, 0.482598778123453f, -0.273426091300166f, 0.980640722167518f, 0.198298590133615f, 0.678100193958147f, 0.530416610025615f, 0.196483886579908f, -0.00515783872303177f, 0.0273438459465027f, -0.257248394117661f, -0.576964504105195f, -0.331030677719652f, 0.389178134459083f, 0.0714066784585938f, 0.915179137858455f, 0.529738860096996f, -0.0851681338619263f, -0.692212896293625f, 0.0786352959300358f, -0.122712774017974f, -0.154641019547052f, -0.487537192251297f, 0.0435645872670241f, 0.856938631597551f, 0.351874085305670f, 0.708100804109985f, -0.701200509799317f, 0.0804479422214388f, -0.0794375302823220f, 0.543751723132725f, 0.346144383452864f, -0.680373368944156f, -0.572281173045994f, 0.237981706511708f, 0.0671482960376590f, 0.852393956008547f, -0.301262907769845f, 0.523762878044853f, 0.0885512158718469f, 0.885168455552951f, -0.333351382431635f, -0.914187358461713f, 0.657220242471575f, 0.202238670865175f, -0.660684692864216f, 0.641271628674064f, 0.795923699912913f, -0.332641448887164f, -0.297595219329770f, 0.427283618553541f, 0.601893958036382f, 0.355248259075043f, -0.420766820174961f, 0.355159952778514f, -0.806733697216087f, -0.694403711049608f, -0.719250654428532f, 0.580487742419744f, 0.959156165420351f, -0.941898541689400f, 0.960568821753178f, 0.119007749103819f, -0.973468502734443f, -0.627534816021182f, 0.331394418445345f, -0.415230278112412f, 0.225355270950915f, -0.216818510922154f, 0.716553646689289f, 0.149097723527982f, -0.212491921692561f, 0.681645638056938f, 0.675358683729395f, 0.0591550775861416f, -0.221626142364110f, -0.235878877821190f, 0.168188057112471f, -0.709738432254387f, 0.842890391064944f, -0.331175752377862f, 0.231375360302226f, -0.714989093452242f, -0.492645353426504f, 0.552424848261518f, -0.436987392663331f, -0.336155191719795f, 0.137666231065822f, 0.739347397348610f, 0.493222787180627f, 0.283646543313800f, -0.603522923409923f, -0.474181275984451f, 0.249315354427624f, 0.323736714335287f, 0.933612934150728f, -0.651555022796413f, -0.743229221575077f, -0.648309364385349f, 0.115117716036212f, -0.0689988553878600f, 0.0394979772968704f, 0.732729774997258f, 0.487584669162102f, 0.808754952095239f, 0.827617962775983f, 0.550826738558347f, 0.890858298785235f, 0.152998196795770f, 0.401198245071198f, 0.187173931669199f, 0.576387011979054f, -0.464903903379260f, 0.735172244343599f, -0.0393734341215035f, -0.501927105416023f, -0.852926247859480f, 0.384774001880198f, 0.723957370923565f, 0.869614310250896f, 0.698124990202440f, -0.0618370378422302f, -0.273879540781302f, -0.0745005910544518f, -0.754408143155094f, -0.859084370639359f, -0.709011936778905f, -0.883595552533659f, 0.326386065122049f, 0.756686513420982f, -0.639817612043620f, -0.536531544653662f, -0.596858657734988f, -0.187117983404806f, 0.760208405412209f, 0.191383034225783f, -0.771443976174702f, -0.371171018178012f, 0.723338724416329f, -0.325113980261468f, -0.652823731845602f, -0.902765567501679f, -0.109945188610355, 0.863727536109734f, 0.762531987550249f, 0.484671237555863f, -0.376731181566557f, -0.961176245257487f, 0.374503763045540f, -0.275274129954644f, 0.947951135663002f, 0.891610575724484f, 0.233179187366345f, 0.868694446846928f, -0.201812205484274f, -0.676342903796604f, 0.962133604967067f, 0.0941637112283598f, -0.0856261317646829f, 0.375061189807232f, -0.275342940020193f, 0.0614298144531287f, -0.183234253182376f, 0.146964792162229f, -0.307180215012337f, -0.139123531176191f, 0.130840221889238f, -0.0654726742084248f, 0.988722897887987f, -0.805684911622576f, 0.763299463922693f, 0.148136188784880f, -0.432183160161832f, -0.592185939638987f, -0.593835208842770f, -0.366135084813261f, 0.840566739882685f, 0.572052978307971f, -0.825682529425410f, -0.970222226210689f, -0.554421263584439f, 0.324648156825255f, 0.0472246837302466f, 0.168098848238140f, 0.00634984653176796f, 0.850237261066903f, 0.286624344510407f, 0.196043215794080f, 0.289161416244007f, 0.334801090322515f, 0.871286740072183f, -0.754609531300255f, 0.623871003889383f, 0.0843430009639772f, -0.736369938040848f, 0.400507674511444f, 0.816325383600297f, -0.500667496861800f, 0.453092855162135f, 0.281798170796444f, 0.631969623501011f, 0.472467114651372f, 0.525988741184527f, -0.124862967293674f, -0.882904489381606f, -0.501090007558747f, 0.631622297793485f, -0.0234210285578584f, -0.521093811962915f, -0.0402368492672573f, -0.762999364505356f, 0.948716268452360f, -0.572740830308272f, -0.261042904339051f, -0.506108365537530f, 0.585933508412429f, -0.362463094458446f, -0.885375028242576f, -0.835757117571791f, 0.337250829139564f, 0.298618238243588f, -0.744903291826588f, -0.979848674056393f, -0.488518944548476f, -0.000297116577397283f, -0.137863396173336f, -0.627207234158244f, -0.970417810284170f, -0.601487862773028f, -0.999527775716382f, 0.116672274325216f, -0.786330829714504f, 0.740118245374718f, 0.856485463622646f, -0.555144930193560f, -0.0168912375666686f, -0.774544329159697f, -0.782767315598991f, -0.600844843420598f, 0.885816107471180f, 0.577075799078571f, 0.663829997048111f, -0.359000184287277f, -0.390009578642891f, 0.202240602818017f, -0.0191477232064394f, -0.566459499064884f, 0.288883557382261f, 0.962583478738218f, 0.782123756762393f, -0.312311582870785f, -0.749354208187204f, 0.205679267602357f, 0.804004517387718f, -0.733078779233144f, -0.426195645938973f, 0.686872484317089f, -0.398704803137823f, -0.267786412313359f, -0.374306263341615f, 0.632992513422251f, -0.972217744254910f, -0.167080739523409f, 0.608176739669718f, -0.935550125875275f, -0.422451600932096f, 0.499643952974426f, -0.491034978653149f, -0.0256130378373849f, -0.158669355267388f, 0.360503946885584f, 0.227714934784132f, -0.138648043280479f, -0.0707461296301128f, 0.0638330442765616f, -0.168811643868974f, -0.575670642767690f, -0.162143785491822f, 0.528621079903453f, 0.581283330394272f, 0.444430744183000f, 0.859288341846780f, -0.170487584890459f, -0.440175706710406f, -0.184806402672108f, 0.676010805169568f, -0.0117535553470483f, -0.231606756742133f, -0.210042044569361f, -0.517950708003565f, -0.805772781723687f, 0.156938933772370f, 0.892075905739393f, 0.403874478002384f, 0.572031508558373f, -0.604145909072008f, -0.330076696654475f, 0.0314560087228033f, 0.683787496948704f, -0.788582181996934f, 0.835276281386949f, -0.0644658492206380f, 0.938270191882745f, -0.344927907293928f, -0.976720519493346f, 0.906264084343827f, -0.648152742145255f, -0.776984965421811f, -0.299470572593974f, -0.423690646950321f, 0.749911693814570f, -0.701929894551648f, -0.665191316321370f, -0.568359320650352f, -0.957309362369509f, 0.914088966355983f, 0.770952996203681f, 0.0924190787439159f, 0.844599990803978f, -0.613336716591875f, -0.683270165308367f, 0.358563204319583f, 0.934597169812267f, 0.236596595813630f, -0.895964332479994f, -0.673302324943916f, 0.454883302340070f, -0.473926010524343f, -0.576000657136217f, -0.644850950007290f, -0.980218836434995f, 0.321620362364719f, -0.799924718666919f, 0.0619872524925393f, -0.609255645268410f, 0.159243124858648f, -0.339764623434603f, 0.379865023026277f, -0.923132229333074f, -0.0300494021321296f, -0.183835365297645f, 0.122648511393234f, 0.887652015676064f, -0.616448517838488f, -0.920600866006207f, 0.352861591267815f, -0.930578364778234f, -0.378819076263050f, 0.775423778544869f, 0.836977798656885f, 0.0472244767469148f, 0.484934339557912f, -0.939155187409193f, 0.261555270800537f, 0.143595058480400f, -0.323517719771947f, 0.483466454684928f, -0.423163689969697f, 0.356966814701025f, -0.843907304366205f, 0.945903563730962f, -0.495952298317153f, 0.972277051575873f, 0.153052037173145f, -0.715894882755676f, -0.617028915483254f, -0.332307224095366f, -0.171207102890728f, 0.841771328272651f, -0.0308707743261867f, -0.626480028747696f, -0.729235538916864f, -0.743517330301179f, -0.733868915239511f, -0.449192858200231f, 0.362286468575150f, 0.327436676142902f, 0.609768663831898f, -0.147499187968100f, -0.470195300907973f, -0.232167856443943f, 0.225074905574485f, -0.0818541072414634f, 0.793403933843056f, 0.267628199755028f, -0.391701371806294f, -0.846991992740029f, -0.776221590294324f, 0.121351482320532f, -0.189789365942677f, -0.894392208695015f, -0.632864319945356f, 0.927817761109627f, -0.732454610273421f, 0.260011686544283f, -0.713973491605344f, 0.469764032416604f, -0.608895265807545f, -0.684992974060601f, -0.745556289276139f, -0.536308213076133f, 0.586581187207818f, 0.149804345860779f, 0.401576742698496f, -0.719670291046630f, 0.618659855530024f, -0.256639783379370f, -0.862966031725668f, 0.893866512913152f, 0.861800793529066f, -0.704895723095590f, 0.154163397540805f, -0.0775797186536984f, -0.252297335448882f, 0.869851864160888f, 0.428747373815147f, -0.818372805928921f, -0.739117647833389f, -0.697378012429133f, 0.182997863108567f, 0.689563104159966f, -0.0506114067037338f, -0.705077813920782f, 0.452892458862023f, -0.365069844049503f, -0.889224821648518f, 0.0194889225677406f, 0.847743515500726f, -0.0650338075825718f, -0.108889937983496f, -0.168485037502421f, 0.912533003086865f, 0.428132366084106f, 0.692652998111620f, 0.130599999674344f, 0.411245435867244f, -0.194909473459497f, 0.562152151569866f, 0.503795293326445f, 0.801805532943245f, 0.795718119772331f, -0.327975015537058f, 0.771389506217327f, 0.237139782375987f, -0.793798852884360f, 0.537824655594807f, -0.0767253125021830f, 0.444538451472890f, 0.623473048970629f, -0.500663871860675f, -0.890399840538612f, 0.389528755348857f, -0.915832255765501f, 0.000652855725217894f, -0.121310443088642f, 0.206662014558968f, -0.409513641801496f, -0.0496262665388731f, -0.313314447256644f, -0.994839397423865f, 0.344513198428247f, 0.250828855150578f, 0.845438302422055f, -0.728803841305459f, 0.249670562418639f, 0.543601559270672f, 0.0138774767713057f, -0.0667600054234216f, -0.803421294778238f, -0.222729734665659f, 0.461896933387103f, -0.378537171475208f, -0.464200027877777f, -0.363170335357481f, 0.616070694104851f, -0.316407896795124f, 0.131719997218670f, 0.0622146037260092f, -0.881713850066484f, 0.400811652868418f, 0.163777537634682f, -0.528768052383715f, 0.553072310703894f, 0.931393033749660f, 0.410062835546529f, -0.190904471223264f, 0.0533617852685424f, -0.911780226731855f, 0.823696403963215f, 0.756735978125573f, -0.849701310148249f, 0.106070214350541f, 0.747890454578944f, -0.559823302095172f, 0.976181619002882f, 0.506524051225122f, -0.0735228576098872f, 0.635610640336510f, 0.607728217052133f, -0.383443012662118f, -0.640835123345673f, 0.0897243696426577f, 0.722421963278953f, -0.368833835044170f, 0.684790387373836f, -0.0336846755494535f, 0.199819176553169f, 0.351822803019512f, -0.433387005248570f, 0.709401898386598f, -0.0149217994364210f, -0.549115733466769f, -0.774049259429836f, 0.440376751789406f, 0.740171176715015f, -0.322301969056869f, -0.148261856544327f, 0.724527166150266f, -0.744178178219827f, -0.743031462890542f, -0.00997727490160383f, 0.550074849063942f, 0.147825200269716f, 0.777182602759074f, -0.625412073440604f, -0.0614214671235789f, -0.400121310797195f, 0.864511820640236f, 0.327656445569618f, 0.765838911283705f, -0.906185069285438f, 0.543656228031101f, -0.527337383463707f, 0.544932532036177f, 0.453966596910417f, -0.422906847383216f, 0.803455668330395f, 0.496651297123425f, -0.254890927444284f, -0.940902660088963f, -0.0691448074129200f, 0.0165534278793877f, 0.510199004798987f, -0.0286331020627788f, -0.141471298460923f, 0.872000980716430f, -0.752995088893842f, 0.167696515625982f, -0.181673581299286f, 0.496236252387172f, 0.854022562040503f, 0.388320660177419f, 0.499320363074588f, 0.173522726183149f, 0.0334192536945390f, 0.631347719906229f, -0.832803059709609f, -0.523826088751894f, 0.322557683663180f, 0.0263621365506006f, 0.948982322858062f, -0.253991680115490f, -0.165970359640120f, 0.331700483099733f, 0.808731855823033f, 0.159862831431822f, -0.438178259673022f, -0.943749594272300f, -0.967819867274861f, 0.263403865531262f, 0.710981741513574f, -0.274597382335371f, 0.929606564147885f, 0.125943272920181f, 0.691306164809532f, -0.607946869004681f, 0.284352421048012f, -0.421663515398071f, -0.409479725854699f, -0.152265311389352f, 0.630868673855242f, 0.123144840061153f, -0.645105689918733f, 0.360153393247973f, 0.683885744053582f, 0.752598814717991f, -0.581494857182821f, -0.469116962448560f, -0.0691726199196117f, 0.174679188611332f, 0.351269328558955f, 0.394815335607621f, 0.710281940645013f, -0.618593505217632f, -0.721546422551907f, -0.974088703589852f, 0.939556772536401f, 0.599407011070674f, -0.342213391542906f, -0.387135346574836f, -0.572027944718123f, -0.622717582512866f, -0.676949872287677f, 0.993953153886700f, -0.784539234625462f, 0.788778188174951f, -0.0652679971583152f, -0.988740647590182f, 0.748989697777310f, 0.412949190397683f, 0.206661198525718f, 0.573116044772809f, 0.938498079842984f, 0.743167714677278f, 0.755679122637903f, -0.295095987460132f, 0.217166189740252f, 0.230160404687938f, -0.504654557405015f, 0.472402206737240f, -0.867751757044285f, 0.869050101160567f, -0.905285205825199f, -0.0698843699947245f, 0.762379282963140f, 0.634191197174691f, -0.498487028811837f, -0.284257632541078f, 0.224245853978976f, 0.412950901773606f, -0.831984679101472f, -0.375663639002356f, 0.153699995838016f, -0.953997055484851f, -0.545360745186449f, 0.637687001020610f, 0.465459355638311f, 0.0769011654935299f, 0.267123343048604f, 0.545842501706277f, 0.778890986545214f, -0.363432183057524f, 0.479786652022207, -0.600912698239979f, -0.738845504293020f, -0.775987143750184f, -0.705559714187038f, -0.310523750352236f, -0.576081829930414f, -0.0341897834633795f, -0.388414434291246f, -0.790681299048144f, -0.169440674711419f, 0.219815472280053f, -0.323451599202462f, 0.835623141427806f, -0.932446301638351f, -0.831480966559550f, -0.185050128422203f, 0.946045240208487f, 0.864740749402213f, 0.916918979039328f, -0.204049261822351f, -0.807183358636872f, -0.484543897885746f, 0.974235382435000f, -0.208019257024664f, 0.647411336652954f, 0.0961385231960816f, -0.800258527388060f, 0.352982142334643f, 0.917274278881503f, -0.733934252997685f, -0.229420044045673f, -0.358499183112933f, 0.469156578609832f, -0.859359096702447f, -0.937762141277625f, 0.389776419837803f, 0.458425599271073f, 0.542973137971009f, 0.675023236195573f, 0.944029213696263f, -0.774027667733194f, 0.262984845114612f, 0.842689106929982f, 0.349251854560315f, 0.815938991679117f, -0.226283690374971f, 0.144356327986477f, -0.610588223452142f, 0.539695204296007f, 0.655759463021729f, -0.725805170479948f, -0.194977831685847f, -0.306105075607822f, 0.725461617920836f, 0.678283785172857f, 0.250577882812283f, -0.571672652704059f, 0.112132856850530f, -0.236412229648694f, 0.768173015701816f, -0.799251028098975f, 0.100723381526471f, 0.113856811781171f, -0.0281630563735495f, -0.0727902548617043f, -0.515248547261805f, 0.795765010992038f, 0.505540143557856f, -0.496124371632015f, -0.363010091302494f, -0.302067159683438f, 0.941309812688142f, 0.0564765277142674f, 0.733027295879568f, 0.582734217224559f, -0.159007222603058f, 0.827637470837748f, -0.163060519537145f, 0.352357500273427f, 0.920405360379926f, -0.280691553157313f, -0.401974149240862f, -0.131353114797667f, 0.0719728276882135f, 0.795795661384902f, -0.348203323368113f, 0.946184663961743f, -0.188400643814906f, 0.979319203447783f, -0.132195434304746f, 0.585832597473452f, -0.894730397941282f, -0.998045985412111f, -0.717844040997160f, -0.706372640246558f, 0.237517748136224f, 0.767232946579208f, -0.246080656591091f, -0.767887803661775f, 0.139501344992184f, -0.545658806327887f, 0.480755550666584f, -0.355750609145607f, -0.493518864013929f, 0.832011102158605f, 0.122542855024589f, 0.179356501845966f, 0.630805165349165f, -0.888557403477561f, 0.861375782261841f, 0.963467658712489f, -0.00498707715217361f, 0.341894517453263f, 0.654808049991043f, -0.826909952854692f, 0.101446328788119f, 0.401514152845232f, -0.830556985096328f, 0.832187560444347f, -0.657254039822149f, 0.0304197382717133f, -0.718462386339415f, -0.592343549551534f, -0.356333235896531f, 0.674135547073730f, 0.606490641440102f, -0.707328770155748f, 0.0251846271186025f, 0.763024927861424f, -0.258224600040528f, 0.456384203436896f, 0.626482995304888f, 0.162353458245830f, 0.964280614412026f, 0.869262296229816f, -0.0659501568862260f, -0.712869755397848f, -0.946968242335746f, -0.852822740386429f, 0.791522782900379f, 0.824530390150335f, -0.369383609091590f, 0.118366422602132f, -0.713278848975255f, 0.549165545117801f, -0.00201102645336770f, 0.748955154405439f, -0.173689412898754f, 0.175162399203493f, 0.0819730422177463f, -0.804833155982895f, 0.972966530563786f, -0.0614871820303859f, -0.293463394754661f, 0.885919261783643f, 0.498531250561504f, -0.808874001349436f, 0.364344357769432f, -0.945616638616975f, -0.285864129675031f, -0.0438177789332626f, 0.303981486324719f, 0.362653007142366f, -0.543157427730716f, 0.174551703296805f, 0.140105048664068f, -0.704163993684247f, -0.647461975308389f, 0.831243960763754f, -0.364954329841192f, -0.730289885595360f, 0.0119708019435723f, 0.796338505809816f, -0.227851954967331f, -0.927330125804492f, 0.0602265250934577f, -0.485204061877453f, 0.198319346525046f, -0.529723177394882f, -0.321493822700232f, -0.839566193416413f, -0.187812484529161f, -0.396142329367383f, 0.367600156667632f, -0.922657847865138f, 0.893508892950972f, -0.504434314314017f, 0.663184814192863f, 0.887813887366393f, 0.267103483259066f, 0.984313142773772f, -0.667515321448428f, 0.0718416862496054f, -0.733363156570869f, 0.00186343206374962f, -0.316531364321301f, -0.467549697367438f, 0.569865535259013f, -0.556502178434536f, -0.650896672234238f, 0.564462797319346f, 0.585276582729153f, -0.433005641153548f, 0.847012427243871f, -0.462088105064984f, -0.379468633087939f, -0.0104892833799723f, 0.654191676584918f, -0.893278846859767f, -0.689350274835588f, -0.333220721049179f, -0.0461703436190983f, -0.463411501818667f, -0.995085073808794f, 0.526075522777196f, -0.0686703698159610f, -0.855908120278260f, -0.239774384006192f, -0.524142243888286f, 0.119526621106050f, -0.838266471869898f, -0.459366707886497f, -0.974921205300089f, -0.680517660007036f, 0.507695286553230f, 0.0920009889477380f, -0.674459855090400f, 0.554585280302756f, 0.357871391273056f, 0.453052004120624f, -0.991707675828263f, 0.144725488641274f, 0.0886535789688503f, 0.708257184179799f, 0.579351194763774f, 0.902098539548710f, 0.0104715251706708f, 0.112677648152527f, 0.0513772996762050f, -0.647561525299580f, 0.321958856072156f, -0.433510239079594f, -0.481493822802105f, 0.651663699618654f, 0.922649363108760f, -0.751799312011289f, -0.0336105332513619f, 0.236872038257485f, -0.0434863841224971f, 0.150810692021768f, -0.217629544451037f, 0.345890414626050f, -0.471941673338326f, 0.675001035054686f, -0.986585320322202f, -0.784679789758475f, 0.270727429189404f, 0.595792127677512f, -0.485969146811564f, 0.222507692419212f, -0.850070310429306f, -0.575184466843042f, -0.220860571657717f, -0.749449040845746f, 0.743039624335149f, 0.463892797640518f, 0.224829531690830f, 0.935410439714992f, 0.00609595972560872f, 0.830877831388658f, 0.0270299847557276f, -0.648763861115704f, 0.471982277585509f, -0.145722971031426f, 0.650947186397952f, -0.266164907037466f, -0.962378355156458f, 0.354855353373398f, -0.184127215272909f, -0.825621979621661f, 0.595495186093792f, 0.448679578752395f, -0.839671989567806f, 0.302158874138200f, -0.735484620769119f, -0.891040803749876f, 0.880298595525880f, -0.281199581528421f, 0.0195033020490396f, -0.511515485794419f, 0.447303195702203f, 0.375317547074287f, 0.964442757731427f, 0.167643569291013f, 0.0118587246816413f, 0.958187068873858f, 0.315395458761821f, 0.188852872643367f, 0.417450657662866f, -0.540566147670448f, -0.422709015019828f, 0.101425586029329f, -0.235465301656357f, -0.806044548641562f, -0.617153815671298f, 0.350658348898447f, -0.738540593521098f, 0.291893065415692f, 0.335435501842245f, 0.832048727909480f, -0.609539777284250f, -0.436992256701542f, -0.685315947977391f, -0.502107715051164f, -0.893460699283628f, -0.262263680492396f, 0.454417031133778f, 0.223227655510993f, 0.605288383003966f, -0.698800586984034f, 0.864843125666124f, 0.363752223710394f, -0.354571459375900f, -0.575008718239530f, 0.423061550052490f, -0.272459660313524f, -0.116932919064239f, 0.547073367599225f, -0.890822451422250f, -0.884262586749836f, -0.889803003239001f, 0.217660629852574f, 0.154863581361214f, -0.333284425759330f, -0.826087281020982f, -0.958198419703014f, 0.850114828540176f, -0.391190814837661f, 0.956578087128909f, 0.0541599967910713f, 0.0988550815990206f, 0.851903747125444f, 0.361959550717838f, -0.901818125706440f, -0.0561477675277424f, 0.522090821863134f, 0.263383912024089f, -0.161061362097086f, -0.983707460720128f, -0.333128836619106f, -0.546535222349413f, 0.627261888412583f, 0.408731616102241f, 0.754700916401496f, 0.869772826180715f, 0.362242883540519f, 0.853587698951791f, -0.698910717068557f, -0.671945256263701f, 0.802655941071284f, 0.338701009518668f, -0.0297818698247327f, -0.881311052338108f, -0.296717226328950f, -0.965699941652671f, -0.737164428831818f, 0.00804554422537485f, 0.989716933531351f, -0.832438692682457f, 0.454553001515962f, -0.933801685729775f, -0.644562445615081f, 0.104508389084640f, -0.535426180524709f, -0.937041822784313f, 0.599911275476691f, -0.789109397888652f, 0.821293320968620f, 0.818032308067912f, -0.838306491947354f, -0.172883985566904f, -0.185775969502745f, -0.672256019841514f, -0.412525056012874f, 0.142272136963196f, 0.792136721788200f, -0.726314486042219f, -0.445981475954073f, -0.857821372905156f, -0.783006950965519f, 0.438776336055643f, 0.400193156140386f, 0.177525578340235f, -0.435380642286229f, 0.547815754835977f, 0.0496394855194708f, -0.442174406426496f, -0.0856142956982360f, -0.0247840885457120f, -0.779016166389253f, -0.511802368745331f, 0.319887353303028f, 0.721806644023428f, 0.770423389111803f, 0.809969588377187f, -0.196191981856391f, -0.105718971622809f, -0.301674515042257f, 0.613622254387482f, -0.969517273103490f, 0.0144576310630131f, -0.668829420461301f, 0.750377960820232f, 0.696858494013122f, -0.563485511352760f, 0.726226115587466f, -0.227540741583116f, 0.665488592033944f, -0.124611809537824f, 0.489550286613580f, -0.579185308695604f, 0.628687311174276f, -0.295770837727116f, 0.240358361854250f, -0.155642183802961f, -0.885945841456110f, 0.388592282428421f, -0.663862196774143f, 0.363779469451472f, -0.371285870971327f, 0.563159689631810f, 0.102725415308920f, -0.320909176496511f, 0.334328794247963f, -0.401664407219370f, 0.726728495517480f, -0.192310060924823f, -0.107973316004269f, 0.898177814643418f, 0.456682306673978f, 0.890742303266606f, -0.742770990765425f, 0.0337493848747046f, 0.786190819119190f, 0.911503487800545f, 0.288384155888888f, -0.249479393879906f, -0.431949793185094f, -0.0847659302921913f, -0.475416985100444f, -0.362720571751962f, 0.676910741300893f, 0.00488530543559529f, -0.227678010632002f, -0.0632947771540859f, -0.990261099329279f, -0.708485805011827f, -0.304846597458441f, -0.480289782580152f, -0.593254971635338f, -0.656335976085053f, 0.584373334310954f, -0.493268395245234f, -0.00212668034894836f, -0.480221591678953f, 0.622365041709782f, -0.258845071515928f, 0.943825418665593f, -0.716642329101759f, -0.765317239111819f, 0.324487844009035f, 0.108158868464706f, -0.790583201992229f, -0.649218622127061f, 0.751409704126257f, 0.301455204388007f, 0.620482350165047f, 0.411016780608874f, -0.878843779367281f, -0.779673415191805f, 0.616508572699874f, 0.0750844738292273f, 0.341011338533919f, -0.553376665552953f, 0.277561087965059f, 0.527499935800293f, -0.489644680144407f, 0.514353996113782f, 0.229842524701725f, 0.139172928186734f, 0.793753206591897f, 0.835555341130211f, 0.794120687009671f, -0.0994745468343306f, 0.109098970584400f, 0.383123470993648f, 0.272549010931094f, 0.683070582699418f, 0.522823199313615f, 0.235903759158310, -0.269490013000195f, -0.103775744391749f, -0.994083979953753f, 0.754983594207459f, 0.806308398378106f, -0.997543362839150f, -0.00396367603607373f, -0.873768378178592f, -0.755907732827809f, 0.703713206520365f, -0.0716773056166142f, 0.0792968663717508f, -0.113760825029016f, 0.828188140127672f, -0.103062543982628f, 0.0455017026983378f, 0.330658414568756f, -0.615810862221588f, 0.827890015477212f, -0.507551960954374f, -0.371044788092612f, 0.723489294741891f, 0.169072478802524f, 0.885612989356318f, -0.496475905980558f, 0.114400438991609f, 0.427961880327008f, -0.0456714004002505f, 0.0246660859589438f, 0.175616122301987f, -0.349777838484285f, -0.939474935533562f, -0.215061649130134f, 0.907049169335834f, -0.0553600192559760f, -0.982464152311714f, 0.405919915647442f, 0.755952405091542f, -0.695422520039876f, 0.373280568864688f, 0.483909023765611f, 0.784896384994620f, 0.978722132488262f, -0.113866140463085f, -0.630016943176703f, 0.512742627309861f, -0.829104067044703f, -0.240982431155520f, 0.0107361024967163f, -0.438682584788413f, 0.935730031472303f, -0.953447901200043f, -0.984218956474073f, -0.745077052885218f, -0.466232938128846f, 0.0326267564209573f, 0.303877586274065f, -0.199843777507458f, 0.674317529952029f, 0.448678903834397f, -0.681863209154081f, 0.273397524216090f, 0.193101955704959f, -0.342858479278718f, -0.485179713360910f, -0.586067050491890f, 0.393099777352274f, -0.982324485510343f, -0.852553426343700f, 0.773613825101220f, -0.590256032959421f, 0.837952413540589f, -0.643137731235821f, -0.311955662956384f, -0.888588599835619f, 0.304629859477166f, -0.810098957400030f, -0.534291626181040f, 0.878601703692302f, 0.362706441157764f, -0.254447668911795f, 0.604309282304246f, -0.977266419340276f, 0.250927873824064f, 0.549600558999971f, -0.796155833245480f, 0.226373301058549f, 0.0137578302483823f, 0.819708534464965f, 0.185662636424304f, -0.450456459548662f, 0.0953849597308440f, 0.736872088617975f, -0.582024306116842f, -0.0522261513001507f, 0.394348349710790f, -0.461023913227183f, 0.139996201153565f, -0.790168851966909f, 0.692544084408690f, -0.580603732841955f, -0.584540773580447f, -0.967062276813525f, -0.00886260208554912f, -0.0520831218167985f, -0.999614949922684f, -0.965820736077636f, 0.366390034326646f, 0.0323069925013668f, 0.164651515113853f, 0.300260003499445f, -0.340634856317630f, -0.238157231550037f, -0.291645957143165f, -0.773881882387456f, -0.144494053860223f, 0.660329619628580f, -0.626727996257997f, -0.994965090982706f, 0.161018019917379f, -0.327211572176153f, 0.0410991278573425f, 0.0123663905917732f, 0.747176159655312f, -0.485981637435718f, 0.00667961234248971f, 0.631625759154389f, -0.831294487064668f, 0.449606477050286f, 0.768845094514142f, 0.928354534843426f, 0.812647997969340f, 0.353418126917875f, -0.872184763557736f, -0.579130598386915f, -0.912928075675835f, -0.779484407508668f, 0.534916834944041f, 0.326353225230543f, 0.395431557674662f, -0.842103899863317f, 0.196590107332985f, -0.261317824893025f, 0.750190543523333f, -0.103409967857074f, -0.201452426430379f, -0.213633615009587f, 0.578822104214576f, -0.130809161238349f, -0.774608769872343f, -0.0222201705228122f, 0.126990738965544f, 0.785780586747108f, 0.0379484317527632f, 0.837140835706189f, -0.191007948387153f, 0.106781679021568f, 0.990298140861558f, 0.618337701073777f, 0.460255491901774f, 0.716379796730692f, -0.159421014009881f, -0.560212468621569f, -0.147263014783522f, -0.962301694075771f, -0.327702010262213f, -0.773959532468388f, 0.351239668535113f, -0.682281479449518f, 0.342188824054257f, -0.743039216419066f, 0.700710268270439f, 0.919651386092770f, 0.626343233048871f, -0.157189576636596f, 0.781882574006976f, 0.349953565654219f, 0.361235312853466f, 0.313242228422046f, 0.582185182102266f, 0.554504358491139f, 0.711217954194576f, 0.332473377627418f, 0.165078226255772f, -0.228349029389292f, 0.899730713958153f, 0.653894503448836f, -0.0452904440925501f, 0.0328806142413372f, 0.793701315832839f, -0.703826261467540f, -0.901648894320192f, -0.195631966969018f, -0.0470590812056508f, 0.487185699934959f, 0.175961644103331f, 0.818028721319245f, -0.224389104974946f, 0.901974203693823f, -0.153212477843726f, -0.472747796173897f, -0.587471692952684f, 0.452340198339707f, 0.996443894349412f, -0.849126217374502f, -0.403800337277983f, 0.923427876645159f, -0.0516037992113898f, -0.380335341989182f, -0.299914673109747f, 0.764492139190834f, 0.773463290027243f, 0.0175454601261817f, -0.400742340353541f, 0.912354892189422f, 0.999766609328281f, -0.521321752061712f, -0.365769506846305f, 0.477612405338644f, -0.0522578739905535f, -0.479259238587280f, 0.645161410912429f, -0.702546085166056f, 0.359736398041538f, 0.638130894056863f, 0.115633419893101f, -0.674410360620500f, -0.150824943737990f, -0.824854463897591f, -0.504410162129685f, 0.560317574021813f, -0.159611666752889f, 0.997647540626334f, 0.702777895178414f, -0.946494281691535f, -0.0109619562916898f, -0.383756482005404f, 0.872670066971334f, -0.453527506439184f, -0.635719199113957f, 0.932852122005178f, -0.800755479140234f, -0.225213334363716f, 0.251163542389519f, -0.598147625383133f, -0.155241293946661f, 0.967736510890644f, -0.0157250628103103f, 0.250570924071858f, 0.209749651169078f, -0.381016062687537f, -0.679300447230592f, 0.160197663113971f, -0.749803147200800f, 0.596917045783617f, -0.0878737681749431f, 0.642402180339789f, 0.261614973684270f, -0.111833224093973f, 0.300170844971678f, 0.317966800167647f, 0.0585375534708252f, -0.842709435910728f, 0.760207701069839f, -0.979366191145221f, 0.940703569377911f, 0.866488078693979f, 0.553497107695259f, 0.127260247084497f, 0.530106152060111f, 0.725171359852920f, 0.356742729430045f, -0.209841680046178f, -0.164239817187855f, -0.888858150931758f, 0.0367561852378047f, 0.803496113779956f, -0.594927045375575f, -0.00347281985657166f, 0.114118941713783f, -0.427864462568672f, 0.719021423892768f, 0.335845790828654f, 0.0207216235296064f, -0.523146933862102f, -0.145001077781793f, 0.490566784879983f, 0.461904660734682f, -0.897010089735077f, -0.895737903861849f, 0.343397505472310f, -0.684377591381862f, -0.0154016881290400f, -0.462987614871549f, 0.884045010701589f, 0.192617174725234f, 0.226497290324550f, -0.788151335932529f, -0.190538526746651f, -0.556614046330326f, -0.139480186854974f, 0.196785300148418f, 0.978844132512627f, -0.290726060479808f, -0.591813978495167f, -0.0769033757443105f, -0.467044929381376f, 0.171585053083057f, 0.408215527269010f, -0.818706013465989f, -0.328144984930982f, 0.790275356337217f, -0.977491163139178f, -0.979679268318504f, -0.524875121608236f, -0.263859024168277f, 0.0180787743488171f, -0.984390626106750f, 0.952274619010224f, -0.851400664579601f, 0.692959439369046f, -0.150312001943653f, 0.712066554169562f, -0.492336226254660f, -0.453559897031351f, -0.159679763180474f, 0.745834647687870f, -0.725963425297178f, -0.720341794596050f, 0.370674334928492f, -0.845974926208293f, -0.00448769398027360f, -0.595973105115042f, 0.967372249596385f, 0.512949503724102f, 0.889619262804735f, 0.990718232652913f, -0.662246751886904f, 0.333846293708563f, -0.423114421367372f, 0.549637439543149f, -0.987876053136374f, -0.782714958794276f, 0.294868983681807f, 0.931284560597614f, 0.445522387300861f, -0.388400162488578f, -0.182673246109423f, -0.773488958971573f, 0.438788569593725f, 0.578106509978236f, -0.373449127435319f, -0.301996528814967f, -0.227124771031239f, 0.700176189695036f, -0.910948938567526f, 0.733412403327578f, 0.486154072292544f, -0.974058632864456f, 0.216693355653246f, 0.147564301397678f, -0.715192277853558f, -0.366996833259925f, 0.568909126406069f, -0.0810069456450131f, -0.371253841044151f, 0.254736918036059f, -0.868966383080701f, 0.190312518076662f, 0.457253801337437f, 0.941043431633233f, -0.297470749600241f, 0.244270515950156f, -0.240122562119888f, -0.766384662307300f, 0.765045432900429f, -0.608250739173787f, -0.733052557932594f, -0.268433000443065f, 0.733598123424154f, -0.0550005774741753f, 0.273893221740822f, -0.659641650983149f, 0.967032725204337f, 0.390126626361090f, 0.518740746381756f, -0.859387560527806f, 0.554117289841284f, 0.648904904654236f, -0.755880975555381f, 0.834231592524942f, -0.137512395743275f, 0.0477027353535724f, -0.880364563062979f, 0.458763614093086f, 0.650036413308116f, 0.496385905878033f, -0.418537115548864f, -0.565561960782851f, -0.227941684691245f, -0.165031891659812f, 0.204464989908300f, -0.688093624763916f, -0.678874848552394f, 0.813764873880514f, -0.561723359541237f, -0.575805702297063f, -0.288097000970518f, 0.950119107184838f, 0.709879842972902f, 0.730067219897393f, 0.710813066057284f, -0.192333836978130f, -0.190446300563246f, 0.872679304648751f, 0.134143163657763f, -0.979443835407234f, -0.103872104041761f, -0.0568328979324004f, -0.863020133862081f, -0.0257801722427251f, -0.577962771617033f, -0.0500056799801032f, 0.191817418291914f, -0.799853775410853f, -0.110019424741421f, 0.840753817223395f, 0.355588322976119f, 0.274501278628024f, 0.757538306972136f, 0.771547320156202f, 0.0394143752709530f, 0.120744072764658f, 0.324337882930581f, -0.380086709776951f, -0.772025774284869f, 0.473986846199588f, 0.703247561676381f, 0.734667480205300f, -0.594290184210087f, 0.760158653782445f, 0.624553744314883f, -0.941053266957965f, -0.165913770936962f, -0.0497972870738055f, -0.0435608680908517f, -0.663165366083943f, -0.570972482385751f, 0.427845034528880f, 0.0897903148165149f, -0.481825010950428f, -0.0901127105939594f, 0.887770435656611f, 0.770985476674623f, 0.00966158758316293f, -0.331059327378268f, -0.286033645163736f, -0.0698945910210471f, 0.834392309773299f, 0.875537383319608f, -0.657919190548359f, 0.583890957562885f, -0.418481077359384f, -0.282242397022386f, 0.864577023994874f, -0.898367126143440f, 0.815804441243808f, 0.616061408588373f, 0.132365642864798f, -0.221099752471970f, -0.852722283680675f, -0.269499596712950f, 0.360828136129415f, -0.120022743070141f, -0.0354652134632905f, -0.718389836602256f, 0.973490047219112f, -0.201775047168341f, 0.348769511760972f, -0.338750368577880f, -0.269769414088757f, 0.498910931428472f, -0.787648791515347f, 0.508408064858444f, -0.904215976374529f, -0.778575029821227f, -0.662889546847757f, -0.787503064261069f, -0.915166838630178f, -0.415784802770356f, 0.731806835017609f, -0.903922155472207f, 0.0872811033112211f, -0.452516774501827f, 0.577942533813694f, -0.200909337658770f, 0.866167939661793f, 0.982552542055944f, -0.332277333696961f, 0.201673960342839, 0.881239812364993f, -0.0293753746942893f, 0.0967170348490725f, -0.765573023404242f, -0.179225339525953f, -0.931530757069740f, -0.702596334762137f, 0.439106079307245f, -0.469364154277323f, 0.211063395888038f, -0.245858633045693f, 0.936376071219385f, 0.0334087380010875f, 0.0765265939183459f, 0.417091701258078f, 0.962467059286170f, -0.180698008768999f, -0.129816441691123f, -0.833694435146788f, -0.800582099046532f, 0.736376297618233f, 0.0164704176688124f, 0.207462305741760f, 0.300555292898496f, 0.777154212278295f, -0.0804533056660695f, -0.279940128908185f, 0.203101811030871f, 0.447496959357837f, 0.508353359025257f, 0.644333822521829f, 0.897259297488483f, -0.675785952117501f, 0.149337263319588f, 0.350953290584184f, 0.600296681944338f, -0.606098182955297f, -0.418312129297725f, 0.792551232171214f, -0.944025948110651f, -0.923106441737020f, 0.508989820072736f, 0.101554011154237f, -0.799369609980037f, -0.229001813644938f, 0.196367996268564f, -0.634078446275840f, 0.267446716753553f, 0.943765754688567f, 0.329924442019441f, -0.898235312442524f, 0.563592978494850f, -0.976934293161001f, -0.609744819901837f, 0.498989633313589f, -0.105680058480959f, -0.400730747241191f, 0.264919109340783f, -0.313066735594123f, -0.465399967597728f, -0.425123918113080f, -0.609514085808810f, 0.916560800692384f, 0.0173757138934230f, 0.147814399202503f, 0.594152503614559f, -0.145681097751433f, -0.427232299718493f, 0.233460382614713f, 0.337361272635241f, 0.376106438004541f, 0.900277274651600f, 0.424547631957395f, -0.710790444715071f, 0.0846761090154495f, -0.0122707338404220f, 0.119989812955904f, -0.239774389963524f, -0.692300891031819f, -0.735109129583214f, 0.802276300301071f, 0.348982047806247f, 0.916302084278941f, -0.0838164783829127f, -0.989134997097880f, 0.832909602224562f, -0.701363449605445f, -0.150487976031971f, -0.728594035984111f, -0.144393031996783f, -0.458856761770637f, 0.733295441303064f, -0.405608670768629f, 0.522871610912813f, 0.468223399458939f, -0.575139530810903f, -0.241684287862418f, -0.499140599234906f, -0.395586476697394f, 0.692745485195348f, -0.125142235859546f, -0.342212246193052f, 0.133841188490164f, -0.539478395228865f, -0.887973984329817f, -0.474033882236453f, -0.837114132429830f, 0.773392302912611f, 0.117697651876253f, -0.461595011213406f, -0.528669601602068f, -0.957799577987062f, -0.468654423525192f, -0.0602288998398475f, 0.154553704272891f, -0.422854231304259f, -0.496136532114270f, -0.348154983723668f, 0.0576478341707483f, 0.542088962901856f, -0.0465812136931592f, -0.280128217727361f, -0.900695482510248f, 0.525110685457899f, -0.957266165874283f, 0.136490670826643f, -0.213221811269364f, 0.690040133288898f, 0.269408771473479f, -0.0488994830172422f, -0.837526616586426f, -0.289127052660601f, 0.149325279006459f, -0.694169700971401f, -0.0230547571616897f, -0.368313297034846f, 0.344434270521740f, 0.859135365902404f, 0.839336654691204f, -0.511783987355355f, -0.0349625753049687f, 0.935857929664427f, 0.820032045433520f, -0.0394079346656324f, -0.656352913407746f, -0.874383371678169f, -0.425836335156061f, 0.208600154889275f, -0.135596548598733f, 0.566430757256762f, 0.820840891306264f, 0.735746624790780f, -0.765482927015804f, -0.0195537720748045f, 0.606216172027628f, 0.436027839798869f, -0.609233580289002f, -0.963547951222316f, -0.575271468261977f, 0.692873344771925f, 0.143031668657597f, 0.890157114774225f, 0.762299295692265f, 0.653618249618643f, -0.957258626549595f, 0.521895225378123f, -0.607922211531407f, -0.956795748110572f, 0.477633684273092f, 0.794301967670603f, 0.139753218894595f, 0.371726372555490f, -0.804791987531745f, 0.837080126047059f, -0.440992020192054f, 0.584986017638085f, 0.950442046050057f, 0.613109120495913f, 0.633948971396891f, -0.581246845000116f, 0.730290176291093f, 0.599119212595240f, 0.120096101936515f, -0.144169383323758f, 0.930776406826440f, -0.0209712926465206f, 0.572995665695966f, 0.924623298379120f, -0.751832867985678f, 0.630196806059302f, 0.506634179395662f, 0.0388997263873157f, -0.311041196366299f, -0.729049093325017f, -0.918815504666740f, -0.103935429478766f, -0.000623544124330300f, 0.102880227280474f, -0.563637096166535f, -0.332148269587814f, 0.472114131256244f, 0.295717126494164f, 0.246944592105312f, -0.713191555660498f, 0.160410320426559f, 0.110992936470077f, 0.213877527744528f, 0.541660996543375f, -0.872405734998843f, 0.388515073094269f, -0.840811647524440f, -0.968008592072007f, 0.669947948420772f, -0.122943215855172f, 0.565929115911552f, -0.695408966310186f, 0.361296950635219f, 0.574282481983669f, 0.0877180513263536f, -0.694316083550519f, 0.327696487191071f, 0.289746985823208f, -0.241476327174879f, 0.605084742574250f, 0.0929272338220821f, -0.391399761658219f, -0.612928183827531f, 0.0471987261466311f, 0.157388702609590f, 0.575695018001234f, 0.450453491026024f, 0.876623108212541f, -0.456500163180038f, 0.436901006801809f, 0.796734433864345f, 0.771008396172517f, -0.784740610155705f, 0.405172719255834f, 0.958393667559228f, 0.787380105147761f, -0.262826016234054f, 0.773327117333271f, 0.482142068916266f, -0.461607549022954f, -0.153993688218026f, -0.129280134980317f, 0.901812622560630f, -0.111520793491644f, -0.0973214524989203f, -0.293695817178366f, -0.190045093887485f, -0.204792515844396f, 0.501086384719391f, 0.755953359112033f, -0.425886872154604f, -0.0883029298084141f, 0.763071371252921f, -0.556289447935984f, 0.577370462369201f, 0.0480599614417476f, -0.794423686623353f, 0.756645959967545f, 0.570538730848462f, 0.872575422156333f, -0.443572567528656f, -0.0487937634747691f, 0.283986553648095f, -0.170910821134099f, -0.329867000423004f, -0.982322841409943f, 0.555344201026651f, -0.351964643393940f, 0.776172688776518f, -0.148102477734717f, 0.889532618676503f, -0.310979434517253f, 0.711839903052208f, -0.646385596147085f, 0.145592596381502f, 0.233949589173221f, -0.825471565980294f, -0.370248763132654f, -0.777194557275684f, -0.224658064754195f, 0.263281286751478f, 0.849661910468068f, 0.271261490445121f, -0.915885420717958f, -0.947144520818678f, 0.227960459606299f, 0.784463828083640f, 0.995882406349565f, -0.987273766396493f, 0.0792453274840108f, -0.788403526960056f, -0.619975942121645f, 0.801181796307713f, 0.967884377026145f, -0.781223064263388f, -0.300716486479280f, 0.994748932974184f, -0.200152360574411f, -0.101898131541608f, 0.542914585925881f, 0.407729967031792f, -0.105215843903154f, 0.638066037611924f, -0.563777780161298f, 0.134189395993685f, -0.503320561486155f, -0.0379170306314711f, 0.723638115686875f, 0.747948383928228f, 0.928239905995551f, -0.736883772878758f, 0.892242913709735f, 0.468998243295705f, -0.224406388545097f, 0.758754382878863f, 0.994739001052496f, -0.749837906573089f, -0.938777322178786f, -0.619168635741936f, 0.827875717654585f, 0.294033159230782f, -0.372766318349126f, -0.292752124932124f, 0.396629951868878f, -0.986760927173237f, -0.0841834195975009f, 0.999760803826313f, 0.0142305924173638f, -0.820393900206961f, 0.409972278573230f, 0.227315924377402f, -0.641500351639361f, -0.470788010535406f, -0.486171076557593f, -0.758140688442947f, -0.971539708794928f, -0.949039718833189f, -0.146844988902767f, -0.0183627478820223f, 0.402918762093981f, 0.0620266698060286f, -0.182527786403967f, -0.374395326540229f, 0.566584207940253f, 0.879546558847970f, 0.853360173786566f, -0.515321950652696f, 0.511692631053674f, 0.342152084355850f, 0.374686420595610f, -0.794372980760555f, -0.648670375991101f, 0.761192158420166f, 0.223791993225057f, -0.342720055148453f, 0.965612513218950f, -0.796193009647904f, 0.215057114709867f, -0.0459498239576994f, 0.871047701509015f, 0.664672380241520f, -0.546301701630944f, -0.939910946986200f, -0.213195706858966f, 0.559543622118596f, -0.255844807516886f, 0.509576048776352f, -0.699005089750431f, -0.520317652140772f, -0.924306703712950f, -0.923814193467638f, 0.868401299001930f, -0.571229497763863f, 0.984740691690212f, -0.911782692220985f, -0.265295471266664f, 0.0479848731515942f, -0.195328058836883f, 0.758281465939343f, -0.418177229854869f, -0.263323557662932f, 0.0230762644115943f, 0.382605016442608f, -0.576209059863238f, -0.739785100410209f, 0.0956412509899256f, 0.0369702493097637f, 0.0738922616872486f, 0.589371657036664f, 0.548586250623500f, 0.996096574632666f, -0.574178408335425f, -0.827059309028347f, 0.600283403682961f, -0.0651062813338117f, 0.985857002071398f, 0.982700721670305f, 0.777628710286989f, -0.139415722014730f, 0.951156387462424f, 0.806391217144736f, 0.135433009714206f, 0.252388414319270f, 0.485541324740928f, 0.270688932431637f, 0.892850103229909f, 0.440168171407923f, 0.515384398158669f, 0.600884162546465f, 0.947986221531091f, 0.339440884303404f, 0.403857490690436f, -0.937015609644647f, 0.729529495316627f, -0.389601866986821f, -0.420712615666380f, -0.763003723744745f, -0.0619534667970105f, 0.486654476027536f, -0.943536854881494f, 0.471171699317719f, 0.996886209046820f, -0.945316270673373f, 0.230772742042993f, -0.621222111022648f, 0.838934157721328f, 0.124035987915113f, 0.737576768711407f, -0.217898078842006f, 0.0429859145211120f, 0.223685413947773f, 0.820073956039170f, -0.378381145423743f, -0.335672684173821f, 0.649791267584388f, -0.457253860252872f, -0.664776842833046f, 0.150429615666837f, 0.974812973893170f, 0.00119972362050369f, 0.140744912838368f, -0.252632269055503f, -0.124205752907507f, -0.383194456927254f, -0.356455432479067f, 0.0694989880525767f, 0.188230048541949f, -0.854592697407303f, -0.902559387772971f, 0.454054169179423f, 0.534684767654295f, 0.806837289706952f, 0.274203715752641f, -0.765433763984323f, 0.459365005291520f, -0.896797218412250f, 0.382900474341852f, 0.169400421233177f, -0.184111368111075f, 0.0323514487432812f, 0.621015577938758f, 0.139872518806323f, 0.480965263781330f, 0.0649386999855643f, 0.815365754221614f, 0.761990264098834f, -0.0927412249348933f, -0.580853742457387f, 0.211615321410605f, 0.165159968106305f, 0.305515629345863f, 0.725748395743965f, -0.667649812347274f, -0.621843189978885f, -0.939317191264789f, -0.197108718554958f, 0.902152006895939f, -0.889744652803018f, 0.667113256888905f, 0.929471703711725f, 0.660025836042506f, -0.0712223078913006f, 0.416152292126436f, -0.602223852277700f, -0.828462878627106f, -0.956915163338265f, 0.298196541541469f, -0.933863927954050f, -0.198745190221695f, 0.749101206471011f, -0.922366396086261f, 0.769953026855636f, 0.971459582749177f, -0.226637139032289f, -0.593509265485619f, -0.635649447577657, -0.443127775644156f, 0.350464269654307f, 0.379979516655134f, 0.896282784801247f, 0.00871209446887344f, 0.401818712823609f, 0.815422566258939f, 0.215868289995843f, 0.682217845700443f, 0.508819667108007f, -0.988484263336122f, 0.216656890144568f, -0.185777888700071f, 0.522106353117928f, 0.894211314619113f, -0.779300881699217f, 0.137801937535128f, -0.818740955579722f, 0.637214461095055f, 0.187867696634722f, 0.184985729971243f, 0.315323389557324f, -0.0312525033775366f, 0.498559120407008f, 0.855778208118391f, 0.936851170962385f, -0.0524308158818188f, 0.257087262622978f, 0.816141818246927f, -0.147192803443011f, 0.194545158383538f, -0.655428449892669f, -0.650441844539509f, 0.536015423540886f, 0.0250060573607953f, -0.863380305825989f, 0.0605420782823460f, -0.963662464088496f, 0.689136717877590f, -0.929664162821947f, -0.327349437742288f, 0.713122240487331f, 0.765587094162777f, -0.314350325341316f, 0.409992519686522f, 0.753377832105546f, -0.756848529995586f, 0.760787899507869f, 0.512213162407276f, -0.674820237484644f, 0.560776719592082f, -0.874905891603855f, 0.925202682923872f, -0.907405002733482f, -0.575836335118172f, -0.248173888600965f, -0.187923239740639f, 0.230951002247789f, -0.540190666146588f, 0.390890663320481f, -0.705511708249712f, 0.0980457138183717f, 0.879979753648798f, -0.378326046226794f, -0.645363625221967f, 0.883365508962968f, 0.728720763588748f, -0.191571576393619f, -0.941989254130187f, 0.944312154950866f, -0.367184985473008f, -0.974124559264444f, -0.579946765132286f, 0.509825236656578f, 0.952047194261820f, -0.0955445631918663f, -0.00500764501201401f, -0.00111382665477655f, -0.0404281661495578f, -0.265706359102834f, 0.865881843285797f, -0.947915521623861f, -0.820337973623839f, 0.0843747524022067f, -0.948599514028391f, -0.464018526769358f, 0.600790429663803f, -0.0779017384430381f, 0.756949801920938f, -0.955436496929340f, -0.553346424499498f, -0.401256107066610f, 0.569624108543687f, 0.179455179577041f, -0.189386842296675f, -0.467166492259358f, 0.367644583467601f, -0.722338735126514f, 0.863903729827081f, 0.0631027352569811f, -0.982269235503679f, -0.837788470642698f, 0.421730643738386f, -0.671745211565315f, 0.858467932275763f, -0.745298219348761f, -0.659594977600028f, 0.403238381269873f, 0.951987904652099f, 0.228887404582426f, -0.331665752024408f, 0.794789885033899f, 0.669978127515269f, 0.977583870328654f, -0.346398989178462f, 0.692053246433782f, -0.159407706019695f, 0.710808563527500f, -0.555701359319642f, 0.625665798239905f, -0.711048329414687f, -0.672431532474912f, -0.474897384314332f, -0.196250611816064f, 0.902140605659856f, -0.459732035217428f, 0.651412290305649f, -0.686137550630920f, -0.803228611526547f, 0.371120664039117f, 0.289869860968561f, -0.720979161638185f, -0.0940498575417996f, 0.185025844935128f, 0.401524077274769f, 0.811721346556136f, 0.224659861626089f, 0.106438807548742f, -0.117458956991326f, -0.407361487623449f, 0.683891165426988f, -0.216582410631386f, 0.710644530504861f, 0.867797453793643f, 0.626683550176870f, 0.115061097783331f, 0.976742668387085f, 0.250700864990527f, 0.272723539841862f, 0.159923684669346f, 0.167713264013185f, -0.445764377935606f, -0.489538472614810f, 0.227880894824940f, 0.670702116476237f, 0.610361511284318f, 0.503801949624464f, -0.687816091694902f, -0.0413765153535617f, 0.155769004545734f, 0.921910233366689f, -0.467299226678025f, -0.991984541712805f, -0.527009262324220f, 0.248157897392517f, 0.661145853979517f, -0.975947426744844f, -0.242453990684693f, -0.277956284573619f, 0.162010437415540f, 0.889456199489152f, -0.171259539670729f, -0.0636124576727060f, 0.311318764402696f, -0.227771282875219f, -0.567702050585727f, -0.132881625149059f, 0.870846950418812f, 0.440078398779761f, -0.0908818839265000f, 0.410077545060762f, 0.917678125288724f, 0.975295290129489f, 0.736514272579886f, 0.653896379317074f, -0.166512942888681f, -0.218665383726096f, -0.0688642360506688f, -0.596589868100824f, -0.180873413844075f, 0.229002598511067f, -0.647630976455599f, 0.722615884501717f, 0.760194030884127f, 0.253262836539679f, 0.0734191803957118f, -0.941427952376035f, 0.224118866807764f, 0.634990976599086f, 0.538622500570355f, -0.591487367587299f, 0.829253069890529f, 0.426659996899884f, -0.562435396124737f, 0.924178169394878f, -0.693964899988321f, -0.520472617448914f, 0.845157115508053f, 0.162984246343684f, -0.212032053476592f, 0.0482566706558292f, 0.820584028875367f, 0.676120066619505f, 0.590174358812695f, -0.457289938956925f, -0.351282540371674f, 0.322162683499620f, -0.683726196205246f, -0.279636659553935f, -0.186133028676429f, 0.965481755833750f, -0.0550172560314044f, -0.437844829991532f, -0.448670532146325f, -0.438916826946834f, 0.830205353164842f, -0.0125988502002286f, 0.733716462327519f, 0.870000673588185f, -0.189915082276716f, -0.676269331249200f, -0.336432931956768f, -0.288892891213265f, -0.912569275291884f, 0.509853767908707f, -0.658452317958678f, -0.562848133961047f, -0.102082581799095f, 0.904062026055565f, 0.473339990381854f, 0.210234896873676f, -0.0884007008398613f, 0.720872020499257f, 0.538315255331760f, -0.884485227439286f, 0.160844002639634f, 0.625863524205804f, -0.947487159926400f, 0.362643826956149f, -0.189913270725334f, -0.110428721523612f, -0.666510263156819f, -0.214827103263521f, 0.912669747474334f, -0.973896103049543f, 0.665373714127588f, 0.148135031012834f, 0.126524689644449f, 0.00283763548841764f, 0.312700495893193f, 0.579520771033243f, 0.677583023476560f, -0.779567427807191f, 0.0694994546110597f, -0.298762697062437f, 0.655210050716681f, 0.435909078048151f, 0.322095567178671f, 0.764827170021089f, -0.713736794113842f, 0.992844460358584f, -0.735915506109616f, 0.280204875392391f, 0.584446532772711f, 0.796955505835788f, 0.742508124239176f, 0.0785523490091065f, -0.562359397016753f, 0.874448473576734f, -0.794251927759664f, -0.658767152705445f, 0.120015806343044f, 0.662372174700575f, -0.719334975225296f, -0.663474261357014f, -0.637663874969148f, 0.706137632813821f, 0.734790814693796f, -0.449118755654663f, -0.758125670003823f, 0.719059339327447f, -0.228679956701166f, -0.0782671261690160f, 0.637830522744746f, -0.178696376536345f, -0.848273935253246f, 0.840882430630200f, 0.977813953976437f, 0.565474986185913f, -0.807314895274907f, -0.100534840844589f, -0.436186956483089f, 0.854663592026441f, -0.547576146320248f, -0.621784076386717f, 0.688687549426321f, -0.688962085987764f, -0.998914668418794f, 0.751493418398842f, -0.203018738091861f, -0.881317097659280f, -0.422480898609404f, -0.321074554557095f, -0.759379357125740f, -0.806503084491033f, -0.496837315822352f, 0.217087355208111f, -0.776801484423500f, -0.445747498145286f, 0.710204776554782f, 0.274276964033182f, 0.650397224484409f, -0.709395921248168f, 0.862663541330686f, -0.946166202558813f, 0.826638502366159f, -0.450587332736099f, -0.808257632193740f, -0.414360554482101f, -0.471118187583276f, 0.981592919290155f, 0.192794908371370f, -0.314979855997427f, 0.722518962804398f, -0.795914669179603f, 0.121447532644509f, 0.0446893237592363f, 0.651720955387594f, 0.897128141094619f, 0.283834144643742f, 0.369570391543943f, -0.163784005163726f, -0.799144231493300f, 0.338136741961422f, 0.795991730702685f, 0.601735561139351f, -0.556654767533027f, 0.907044495725416f, -0.374604065784494f, 0.814308532452677f, -0.254295412850351f, 0.443103437041340f, -0.0218296619602199f, 0.826728672505738f, 0.773205771668962f, 0.171909022893217f, 0.497670481959597f, 0.954178712898056f, 0.0840098577761919f, -0.705861127301893f, 0.145663865959608f, -0.436204975766037f, 0.479359595998989f, -0.719493824988072f, -0.523146212355768f, -0.917822711649927f, -0.610003715217602f, -0.192266667446473f, -0.377507163265653f, -0.250419291332051f, 0.873627391381727f, 0.922899703740095f, -0.902411671519496f, 0.285830821349708f, -0.577368595723736f, -0.598296174995687f, -0.0152478418690674f, 0.503725955636280f, 0.946501779740920f, 0.261108140547963f, 0.206258978593364f, -0.887022338332430f, 0.989187042741485f, 0.461764104690670f, 0.305280284664753f, 0.243972878436235f, -0.573704516784209f, 0.111805651228880f, -0.373590027525854f, 0.574564836347642f, -0.712884790778729f, -0.0570130063179222f, 0.244209425500712f, -0.717492787619277f, -0.476920207759357f, -0.444169983027413f, -0.254851417015366f, -0.505678630542571f, -0.953549022234155f, -0.0316841901798541f, 0.198256779602804f, 0.151938229162240f, -0.0259028503944394f, -0.799645893003010f, -0.889308912372168f, 0.339221517072804f, 0.904784479404768f, -0.367330903112591f, 0.866281762131661f, 0.112765232993802f, -0.0852946527317187f, -0.283538359072154f, -0.734951426632046f, 0.502970854898684f, -0.541434927857400f, 0.881496286285600f, -0.227404039639917f, -0.636983936776183f, -0.0799774217214970f, -0.833780310813424f, -0.222787370954425f, 0.433143783060434f, 0.0953330524947187f, 0.965400264971588f, 0.308927931247299f, 0.344316393259575f, 0.122880788538352f, -0.898509922382301f, -0.187062523329053f, 0.705352247460646f, -0.817811000761718f, 0.303714513401701f, 0.714863075518907f, -0.00862372607283035f, -0.842715848975590f, 0.816504077307885f, 0.924594085591125f, 0.334618732730041f, -0.212414743241377f, -0.758289625449925f, 0.586405661412351f, 0.909247363444287f, -0.800422609846793f, 0.397430897916299f, -0.408827454151232f, -0.411913213123543f, -0.602703152770135f, -0.893591462026327f, 0.417648762458765f, -0.766362696266534f, -0.166060103951854f, 0.883234167729589f, -0.0741908774062401f, 0.113912882075078f, -0.268248292164738f, -0.825585719915457f, 0.885446166477969f, -0.996523379251940f, -0.000841720632677401f, 0.940286529247477f, -0.528330498750176f, 0.0938880690147421f, -0.966296878893937f, 0.891956527154360f, -0.483384605653306f, 0.257210342748458f, -0.820220338820906f, 0.363913841603935f, 0.0364865250689275f, 0.0619156958713947f, -0.645447937080250f, 0.548279343062761f, -0.289526240449473f, -0.506780094171335f, -0.901771170107367f, -0.437874075223813f, 0.748512212111141f, -0.529884246718074f, 0.924062132675193f, -0.365432219122282f, -0.263296006595835f, -0.927083881647913f, -0.192737974697553f, -0.450051159199964f, -0.543528645806642f, 0.834976909049276f, -0.426975046433596f, -0.361056079272416f, 0.883880063360531f, 0.680380429911630f, -0.553642515320953f, 0.548847108935282f, -0.357430246936948f, 0.210445016993628f, 0.949511601115471f, -0.611278947360487f, 0.344744934459962f, 0.0684247970496175f, -0.877154656281116f, -0.521992702610556, -0.0303764312006813f, -0.647220068176984f, 0.693175336224119f, -0.0955602614554496f, -0.765579758912278f, -0.821318118938906f, -0.220936603794347f, 0.159013709512021f, 0.0222743973539492f, 0.569438412513281f, 0.896083437551563f, 0.973699071868637f, -0.403438951991928f, -0.976931032127622f, -0.0720613180573018f, 0.0788813367661694f, -0.430781354548607f, 0.580378296309349f, -0.175446689199481f, -0.256743557012462f, -0.696667845393283f, 0.870473046831235f, 0.146660713923108f, 0.277741407197705f, 0.502075064404417f, 0.396530064046844f, -0.000209092342246420f, -0.977003947244262f, 0.451457326960000f, 0.420509664462095f, -0.0826395067671402f, 0.461120688156973f, 0.786867285802415f, 0.429254905841222f, 0.894426863739026f, -0.670297281923597f, -0.833650409296060f, -0.908588009702110f, 0.516311115539149f, 0.975234001829324f, -0.532953533466378f, 0.775291582519158f, -0.0136022600428900f, 0.654817093112596f, 0.363512141498233f, 0.624779024037534f, 0.0237004661473674f, -0.172570506046968f, 0.401807838319043f, 0.997391258152958f, -0.553969395939123f, -0.415425175833161f, -0.758032843655304f, -0.482766088920005f, 0.637574309072414f, -0.729000055114342f, 0.699851428676091f, -0.827508053421131f, 0.900655803848482f, -0.431149800814228f, 0.0369409101983413f, -0.378608101457895f, 0.237564147838841f, 0.533020461112441f, -0.280269627508005f, -0.864065787343603f, -0.0381481642453043f, -0.566886547530062f, 0.539727700361167f, 0.166859339425035f, 0.850080295054718f, 0.384690146030125f, -0.384995288415294f, 0.303656036600558f, -0.580297619022502f, 0.0649069482840878f, -0.162922327392773f, -0.235019427063355f, -0.265468718118809f, -0.121827312187455f, 0.0416628805824146f, 0.343481543012411f, -0.251429566892972f, -0.868100204320718f, -0.802636407512128f, -0.549547579028752f, -0.570017983863503f, -0.853634311513627f, -0.564570567173235f, 0.955944215494794f, -0.0930750790375956f, -0.160319122401953f, -0.640886790354213f, 0.798634607857513f, 0.503051518023559f, 0.765247226736789f, 0.909476811674882f, 0.677590253114963f, -0.110641683440517f, -0.336445241915220f, -0.684064840782028f, 0.962285048920031f, 0.883303701653897f, 0.981819291389659f, -0.597290928759656f, 0.215792997443025f, -0.847656608719347f, 0.679887992445640f, 0.299901700372808f, -0.677306526467426f, -0.348340058872692f, 0.651490451411335f, -0.133387041637395f, 0.718311240322040f, 0.0869279817052975f, 0.155413706090559f, -0.869119988858735f, -0.566773040844476f, -0.0513826414151206f, -0.368087669232071f, -0.978175512831125f, -0.229213501073727f, 0.344608572405871f, -0.663307667219997f, 0.437238632879575f, 0.00205230197288353f, -0.0897076092856746f, 0.834529513214144f, 0.131872357342232f, 0.113081940417244f, -0.418620232731326f, -0.317993033651213f, -0.740303025960662f, 0.423423655701288f, -0.300833032468860f, -0.458960388256530f, 0.692670405117589f, -0.559944357561921f, 0.0168623577148430f, 0.568661331088367f, -0.385055363002398f, -0.356055436463140f, -0.794446573681063f, 0.908870080953069f, -0.295500656666577f, 0.800625150733729f, 0.206307902542489f, 0.729591183391974f, -0.0655746333947396f, -0.261707022686154f, -0.802380330579914f, 0.0812359238243023f, -0.00528231140765212f, -0.725740453383981f, 0.919076065030463f, -0.896497189839174f, 0.861919731820265f, -0.804273875755869f, 0.230339021648310f, 0.296779613186519f, -0.349872572510143f, -0.270230381483447f, 0.0368924200249658f, 0.581340248642417f, 0.943620537648739f, 0.715012058065301f, 0.528414993233909f, 0.695917111744314f, -0.634354198968852f, -0.483786223099716f, 0.565405035681248f, -0.530076864213017f, 0.363019522302994f, -0.825556544716473f, 0.891096876998683f, -0.990692760548295f, -0.450641405862313f, -0.597008073985341f, -0.464377765418678f, -0.942926913464693f, -0.871399725569805f, 0.232335933943403f, 0.858786794807406f, -0.528589179815518f, -0.324757177062634f, 0.595880088750788f, -0.976574570427974f, -0.423824220654658f, -0.832990206908489f, 0.198704682807118f, -0.168244652325292f, 0.843066822744011f, 0.0912498543932607f, 0.485570815146582f, -0.104653316420662f, -0.623461298489716f, -0.807713596811018f, 0.737782734425857f, 0.456364368166532f, -0.430703367862900f, -0.188953991637209f, -0.827984282695373f, 0.0246267653665548f, 0.891225605267640f, 0.910600867999638f, 0.345236086687552f, -0.600682365520065f, 0.833182106437698f, 0.213749250288017f, -0.0866339102562885f, -0.618385082289017f, 0.859527120927500f, 0.749978780964161f, -0.334770513867011f, 0.242140166670949f, -0.196268320459958f, 0.611789869603675f, 0.655057159657307f, -0.603759576722096f, 0.614654509385217f, 0.144145218488192f, 0.959930150756613f, 0.485009777784726f, -0.564230295010912f, -0.404716165405314f, 0.0442672151313601f, 0.929486639423805f, 0.409386317338224f, 0.527053707674182f, 0.899087569745327f, -0.933259779365388f, 0.265159475034860f, -0.858300862890810f, -0.870994388031662f, 0.354868177430506f, 0.00956840260511749f, 0.429740959889133f, 0.649668163567379f, -0.744532888765288f, -0.967499901569196f, 0.556703631745254f, 0.535130550118618f, -0.639502350153040f, -0.604586469532735f, 0.0799683564329623f, -0.156074786599444f, -0.348308700325411f, 0.217829052228100f, 0.545642400171123f, -0.303317700019152f, -0.473220675222451f, -0.239688108834945f, 0.0998500862725149f, -0.962734081833842f, 0.870743993144299f, 0.464578557934316f, 0.184511089576136f, 0.559729843314504f, 0.0702052363354577f, 0.632714874625648f, 0.212930743289312f, -0.454606863365109f, -0.592679055778218f, 0.287649993384466f, -0.457293694071368f, -0.423493046785686f, -0.0674763327876298f, 0.242131064298176f, 0.488581911885965f, -0.464567743213882f, -0.387515661812354f, -0.914585596974616f, -0.255803162310627f, 0.941267268311980f, 0.690278917089395f, 0.302397314111962f, -0.178461434689705f, -0.949279941481428f, 0.160440202901122f, -0.970582196769486f, -0.0119478205074164f, -0.206440255898676f, 0.221640403444713f, -0.819801447827624f, 0.263614394802488f, 0.616376195532700f, -0.596859494305351f, -0.118659509995453f, 0.458168997595326f, -0.0400474705134108f, 0.934465050133603f, -0.852936731989621f, 0.0191637795580570f, 0.298534793677081f, -0.857491630206749f, -0.0141198383157879f, -0.365027350962024f, 0.450964838023674f, 0.351383095290905f, -0.387039947149600f, -0.983994933095116f, 0.610531582220017f, -0.0446025524732094f, 0.216718014780746f, -0.676819246943449f, 0.0385619292249610f, 0.192482456707739f, -0.288809653393521f, 0.241774557042318f, -0.444638770943313f, 0.535319194413803f, 0.374773141606987f, 0.186364279454450f, 0.0701814972821988f, -0.452753172654203f, -0.350918291268194f, -0.332963791049667f, 0.179301863965318f, 0.954101654404080f, -0.687960044344130f, 0.611454049205213f, -0.696789567124132f, -0.551566492897529f, 0.656434797122885f, -0.601779335396959f, -0.265656331560395f, -0.528821434638507f, 0.153601151147409f, 0.514739334540489f, -0.0517769842323894f, -0.659246830986894f, -0.453055366696259f, -0.0515886000780059f, 0.958478845408115f, 0.0221452906045994f, -0.159960643390796f, 0.816263632871352f, 0.245244170325114f, -0.0919839688704780f, 0.947170598807362f, 0.846772793441790f, 0.247105133025056f, -0.801972939368103f, -0.224977420586025f, 0.130099925027197f, 0.497816036746753f, 0.308139730113712f, -0.0536876417759813f, -0.492022090866895f, 0.188938438822753f, -0.400894058284033f, 0.314370104391157f, 0.618580768947071f, 0.830051263404639f, -0.228700130023340f, 0.811855169643177f, 0.0924092179787017f, 0.273652523319809f, -0.0624274843235475f, -0.503696982048589f, 0.510545161203341f, 0.341823133345436f, -0.437486933663093f, 0.0134072800031224f, 0.613837993234983f, 0.740945655313894f, 0.135311460882606f, 0.464832228842466f, -0.973962843371452f, -0.519388256678232f, 0.631469277357519f, -0.936937468616713f, 0.208677911871604f, -0.0946010975796272f, 0.560587233611855f, 0.230925763372331f, -0.637408482848184f, -0.679175194353885f, -0.408696637706987f, -0.0837464598184048f, -0.911070817707239f, 0.985815432104941f, -0.208807972878988f, 0.741966810464688f, 0.162772839973564f, 0.717702638881939f, 0.490767958961575f, -0.835565390813677f, -0.878516167634055f, -0.956727838876563f, -0.00772081382858891f, 0.355227897612178f, 0.202889185809854f, -0.431078767653467f, 0.106936101717808f, 0.354494042302258f, -0.619623833602791f, 0.193065593078352f, -0.105803087758606f, 0.151828327005194f, -0.141094922099930f, 0.847569902283069f, -0.656683924792181f, -0.880754505470701f, -0.421714047610595f, 0.681762288858050f, 0.633712681698887f, 0.947060360650644f, -0.959122611588459f, -0.0690574969687099f, -0.805062392278087f, 0.226501754467861f, -0.414732397455275f, 0.242398867364043f, -0.831838824773804f, 0.00787391802290793f, -0.860692119913991f, -0.391321299589110f, -0.0548681430681355f, -0.992920640472037f, 0.0975642331777702f, 0.894630836703243f, 0.767919825689366f, -0.260878774442215f, 0.407457430171103f, 0.140688657702825f, 0.737494845272763f, -0.650969054257040f, 0.230613259000797f, -0.0986876345046772f, 0.0996951163848971f, -0.679173062298700f, -0.760174222364469f, -0.613840714529317f, -0.692138390397415f, -0.0919103790884603f, 0.0259548517830916f, 0.463763807478796f, -0.859327137970617f, 0.298600182982665f, -0.591236092977368f, -0.994984881037264f, -0.0533840054951049f, 0.544979189292485f, 0.652482875230260f, 0.897548627394727f, -0.340241293753474f, 0.508237349558163f, -0.611986702936889f, -0.399952468536369f, -0.758494484998191f, -0.148960755782999f, 0.895231513826071f, -0.870487943961511f, -0.172763884748068f, -0.652702954266129f, 0.784450103085903f, -0.428504279168614f, -0.347266234450861f, -0.0897193897382391f, 0.760686883857503f, -0.0863659842493281f, -0.453544362916610f, 0.713112885874267f, -0.529914378597266f, -0.134507787695203f, -0.590955798880753f, -0.372583442870916f, 0.646730663631020f, -0.809515553972267f, 0.0226873348847205f, -0.209338539804651f, -0.737170063193136f, 0.365916689978321f, 0.658019395382111f, 0.733982378695990f, -0.579926149814113f, 0.973814182111372f, 0.933875763922095f, -0.985234946636757f, -0.103124599698243f, -0.798304574918884f, -0.119705341414667f, 0.205941898284561f, 0.111088288053652f, 0.418598493379981f, 0.309112287901667f, 0.0865232803642195f, -0.281174085998345f, -0.158426951248790f, 0.156672456990889f, 0.608691108739118f, -0.124654784531448f, -0.372060827503666f, 0.555750853569654f, -0.481715370485256f, 0.411012047999522f, 0.265636511301544f, 0.164466400718006f, 0.427292785417094, -0.407665783814271f, 0.0463239131527564f, 0.0109249300633605f, 0.0949704798708169f, 0.223291931618591f, 0.708651599857453f, 0.810927407452143f, -0.298811874805995f, 0.347215272448441f, 0.778225160999446f, -0.981258755328673f, -0.629231280170021f, -0.948786159268210f, -0.0530522786747270f, -0.665046033882002f, 0.776993795678436f, -0.604492154463805f, -0.906360689482177f, 0.543616910115371f, -0.501547360013149f, 0.571784796850774f, 0.868511495621889f, 0.783008382563488f, 0.571870376568081f, 0.0471150346240308f, 0.402433510592678f, 0.661353159662286f, 0.0253381317208246f, 0.720141243708461f, -0.478805385943742f, 0.989639021624774f, 0.538614599364854f, -0.282810721919526f, 0.888399971333007f, 0.118572990347886f, 0.564528382703688f, 0.988296121763412f, 0.509638594649021f, -0.797738059997026f, 0.0363326380089621f, 0.978315833815278f, -0.483368013204689f, 0.879051054425480f, 0.632539830439323f, 0.722677742708361f, 0.578919286433726f, -0.250721628167261f, 0.534435049744896f, -0.0404568429105234f, 0.00805525426120179f, 0.841210870775473f, -0.731771544679396f, 0.713758914490801f, 0.830250762535296f, 0.436563669872217f, 0.567024378980237f, 0.983941121609744f, -0.253548560865555f, 0.647105012325159f, 0.434994339049196f, 0.130837710207442f, -0.775136733344706f, 0.234917279141211f, -0.498429841761386f, -0.273571256415041f, 0.247467425899991f, -0.970396693506149f, 0.975835855884816f, -0.347896516486866f, -0.552856369180847f, -0.887336234316568f, -0.573271015958957f, 0.910862901097874f, -0.807236601077904f, -0.523971593712952f, -0.263589563369279f, 0.591056276091253f, -0.320168527954128f, 0.726795865615521f, -0.731502115921006f, -0.942225519371229f, 0.268573107637337f, 0.380348127119473f, -0.284539943611895f, 0.117478291379931f, -0.817442486350524f, 0.0734705767013011f, -0.626880755668906f, -0.873066996524459f, -0.528675805715351f, 0.490255491577847f, 0.398142666604162f, -0.911320079669940f, -0.870350237514323f, 0.854587452657144f, 0.736349579728106f, 0.948232845958681f, -0.00126774478569258f, 0.905641169934000f, -0.965500575551565f, 0.0831330388550517f, -0.892713267782484f, -0.277958019172831f, 0.312987842344813f, 0.484268977417485f, -0.365960524226328f, 0.177956605738091f, 0.913776767689874f, -0.897537691614058f, 0.473075982698961f, 0.913190042662185f, -0.00843862630950820f, 0.972679442298938f, -0.856058592202917f, 0.264007224067230f, -0.138444823656136f, -0.386195416368251f, -0.286657907928107f, -0.231200657384828f, 0.917365701941188f, -0.271317547281263f, -0.252691685075831f, 0.893742787021399f, 0.512463051119608f, 0.979155111008605f, -0.472272776864686f, 0.238767541974988f, -0.672234403865928f, -0.846783135777377f, 0.0877594573148737f, 0.493055606176910f, -0.289012308379085f, 0.416463895880697f, -0.0795051375851281f, -0.476692131327163f, -0.430471976159529f, -0.701875030095239f, 0.724684336417516f, 0.984802039066595f, 0.798285421773762f, 0.000509924988974175f, -0.0852199551444761f, -0.709724122158260f, -0.332735158942919f, -0.741119907407496f, 0.729608513555970f, 0.500578022862182f, 0.520862987462710f, 0.565678561009731f, -0.393741545311224f, -0.568866018100912f, 0.571654318026290f, -0.817900961532165f, -0.793268461448962f, 0.614914392385859f, 0.763415306986536f, 0.450074180772758f, -0.737435729799608f, 0.841185794339245f, 0.894276069286366f, -0.276262284222369f, -0.798623475612628f, -0.280994234105732f, 0.821175230597885f, -0.474251640366966f, -0.190039801864015f, 0.0663032720971493f, 0.884162053156770f, -0.162023139878049f, -0.963135153785511f, -0.582213329804047f, -0.328536493809765f, -0.938405687658462f, -0.0171569611327957f, -0.727260847907578f, 0.419920927745257f, -0.361592243835530f, 0.476989471873569f, -0.146161675185107f, 0.431817832405826f, -0.371528849369885f, -0.940567978751516f, 0.165203770962029f, 0.781321525273307f, 0.0585592625092357f, 0.573299596753579f, -0.378869924017182f, 0.523139576520889f, 0.385605607116478f, -0.235893429970747f, 0.285814921067909f, -0.121941292771133f, 0.621558611608942f, -0.0860979132283732f, -0.627097832687809f, -0.312083243705910f, -0.494490796681559f, -0.987187334387934f, -0.0804474888246625f, 0.496400656176795f, -0.851811189314651f, -0.791398271297849f, -0.868174317799275f, -0.226794668997878f, -0.335339474552766f, -0.276765924750817f, -0.395876032147377f, -0.740529136126816f, -0.167799472110453f, 0.593129248263724f, 0.336783120133436f, 0.248892158925787f, 0.950120283075237f, -0.795216613504226f, -0.574731116508357f, -0.822689608026685f, 0.973698546284335f, 0.125166556654624f, 0.588150318080073f, 0.128654744345192f, -0.219207714307262f, -0.271053050307713f, 0.124071241265810f, -0.618209718015327f, -0.766619799595349f, -0.478340220431165f, -0.446873929629545f, 0.978019432749647f, -0.627041040766022f, 0.169323691066764f, -0.714079827532216f, 0.386101296128268f, -0.360225804976135f, -0.236797717782837f, -0.311635747131794f, 0.0482888201705840f, -0.477302740867809f, -0.427349080854399f, 0.390352470816329f, 0.611790541936623f, -0.648292156214605f, -0.345871618789073f, 0.509300603302844f, -0.0142202703124219f, -0.570248077753979f, -0.0629178211029751f, -0.737806048037047f, 0.497750084049821f, -0.761650107803135f, -0.788756591098617f, -0.994497286039420f, -0.987344273533962f, 0.657151987467984f, -0.763708299084062f, -0.0729359162118841f, 0.0455275633022023f, -0.101919187896584f, 0.457804242981095f, 0.0117715388281796f, -0.274125197027132f, -0.949738804931191f, 0.762108173886486f, 0.405150754308562f, -0.733330375873553f, -0.712774896799572f, -0.791947616412901f, 0.444023894424500f, 0.00507562975249609f, -0.900698136223538f, -0.576055334977054f, -0.948895529956106f, -0.832665060374124f, -0.992753953473078f, -0.0674086978315183f, 0.569494111501383f, -0.962269067721443f, -0.489700810475570f, 0.972626508328545f, -0.777400448149780f, 0.115588644128954f, 0.0730469703310024f, 0.523584488072518f, 0.659055312807301f, 0.134198234373838f, -0.797833055125151f, -0.167842823235145f, -0.662347837139732f, -0.537544370279756f, -0.622353549740796f, -0.789789664448618f, 0.985300123665319f, 0.862449845163424f, 0.973193986256980f, 0.148883268671144f, 0.283619537155083f, 0.508503183151258f, -0.246167305966866f, -0.259543094514413f, -0.778029136807597f, 0.128978622849116f, -0.920978818238085f, -0.116324837544276f, -0.261472397833253f, 0.772449038068069f, -0.696754008784325f, 0.980778877985902f, -0.227636956328402f, -0.472493776528032f, -0.568519858000960f, -0.151689463117960f, -0.102997587484899f, 0.464752146042376f, -0.839114793935065f, -0.0325074343587592f, -0.180618880765978f, 0.0132253638432844f, -0.646173464496730f, 0.821983901071593f, 0.657453744559881f, 0.786315172070382f, -0.438718096604728f, 0.702691078885442f, 0.859957412428682f, -0.505281395658564f, -0.236722160990303f, -0.698465568366759f, -0.746418979540090f, -0.218205126412646f, -0.808715244840435f, -0.949813739800491f, 0.176975348790769f, 0.723960974918154f, -0.139253733704369f, -0.387224393658603f, -0.869945438924443f, -0.396979039594941f, 0.0256060022407458f, -0.566074790002811f, -0.161564565183606f, -0.736189868188370f, -0.205593811665825f, -0.628996407588712f, -0.0266462623004120f, -0.344127255771429f, -0.229003801178142f, -0.469786561635510f, 0.258249378153965f, 0.160442939158622f, 0.0528817242116550f, 0.261960766261548f, -0.571069557415276f, 0.411333771884545f, -0.145205354714326f, 0.249324532476397f, 0.163889600722793f, 0.649915677347011f, 0.147077371087195f, -0.227104208942068f, 0.867390199578604f, -0.0734153565896754f, 0.0491208061060167f, 0.0360590744216485f, 0.181620126101180f, 0.0567549454976457f, -0.856976992549465f, -0.242511192726339f, -0.624770508991394f, -0.793161214564285f, -0.251208532727981f, -0.833192309869275f, 0.368166434661069f, 0.939730260791580f, 0.305796202211942f, -0.598830491282818f, -0.0575368190467946f, 0.371329658849021f, -0.227872714677810f, 0.707539568196379f, 0.795186297468385f, 0.475847791658551f, 0.829361555893632f, 0.405386540930889f, 0.213282954068900f, 0.767339023510319f, 0.525055513018554f, 0.259437496637378f, -0.524342591286100f, -0.731515526086696f, -0.233118783725590f, 0.237972339628935f, -0.933985285078109f, 0.537013420173496f, 0.498819465200784f, -0.407713459607516f, 0.382821417923595f, -0.416894700661466f, 0.0787266904103943f, -0.0627973593192392f, -0.320105342653426f, -0.844066834407447f, 0.138221622417319f, -0.676665423871596f, -0.961043785105959f, 0.832268610130385f, -0.905530890441773f, -0.114191325652611f, -0.376697124207843f, 0.390323137798417f, 0.953143142925101f, 0.983427991280007f, -0.0895687386326503f, -0.681543125061097f, 0.677131540142176f, -0.867715848764628f, -0.812718786220309f, -0.212509939486840f, -0.990002327123638f, -0.0682855560011961f, 0.129310729289606f, -0.623746296335073f, -0.285580241032587f, 0.235626081900812f, -0.611973228709249f, 0.539189737955466f, 0.970058678533189f, 0.901944358898624f, 0.168094826408153f, -0.666711281252260f, 0.965612752173968f, 0.651034558458719f, 0.687501917067508f, 0.758614314567106f, -0.839396045781239f, -0.552775028233564f, -0.528941743867256f, 0.174761156721889f, 0.243585712774679f, 0.588913151268911f, -0.306898192880627f, 0.921540023069231f, -0.0223654942298541f, -0.102408576957649f, 0.612577852207921f, 0.835809058447089f, -0.437118459197839f, 0.455316033239981f, 0.311435507416257f, -0.648992336007256f, 0.346823844785409f, -0.632080213667648f, -0.599678627679202f, -0.653822991854328f, 0.484305292443427f, 0.782046295685087f, 0.960987598814982f, 0.627169162605570f, 0.948092598306120f, -0.185268381817018f, 0.602489977060513f, -0.885827813790617f, -0.00179203147433582f, -0.175476447614991f, 0.0461282236560925f, -0.898013889602944f, 0.256310837914276f, -0.733422110056865f, -0.740091677658095f, 0.966724540497493f, 0.328056986822768f, -0.267854591449557f, 0.670545831663244f, -0.356204313297688f, 0.0729865206358908f, -0.594530723723669f, 0.519965324048968f, 0.0632129606097647f, -0.878434885663544f, -0.497945943395010f, 0.0151854050905818f, -0.218036856012343f, 0.547721213710874f, -0.0915514918588898f, -0.279344098401951f, -0.228654882218650f, 0.100432155997130f, 0.802024600677294f, 0.175832345686877f, 0.0551231013299744f, 0.938247319394824f, 0.639298571360036f, -0.291461603371678f, -0.853503115314794f, -0.604829242631156f, 0.0291571486740745f, -0.932575328418390f, -0.621235088415116f, 0.403040314052094f, -0.809695618266849f, 0.966605888732736f, -0.199254401023053, -0.540808222970056f, -0.0141840769249790f, 0.114579158224093f, 0.466889318471371f, -0.145415211797766f, -0.846707387707480f, -0.881237200733915f, -0.410798723199712f, -0.637697860299854f, -0.196366036081372f, 0.193267531425712f, -0.258591200841940f, -0.173003722066551f, 0.478121376006132f, 0.953819951501542f, 0.969916001975448f, 0.131515861287576f, -0.499829658784781f, 0.320952777516193f, -0.226980682212371f, 0.766886115655233f, 0.647310434110803f, -0.772594685974992f, 0.772645949480187f, -0.936357605801364f, -0.671842916281206f, -0.595127074295355f, 0.335132581825520f, 0.648964430112689f, -0.793376819398441f, -0.963663232647360f, 0.914308824314478f, -0.397663128784982f, 0.803240040231588f, -0.291039120047626f, -0.339918835846510f, -0.208620988780609f, 0.278177231697424f, -0.833157746552451f, 0.260554706029473f, -0.580537744139231f, 0.918561093477862f, 0.641368468308093f, 0.827379039283645f, -0.412231303854834f, -0.518315486749742f, 0.423356687848085f, 0.0777277584993787f, 0.394127392657178f, 0.609705410002715f, 0.264669032561337f, -0.460555696512027f, -0.0858908123066196f, -0.281781559603429f, -0.179777723960362f, -0.00449990348855067f, 0.803703377739133f, -0.155074032314596f, -0.00206139428833696f, 0.0661730930565525f, -0.737509215752079f, 0.620182143819587f, 0.114750705414661f, 0.545663051433958f, 0.661601724477194f, -0.592280382351976f, 0.609240020031149f, -0.968781019917808f, -0.668068368389875f, 0.206915551463500f, 0.0951453192552747f, 0.268580107578401f, -0.0450052302342363f, -0.933589842483940f, 0.236570492858402f, 0.0688734168318912f, 0.930163232697303f, 0.435953476823146f, 0.533759385687075f, 0.368282038662015f, -0.602312961473778f, 0.709516631712345f, -0.168303926671961f, 0.130670870119294f, -0.657736111745007f, 0.115028598388756f, 0.173728026281032f, -0.681671363429886f, -0.538786035950873f, 0.481457671665448f, 0.0136795278434168f, -0.570065342244344f, 0.188187050857249f, -0.352869308173680f, -0.979175308628854f, 0.223702879460018f, 0.994220466087713f, -0.147795166105729f, 0.218427535879435f, -0.120050826084179f, -0.0124939247430063f, -0.645134875027126f, -0.503122688484778f, 0.534123007328982f, 0.619710972635444f, -0.234248243706177f, 0.987144458053815f, 0.261284702576427f, 0.851827092094236f, 0.750019654249059f, -0.926154630610335f, 0.449356103243440f, 0.783011320523296f, -0.459228158107270f, -0.228877816937867f, 0.271108937592868f, -0.676085611673506f, 0.783114428240160f, 0.636093784021493f, -0.754110314308629f, -0.546386104880684f, 0.0385811136139234f, -0.768951137117397f, -0.644624743947807f, 0.00890157035391148f, -0.0792572116273387f, -0.989980668770044f, 0.603057533157075f, 0.280835727469123f, -0.634716709420524f, -0.712669415138995f, -0.424129916157595f, -0.436923748487354f, 0.467366013559791f, 0.907740481011987f, 0.788617065944311f, -0.152237692069130f, -0.963044404518533f, 0.907393322909416f, 0.806867676446313f, 0.699270310021791f, 0.107867603776547f, 0.127360747415417f, -0.502645789696788f, -0.511744166872327f, -0.121672719343072f, -0.596527146770249f, 0.410180172377510f, -0.852889849908704f, 0.278972213674154f, 0.0260156356783650f, 0.997558501949683f, -0.499245840292893f, -0.451169267624132f, -0.881643497362337f, 0.986957209874262f, -0.129608292321380f, 0.935829016346258f, -0.649021465281634f, 0.550436689069794f, 0.278888743082679f, 0.0137769346664500f, -0.660666060213522f, -0.416709136728042f, -0.302903068397225f, 0.180657445835459f, -0.908195955986293f, 0.280056533234627f, -0.660025789034158f, -0.798207438952561f, 0.901575224780405f, -0.608702932295102f, 0.318860199910414f, 0.874005722023406f, -0.0816057579181704f, 0.981671341873017f, -0.339234700161323f, 0.559717959858931f, 0.390363525109105f, -0.309384476087470f, 0.956563156784297f, -0.623734354817613f, -0.196627375289105f, -0.702076014509088f, 0.293098766889643f, -0.617152224560368f, 0.859117491438645f, 0.661015739867647f, 0.0747554166353739f, -0.282417009682732f, -0.667461537762524f, -0.451029960388404f, -0.464518668674360f, 0.591389440503293f, 0.552648871601186f, -0.242406315814918f, 0.147876771864331f, -0.00605730052917419f, -0.850648363553678f, -0.659957159486993f, -0.165475362851332f, 0.204150315434812f, -0.665767311591476f, -0.716154682563576f, 0.417487456932076f, 0.448184990956287f, 0.733843802413198f, -0.170228277851921f, -0.346809954182150f, 0.956058632188011f, 0.0315623945930987f, 0.509027121691627f, -0.147826185909834f, 0.717423768198044f, -0.153258078639530f, -0.586190749016474f, 0.122228033051868f, -0.884999045468193f, -0.364729711773548f, 0.0869976154696972f, -0.793532199218799f, 0.533748273468951f, -0.852754376244435f, 0.294752047699830f, 0.136764278163013f, 0.838074791168389f, 0.795224598541123f, -0.778005568697498f, -0.260924769562304f, -0.303759147861313f, 0.273726011325558f, 0.530476779331216f, 0.0866801234357086f, 0.0677702376031544f, 0.724353404182035f, -0.974710312543683f, 0.791838170482991f, 0.247768259921660f, 0.979431048271259f, -0.386992541899814f, 0.0640038231299192f, -0.00457726816166693f, 0.371455553726539f, 0.647649995487707f, 0.268304945808406f, -0.320428608173924f, 0.0927511620029309f, 0.256010036486838f, 0.740396212690346f, -0.656873241472848f, 0.823534292439413f, -0.820380362458844f, -0.453300307443023f, 0.784238355222248f, 0.912791840124321f, 0.0999478035440859f, -0.212620916988855f, 0.0170290625008669f, -0.589062380565879f, -0.171833624145497f, -0.524918122866141f, 0.961528292650892f, 0.101262818636430f, 0.941455114569308f, -0.967226220138929f, 0.616781547648562f, -0.913823148383971f, 0.274508821885917f, 0.924653374107756f, -0.866302908989783f, 0.227541907715857f, 0.0907574361370582f, -0.127499097943315f, -0.942071371521895f, -0.119419163649152f, 0.674284088819523f, 0.881328505929745f, 0.246290207551702f, 0.0547607254148590f, -0.462882918359077f, 0.888969728230585f, 0.666583509571921f, 0.238417203582380f, -0.279842248122727f, 0.855260336845903f, 0.314306869401155f, -0.188654877893078f, -0.609304918228150f, 0.169453885325888f, 0.265617874907016f, -0.943423537926184f, 0.493118676869450f, -0.386147750024858f, 0.0103920154342951f, 0.753677832518483f, 0.363353012331066f, -0.286620106520429f, -0.623332994906295f, 0.183966714365642f, -0.124278942882867f, -0.687889346448110f, -0.509002319646341f, -0.705769785650865f, 0.600586126467172f, 0.814989294939922f, 0.198959025256652f, 0.477897007911356f, 0.757957814363899f, 0.617755921094230f, -0.353589871947529f, 0.419688673189503f, -0.860584865805600f, -0.0232779635193843f, -0.789951030889387f, -0.893196700185750f, 0.610996462535201f, 0.847373590985131f, -0.989553358501822f, -0.367651771428081f, 0.741563712056747f, -0.923595352848971f, -0.580174215739367f, 0.577092000574232f, -0.910872910110270f, -0.907499077314190f, 0.692372247654077f, 0.810694134592084f, -0.608596332548047f, 0.761254615051625f, 0.0546240611947364f, -0.393956427117691f, -0.116127831535139f, -0.0352014590913388f, 0.374742194768889f, -0.927344099730091f, 0.939301337232488f, -0.969831716293845f, -0.0489333404770240f, -0.586719398908953f, 0.0235541378462407f, 0.388882981728285f, -0.0728483242295113f, 0.418280445244943f, -0.574289337805456f, -0.779962057565259f, -0.835190719754123f, 0.918717316922657f, -0.765889988109173f, -0.935310664146932f, -0.0750906135370848f, -0.256246546197534f, 0.693865929543926f, 0.592800255527084f, 0.836743344551035f, -0.801953470827580f, 0.0595524153568945f, 0.158376549012192f, -0.429364776412726f, -0.450531184162532f, -0.169317185285268f, 0.420344570579195f, -0.902838087574441f, -0.654676904337469f, 0.941802178622893f, -0.411034608875500f, -0.455381371659872f, 0.582371240315256f, -0.276150504466756f, 0.164276403376185f, -0.960238817086774f, 0.590055303394028f, -0.995185688656226f, -0.285809748360467f, -0.792066171752882f, -0.456123303649101f, -0.864169187700384f, 0.798745251308383f, -0.517673464079948f, 0.523086536900369f, 0.398784615211052f, 0.908677185333852f, -0.434846969584770f, -0.277024535706464f, 0.575800013122065f, -0.0423952171673019f, -0.327530749916683f, -0.401220909875065f, -0.232577533032385f, 0.577630268254944f, -0.733290201484409f, -0.297499739456838f, 0.166541885572822f, -0.646828619904039f, 0.0312662656272755f, 0.754145050600965f, -0.908499825108811f, 0.315379190361296f, 0.366242661082351f, 0.867903806940678f, -0.613391940567782f, 0.00760147209048068f, 0.953424134034927f, -0.812551125910811f, 0.734998935207065f, 0.781720854678504f, -0.653974423413561f, 0.612587888218526f, -0.297359914095386f, -0.409559158758694f, -0.143962230212734f, -0.814888102841114f, 0.359131810502055f, 0.356924557741016f, -0.872415989401612f, 0.716849887848809f, -0.374916928585818f, -0.0702264435280595f, 0.329843438660215f, 0.0956097573088677f, -0.937528128860310f, -0.322293489817529f, 0.781444964993177f, -0.810141738751828f, -0.150295079242497f, 0.846909181293597f, -0.128124277517711f, -0.752611695817661f, 0.839996835828451f, -0.0705685941510277f, 0.000366462394740585f, 0.0788016995849923f, -0.246053200655556f, -0.156645099915028f, -0.460752333796863f, 0.622021359864204f, 0.722871957583123f, -0.257873353238499f, -0.309810184480446f, 0.765248644407833f, -0.553316047243663f, -0.612742789838491f, 0.354017349601509f, 0.923293368553697f, 0.630695912377860f, -0.148750121613537f, -0.821801680234240f, 0.368247966228196f, 0.405416044101496f, -0.803232509711354f, -0.429778551911399f, -0.723837414527446f, -0.963925147452133f, 0.190882872226757f, 0.477008077263598f, -0.661282403679070f, 0.271643442525556f, -0.915994079618801f, 0.196564556546175f, 0.378359035245796f, 0.584016730657668f, -0.0377864332655202f, -0.327376192853106f, 0.850744189707984f, 0.799571679043808f, -0.111126908452029f, 0.525587242291601f, -0.404486180733535f, -0.134496922397279f, 0.0890128096708100f, -0.815560643303157f, -0.920166023598312f, -0.360079578314899f, -0.556238898466371f, -0.220978103133838f, -0.571530268052405f, 0.573332217175226f, -0.133862258696460f, -0.982130330352248f, -0.352538465285082f, 0.318683937697894f, -0.790927430842686f, 0.691168535237102f, 0.806014327242002f, -0.981639450008060f, 0.407200095027265f, 0.918249921845949f, 0.776880149695420f, -0.437773083955269f, -0.385117533333437f, 0.0115152415796460f, 0.687224538003991f, 0.992524870612626f, 0.471003324792228f, -0.873541777412034f, -0.560923118634380f, -0.726151823613842f, -0.538941951730010f, 0.772057551475325f, 0.858490725829641f, -0.168849338472479f }; # 102 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/fixed-point.h" fxp_t wrap(fxp_t kX, fxp_t kLowerBound, fxp_t kUpperBound) { int32_t range_size = kUpperBound - kLowerBound + 1; if (kX < kLowerBound){ kX += range_size * ((kLowerBound - kX) / range_size + 1); } return kLowerBound + (kX - kLowerBound) % range_size; } fxp_t fxp_get_int_part(fxp_t in) { return ((in < 0) ? -((-in) & _fxp_imask) : in & _fxp_imask); } fxp_t fxp_get_frac_part(fxp_t in) { return ((in < 0) ? -((-in) & _fxp_fmask) : in & _fxp_fmask); } float fxp_to_float(fxp_t fxp); fxp_t fxp_quantize(fxp_t aquant) { if (overflow_mode == 2) { if(aquant < _fxp_min) { return _fxp_min; } else if(aquant > _fxp_max) { return _fxp_max; } } else if (overflow_mode == 3) { if(aquant < _fxp_min || aquant > _fxp_max) { return wrap(aquant, _fxp_min, _fxp_max); } } return (fxp_t) aquant; } void fxp_verify_overflow(fxp_t value){ fxp_quantize(value); printf("An Overflow Occurred in system's output"); __DSVERIFIER_assert(value <= _fxp_max && value >= _fxp_min); } void fxp_verify_overflow_node(fxp_t value, char* msg){ if (1 == 2) { printf("%s",msg); __DSVERIFIER_assert(value <= _fxp_max && value >= _fxp_min); } } void fxp_verify_overflow_array(fxp_t array[], int n){ int i=0; for(i=0; i<n;i++){ fxp_verify_overflow(array[i]); } } fxp_t fxp_int_to_fxp(int in) { fxp_t lin; lin = (fxp_t) in*_fxp_one; return lin; } int fxp_to_int(fxp_t fxp) { if(fxp >= 0){ fxp += _fxp_half; } else { fxp -= _fxp_half; } fxp >>= impl.frac_bits; return (int) fxp; } fxp_t fxp_float_to_fxp(float f) { fxp_t tmp; double ftemp; ftemp = f * scale_factor[impl.frac_bits]; if(f >= 0) { tmp = (fxp_t)(ftemp + 0.5); } else { tmp = (fxp_t)(ftemp - 0.5); } return tmp; } fxp_t fxp_double_to_fxp(double value) { fxp_t tmp; double ftemp = value * scale_factor[impl.frac_bits]; if (rounding_mode == 0){ if(value >= 0) { tmp = (fxp_t)(ftemp + 0.5); } else { tmp = (fxp_t)(ftemp - 0.5); } } else if(rounding_mode == 1){ tmp = (fxp_t) ftemp; double residue = ftemp - tmp; if ((value < 0) && (residue != 0)){ ftemp = ftemp - 1; tmp = (fxp_t) ftemp; } } else if (rounding_mode == 0){ tmp = (fxp_t) ftemp; } return tmp; } void fxp_float_to_fxp_array(float f[], fxp_t r[], int N) { int i; for(i = 0; i < N; ++i) { r[i] = fxp_float_to_fxp(f[i]); } } void fxp_double_to_fxp_array(double f[], fxp_t r[], int N) { int i; for(i = 0; i < N; ++i) { r[i] = fxp_double_to_fxp(f[i]); } } # 275 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/fixed-point.h" float fxp_to_float(fxp_t fxp) { float f; int f_int = (int) fxp; f = f_int * scale_factor_inv[impl.frac_bits]; return f; } double fxp_to_double(fxp_t fxp) { double f; int f_int = (int) fxp; f = f_int * scale_factor_inv[impl.frac_bits]; return f; } void fxp_to_float_array(float f[], fxp_t r[], int N) { int i; for(i = 0; i < N; ++i) { f[i] = fxp_to_float(r[i]); } } void fxp_to_double_array(double f[], fxp_t r[], int N) { int i; for(i = 0; i < N; ++i) { f[i] = fxp_to_double(r[i]); } } fxp_t fxp_abs(fxp_t a) { fxp_t tmp; tmp = ((a < 0) ? -(fxp_t)(a) : a); tmp = fxp_quantize(tmp); return tmp; } fxp_t fxp_add(fxp_t aadd, fxp_t badd) { fxp_t tmpadd; tmpadd = ((fxp_t)(aadd) + (fxp_t)(badd)); tmpadd = fxp_quantize(tmpadd); return tmpadd; } fxp_t fxp_sub(fxp_t asub, fxp_t bsub) { fxp_t tmpsub; tmpsub = (fxp_t)((fxp_t)(asub) - (fxp_t)(bsub)); tmpsub = fxp_quantize(tmpsub); return tmpsub; } fxp_t fxp_mult(fxp_t amult, fxp_t bmult) { fxp_t tmpmult, tmpmultprec; tmpmult = (fxp_t)((fxp_t)(amult)*(fxp_t)(bmult)); if (tmpmult >= 0) { tmpmultprec = (tmpmult + ((tmpmult & 1 << (impl.frac_bits - 1)) << 1)) >> impl.frac_bits; } else { tmpmultprec = -(((-tmpmult) + (((-tmpmult) & 1 << (impl.frac_bits - 1)) << 1)) >> impl.frac_bits); } tmpmultprec = fxp_quantize(tmpmultprec); return tmpmultprec; } # 372 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/fixed-point.h" fxp_t fxp_div(fxp_t a, fxp_t b){ __DSVERIFIER_assume( b!=0 ); fxp_t tmpdiv = ((a << impl.frac_bits) / b); tmpdiv = fxp_quantize(tmpdiv); return tmpdiv; } fxp_t fxp_neg(fxp_t aneg) { fxp_t tmpneg; tmpneg = -(fxp_t)(aneg); tmpneg = fxp_quantize(tmpneg); return tmpneg; } # 398 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/fixed-point.h" fxp_t fxp_sign(fxp_t a) { return ((a == 0) ? 0 : ((a < 0) ? _fxp_minus_one : _fxp_one) ); } fxp_t fxp_shrl(fxp_t in, int shift) { return (fxp_t) (((unsigned int) in) >> shift); } fxp_t fxp_square(fxp_t a) { return fxp_mult(a, a); } void fxp_print_int(fxp_t a) { printf("\n%i", (int32_t)a); } void fxp_print_float(fxp_t a) { printf("\n%f", fxp_to_float(a)); } void fxp_print_float_array(fxp_t a[], int N) { int i; for(i = 0; i < N; ++i) { printf("\n%f", fxp_to_float(a[i])); } } void print_fxp_array_elements(char * name, fxp_t * v, int n){ printf("%s = {", name); int i; for(i=0; i < n; i++){ printf(" %jd ", v[i]); } printf("}\n"); } # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" 1 # 24 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" void initialize_array(double v[], int n){ int i; for(i=0; i<n; i++){ v[i] = 0; } } void revert_array(double v[], double out[], int n){ initialize_array(out,n); int i; for(i=0; i<n; i++){ out[i] = v[n-i-1]; } } double internal_pow(double a, double b){ int i; double acc = 1; for (i=0; i < b; i++){ acc = acc*a; } return acc; } double internal_abs(double a){ return a < 0 ? -a : a; } int fatorial(int n){ return n == 0 ? 1 : n * fatorial(n-1); } int check_stability(double a[], int n){ int lines = 2 * n - 1; int columns = n; double m[lines][n]; int i,j; double current_stability[n]; for (i=0; i < n; i++){ current_stability[i] = a[i]; } double sum = 0; for (i=0; i < n; i++){ sum += a[i]; } if (sum <= 0){ printf("[DEBUG] the first constraint of Jury criteria failed: (F(1) > 0)"); return 0; } sum = 0; for (i=0; i < n; i++){ sum += a[i] * internal_pow(-1, n-1-i); } sum = sum * internal_pow(-1, n-1); if (sum <= 0){ printf("[DEBUG] the second constraint of Jury criteria failed: (F(-1)*(-1)^n > 0)"); return 0; } if (internal_abs(a[n-1]) > a[0]){ printf("[DEBUG] the third constraint of Jury criteria failed: (abs(a0) < a_{n}*z^{n})"); return 0; } for (i=0; i < lines; i++){ for (j=0; j < columns; j++){ m[i][j] = 0; } } for (i=0; i < lines; i++){ for (j=0; j < columns; j++){ if (i == 0){ m[i][j] = a[j]; continue; } if (i % 2 != 0 ){ int x; for(x=0; x<columns;x++){ m[i][x] = m[i-1][columns-x-1]; } columns = columns - 1; j = columns; }else{ m[i][j] = m[i-2][j] - (m[i-2][columns] / m[i-2][0]) * m[i-1][j]; } } } int first_is_positive = m[0][0] >= 0 ? 1 : 0; for (i=0; i < lines; i++){ if (i % 2 == 0){ int line_is_positive = m[i][0] >= 0 ? 1 : 0; if (first_is_positive != line_is_positive){ return 0; } continue; } } return 1; } void poly_sum(double a[], int Na, double b[], int Nb, double ans[], int Nans){ int i; Nans = Na>Nb? Na:Nb; for (i=0; i<Nans; i++){ if (Na>Nb){ ans[i]=a[i]; if (i > Na-Nb-1){ ans[i]=ans[i]+b[i-Na+Nb]; } }else { ans[i]=b[i]; if (i> Nb - Na -1){ ans[i]=ans[i]+a[i-Nb+Na]; } } } } void poly_mult(double a[], int Na, double b[], int Nb, double ans[], int Nans){ int i; int j; int k; Nans = Na+Nb-1; for (i=0; i<Na; i++){ for (j=0; j<Nb; j++){ k= Na + Nb - i - j - 2; ans[k]=0; } } for (i=0; i<Na; i++){ for (j=0; j<Nb; j++){ k= Na + Nb - i - j - 2; ans[k]=ans[k]+a[Na - i - 1]*b[Nb - j - 1]; } } } void double_check_oscillations(double * y, int y_size){ __DSVERIFIER_assume(y[0] != y[y_size - 1]); int window_timer = 0; int window_count = 0; int i, j; for (i = 2; i < y_size; i++){ int window_size = i; for(j=0; j<y_size; j++){ if (window_timer > window_size){ window_timer = 0; window_count = 0; } int window_index = j + window_size; if (window_index < y_size){ if (y[j] == y[window_index]){ window_count++; # 209 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" 3 4 ((void) sizeof (( # 209 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" !(window_count == window_size) # 209 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 209 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" !(window_count == window_size) # 209 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" 3 4 ) ; else __assert_fail ( # 209 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" "!(window_count == window_size)" # 209 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h", 209, __extension__ __PRETTY_FUNCTION__); })) # 209 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/util.h" ; } }else{ break; } window_timer++; } } } void double_check_limit_cycle(double * y, int y_size){ double reference = y[y_size - 1]; int idx = 0; int window_size = 1; for(idx = (y_size-2); idx >= 0; idx--){ if (y[idx] != reference){ window_size++; }else{ break; } } __DSVERIFIER_assume(window_size != y_size && window_size != 1); printf("window_size %d\n", window_size); int desired_elements = 2 * window_size; int found_elements = 0; for(idx = (y_size-1); idx >= 0; idx--){ if (idx > (y_size-window_size-1)){ printf("%.0f == %.0f\n", y[idx], y[idx-window_size]); int cmp_idx = idx - window_size; if ((cmp_idx > 0) && (y[idx] == y[idx-window_size])){ found_elements = found_elements + 2; }else{ break; } } } printf("desired_elements %d\n", desired_elements); printf("found_elements %d\n", found_elements); __DSVERIFIER_assert(desired_elements != found_elements); } void double_check_persistent_limit_cycle(double * y, int y_size){ int idy = 0; int count_same = 0; int window_size = 0; double reference = y[0]; for(idy = 0; idy < y_size; idy++){ if (y[idy] != reference){ window_size++; } else if (window_size != 0){ break; } else { count_same++; } } window_size += count_same; __DSVERIFIER_assume(window_size > 1 && window_size <= y_size/2); double lco_elements[window_size]; for(idy = 0; idy < y_size; idy++){ if (idy < window_size){ lco_elements[idy] = y[idy]; } } idy = 0; int lco_idy = 0; _Bool is_persistent = 0; while (idy < y_size){ if(y[idy++] == lco_elements[lco_idy++]){ is_persistent = 1; }else{ is_persistent = 0; break; } if (lco_idy == window_size){ lco_idy = 0; } } __DSVERIFIER_assert(is_persistent == 0); } void print_array_elements(char * name, double * v, int n){ printf("%s = {", name); int i; for(i=0; i < n; i++){ printf(" %.32f ", v[i]); } printf("}\n"); } void double_add_matrix( unsigned int lines, unsigned int columns, double m1[4][4], double m2[4][4], double result[4][4]){ unsigned int i, j; for (i = 0; i < lines; i++){ for (j = 0; j < columns; j++){ result[i][j] = m1[i][j] + m2[i][j]; } } } void double_sub_matrix( unsigned int lines, unsigned int columns, double m1[4][4], double m2[4][4], double result[4][4]){ unsigned int i, j; for (i = 0; i < lines; i++){ for (j = 0; j < columns; j++){ result[i][j] = m1[i][j] - m2[i][j]; } } } void double_matrix_multiplication( unsigned int i1, unsigned int j1, unsigned int i2, unsigned int j2, double m1[4][4], double m2[4][4], double m3[4][4]){ unsigned int i, j, k; if (j1 == i2) { for (i=0; i<i1; i++) { for (j=0; j<j2; j++) { m3[i][j] = 0; } } for (i=0;i<i1; i++) { for (j=0; j<j2; j++) { for (k=0; k<j1; k++) { double mult = (m1[i][k] * m2[k][j]); m3[i][j] = m3[i][j] + (m1[i][k] * m2[k][j]); } } } } else { printf("\nError! Operation invalid, please enter with valid matrices.\n"); } } void fxp_matrix_multiplication( unsigned int i1, unsigned int j1, unsigned int i2, unsigned int j2, fxp_t m1[4][4], fxp_t m2[4][4], fxp_t m3[4][4]){ unsigned int i, j, k; if (j1 == i2) { for (i=0; i<i1; i++) { for (j=0; j<j2; j++) { m3[i][j] = 0; } } for (i=0;i<i1; i++) { for (j=0; j<j2; j++) { for (k=0; k<j1; k++) { m3[i][j] = fxp_add( m3[i][j], fxp_mult(m1[i][k] , m2[k][j])); } } } } else { printf("\nError! Operation invalid, please enter with valid matrices.\n"); } } void fxp_exp_matrix(unsigned int lines, unsigned int columns, fxp_t m1[4][4], unsigned int expNumber, fxp_t result[4][4]){ unsigned int i, j, l, k; fxp_t m2[4][4]; if(expNumber == 0){ for (i = 0; i < lines; i++){ for (j = 0; j < columns; j++){ if(i == j){ result[i][j] = fxp_double_to_fxp(1.0); } else { result[i][j] = 0.0; } } } return; } for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) result[i][j] = m1[i][j]; if(expNumber == 1){ return; } for(l = 1; l < expNumber; l++){ for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) m2[i][j] = result[i][j]; for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) result[i][j] = 0; for (i=0;i<lines; i++) { for (j=0; j<columns; j++) { for (k=0; k<columns; k++) { result[i][j] = fxp_add( result[i][j], fxp_mult(m2[i][k] , m1[k][j])); } } } } } void double_exp_matrix(unsigned int lines, unsigned int columns, double m1[4][4], unsigned int expNumber, double result[4][4]){ unsigned int i, j, k, l; double m2[4][4]; if(expNumber == 0){ for (i = 0; i < lines; i++){ for (j = 0; j < columns; j++){ if(i == j){ result[i][j] = 1.0; } else { result[i][j] = 0.0; } } } return; } for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) result[i][j] = m1[i][j]; if(expNumber == 1){ return; } for(l = 1; l < expNumber; l++){ for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) m2[i][j] = result[i][j]; for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) result[i][j] = 0; for (i=0;i<lines; i++) { for (j=0; j<columns; j++) { for (k=0; k<columns; k++) { result[i][j] = result[i][j] + (m2[i][k] * m1[k][j]); } } } } } void fxp_add_matrix( unsigned int lines, unsigned int columns, fxp_t m1[4][4], fxp_t m2[4][4], fxp_t result[4][4]){ unsigned int i, j; for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) { result[i][j] = fxp_add(m1[i][j] , m2[i][j]); } } void fxp_sub_matrix( unsigned int lines, unsigned int columns, fxp_t m1[4][4], fxp_t m2[4][4], fxp_t result[4][4]){ unsigned int i, j; for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) result[i][j] = fxp_sub(m1[i][j] , m2[i][j]); } void print_matrix(double matrix[4][4], unsigned int lines, unsigned int columns){ printf("\nMatrix\n=====================\n\n"); unsigned int i, j; for (i=0; i<lines; i++) { for (j=0; j<columns; j++) { printf("#matrix[%d][%d]: %2.2f ", i,j,matrix[i][j]); } printf("\n"); } printf("\n"); } double determinant(double a[4][4],int n) { int i,j,j1,j2; double det = 0; double m[4][4]; if (n < 1) { } else if (n == 1) { det = a[0][0]; } else if (n == 2) { det = a[0][0] * a[1][1] - a[1][0] * a[0][1]; } else { det = 0; for (j1=0;j1<n;j1++) { for (i=0;i<n-1;i++) for (i=1;i<n;i++) { j2 = 0; for (j=0;j<n;j++) { if (j == j1) continue; m[i-1][j2] = a[i][j]; j2++; } } det += internal_pow(-1.0,1.0+j1+1.0) * a[0][j1] * determinant(m,n-1); } } return(det); } double fxp_determinant(fxp_t a_fxp[4][4],int n) { int i,j,j1,j2; double a[4][4]; for(i=0; i<n;i++){ for(j=0; j<n;j++){ a[i][j]= fxp_to_double(a_fxp[i][j]); } } double det = 0; double m[4][4]; if (n < 1) { } else if (n == 1) { det = a[0][0]; } else if (n == 2) { det = a[0][0] * a[1][1] - a[1][0] * a[0][1]; } else { det = 0; for (j1=0;j1<n;j1++) { for (i=0;i<n-1;i++) for (i=1;i<n;i++) { j2 = 0; for (j=0;j<n;j++) { if (j == j1) continue; m[i-1][j2] = a[i][j]; j2++; } } det += internal_pow(-1.0,1.0+j1+1.0) * a[0][j1] * determinant(m,n-1); } } return(det); } void transpose(double a[4][4], double b[4][4],int n, int m) { int i,j; for (i=0;i<n;i++) { for (j=0;j<m;j++) { b[j][i] = a[i][j]; } } } void fxp_transpose(fxp_t a[4][4], fxp_t b[4][4],int n, int m) { int i,j; for (i=0;i<n;i++) { for (j=0;j<m;j++) { b[j][i] = a[i][j]; } } } # 24 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 1 # 19 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" extern int generic_timer; extern hardware hw; double generic_timing_shift_l_double(double zIn, double z[], int N) { generic_timer += ((2 * hw.assembly.push) + (3 * hw.assembly.in) + (3 * hw.assembly.out) + (1 * hw.assembly.sbiw) + (1 * hw.assembly.cli) + (8 * hw.assembly.std)); int i; double zOut; zOut = z[0]; generic_timer += ((5 * hw.assembly.ldd) + (2 * hw.assembly.mov) + (4 * hw.assembly.std) + (1 * hw.assembly.ld)); generic_timer += ((2 * hw.assembly.std) + (1 * hw.assembly.rjmp)); for (i = 0; i < N - 1; i++) { generic_timer += ((17 * hw.assembly.ldd) + (4 * hw.assembly.lsl) + (4 * hw.assembly.rol) + (2 * hw.assembly.add) + (2 * hw.assembly.adc) + (6 * hw.assembly.mov) + (2 * hw.assembly.adiw) + (5 * hw.assembly.std) + (1 * hw.assembly.ld) + (1 * hw.assembly.st) + (1 * hw.assembly.subi) + (1 * hw.assembly.sbc)+ (1 * hw.assembly.cp) + (1 * hw.assembly.cpc) + (1 * hw.assembly.brlt)); z[i] = z[i + 1]; } z[N - 1] = zIn; generic_timer += ((12 * hw.assembly.ldd) + (6 * hw.assembly.mov) + (3 * hw.assembly.std) + (2 * hw.assembly.lsl) + (2 * hw.assembly.rol) + (1 * hw.assembly.adc) + (1 * hw.assembly.add) + (1 * hw.assembly.subi) + (1 * hw.assembly.sbci) + (1 * hw.assembly.st) + (1 * hw.assembly.adiw) + (1 * hw.assembly.in)+ (1 * hw.assembly.cli)); generic_timer += ((3 * hw.assembly.out) + (2 * hw.assembly.pop) + (1 * hw.assembly.ret)); return (zOut); } double generic_timing_shift_r_double(double zIn, double z[], int N) { generic_timer += ((2 * hw.assembly.push) + (3 * hw.assembly.in) + (3 * hw.assembly.out) + (1 * hw.assembly.sbiw) + (1 * hw.assembly.cli) + (8 * hw.assembly.std)); int i; double zOut; zOut = z[N - 1]; generic_timer += ((7 * hw.assembly.ldd) + (2 * hw.assembly.rol) + (2 * hw.assembly.lsl) + (2 * hw.assembly.mov) + (4 * hw.assembly.std) + (1 * hw.assembly.add) + (1 * hw.assembly.adc) + (1 * hw.assembly.ld) + (1 * hw.assembly.subi) + (1 * hw.assembly.sbci)); generic_timer += ((2 * hw.assembly.ldd) + (2 * hw.assembly.std) + (1 * hw.assembly.sbiw) + (1 * hw.assembly.rjmp)); for (i = N - 1; i > 0; i--) { z[i] = z[i - 1]; generic_timer += ((15 * hw.assembly.ldd) + (4 * hw.assembly.lsl) + (4 * hw.assembly.rol) + (2 * hw.assembly.add) + (2 * hw.assembly.adc) + (4 * hw.assembly.mov) + (5 * hw.assembly.std) + (1 * hw.assembly.subi) + (1 * hw.assembly.sbci) + (1 * hw.assembly.ld) + (1 * hw.assembly.st) + (1 * hw.assembly.sbiw) + (1 * hw.assembly.cp) + (1 * hw.assembly.cpc) + (1 * hw.assembly.brlt)); } z[0] = zIn; generic_timer += ((10 * hw.assembly.ldd) + (5 * hw.assembly.mov) + (3 * hw.assembly.std) + (3 * hw.assembly.out) + (2 * hw.assembly.pop) + (1 * hw.assembly.ret) + (1 * hw.assembly.ret) + (1 * hw.assembly.cli) + (1 * hw.assembly.in) + (1 * hw.assembly.st) + (1 * hw.assembly.adiw)); return zOut; } fxp_t shiftL(fxp_t zIn, fxp_t z[], int N) { int i; fxp_t zOut; zOut = z[0]; for (i = 0; i < N - 1; i++) { z[i] = z[i + 1]; } z[N - 1] = zIn; return (zOut); } fxp_t shiftR(fxp_t zIn, fxp_t z[], int N) { int i; fxp_t zOut; zOut = z[N - 1]; for (i = N - 1; i > 0; i--) { z[i] = z[i - 1]; } z[0] = zIn; return zOut; } float shiftLfloat(float zIn, float z[], int N) { int i; float zOut; zOut = z[0]; for (i = 0; i < N - 1; i++) { z[i] = z[i + 1]; } z[N - 1] = zIn; return (zOut); } float shiftRfloat(float zIn, float z[], int N) { int i; float zOut; zOut = z[N - 1]; for (i = N - 1; i > 0; i--) { z[i] = z[i - 1]; } z[0] = zIn; return zOut; } double shiftRDdouble(double zIn, double z[], int N) { int i; double zOut; zOut = z[0]; for (i = 0; i < N - 1; i++) { z[i] = z[i + 1]; } z[N - 1] = zIn; return (zOut); } double shiftRdouble(double zIn, double z[], int N) { int i; double zOut; zOut = z[N - 1]; for (i = N - 1; i > 0; i--) { z[i] = z[i - 1]; } z[0] = zIn; return zOut; } double shiftLDouble(double zIn, double z[], int N) { int i; double zOut; zOut = z[0]; for (i = 0; i < N - 1; i++) { z[i] = z[i + 1]; } z[N - 1] = zIn; return (zOut); } void shiftLboth(float zfIn, float zf[], fxp_t zIn, fxp_t z[], int N) { int i; fxp_t zOut; float zfOut; zOut = z[0]; zfOut = zf[0]; for (i = 0; i < N - 1; i++) { z[i] = z[i + 1]; zf[i] = zf[i + 1]; } z[N - 1] = zIn; zf[N - 1] = zfIn; } void shiftRboth(float zfIn, float zf[], fxp_t zIn, fxp_t z[], int N) { int i; fxp_t zOut; float zfOut; zOut = z[N - 1]; zfOut = zf[N - 1]; for (i = N - 1; i > 0; i--) { z[i] = z[i - 1]; zf[i] = zf[i - 1]; } z[0] = zIn; zf[0] = zfIn; } int order(int Na, int Nb) { return Na > Nb ? Na - 1 : Nb - 1; } void fxp_check_limit_cycle(fxp_t y[], int y_size){ fxp_t reference = y[y_size - 1]; int idx = 0; int window_size = 1; for(idx = (y_size-2); idx >= 0; idx--){ if (y[idx] != reference){ window_size++; }else{ break; } } __DSVERIFIER_assume(window_size != y_size && window_size != 1); printf("window_size %d\n", window_size); int desired_elements = 2 * window_size; int found_elements = 0; for(idx = (y_size-1); idx >= 0; idx--){ if (idx > (y_size-window_size-1)){ printf("%.0f == %.0f\n", y[idx], y[idx-window_size]); int cmp_idx = idx - window_size; if ((cmp_idx > 0) && (y[idx] == y[idx-window_size])){ found_elements = found_elements + 2; }else{ break; } } } __DSVERIFIER_assume(found_elements > 0); printf("desired_elements %d\n", desired_elements); printf("found_elements %d\n", found_elements); __DSVERIFIER_assume(found_elements == desired_elements); __DSVERIFIER_assert(0); } void fxp_check_persistent_limit_cycle(fxp_t * y, int y_size){ int idy = 0; int count_same = 0; int window_size = 0; fxp_t reference = y[0]; for(idy = 0; idy < y_size; idy++){ if (y[idy] != reference){ window_size++; } else if (window_size != 0){ break; } else { count_same++; } } window_size += count_same; __DSVERIFIER_assume(window_size > 1 && window_size <= y_size/2); fxp_t lco_elements[window_size]; for(idy = 0; idy < y_size; idy++){ if (idy < window_size){ lco_elements[idy] = y[idy]; } } idy = 0; int lco_idy = 0; _Bool is_persistent = 0; while (idy < y_size){ if(y[idy++] == lco_elements[lco_idy++]){ is_persistent = 1; }else{ is_persistent = 0; break; } if (lco_idy == window_size){ lco_idy = 0; } } __DSVERIFIER_assert(is_persistent == 0); } void fxp_check_oscillations(fxp_t y[] , int y_size){ __DSVERIFIER_assume((y[0] != y[y_size - 1]) && (y[y_size - 1] != y[y_size - 2])); int window_timer = 0; int window_count = 0; int i, j; for (i = 2; i < y_size; i++){ int window_size = i; for(j=0; j<y_size; j++){ if (window_timer > window_size){ window_timer = 0; window_count = 0; } int window_index = j + window_size; if (window_index < y_size){ if (y[j] == y[window_index]){ window_count++; __DSVERIFIER_assert(!(window_count == window_size)); } }else{ break; } window_timer++; } } } int fxp_ln(int x) { int t, y; y = 0xa65af; if (x < 0x00008000) x <<= 16, y -= 0xb1721; if (x < 0x00800000) x <<= 8, y -= 0x58b91; if (x < 0x08000000) x <<= 4, y -= 0x2c5c8; if (x < 0x20000000) x <<= 2, y -= 0x162e4; if (x < 0x40000000) x <<= 1, y -= 0x0b172; t = x + (x >> 1); if ((t & 0x80000000) == 0) x = t, y -= 0x067cd; t = x + (x >> 2); if ((t & 0x80000000) == 0) x = t, y -= 0x03920; t = x + (x >> 3); if ((t & 0x80000000) == 0) x = t, y -= 0x01e27; t = x + (x >> 4); if ((t & 0x80000000) == 0) x = t, y -= 0x00f85; t = x + (x >> 5); if ((t & 0x80000000) == 0) x = t, y -= 0x007e1; t = x + (x >> 6); if ((t & 0x80000000) == 0) x = t, y -= 0x003f8; t = x + (x >> 7); if ((t & 0x80000000) == 0) x = t, y -= 0x001fe; x = 0x80000000 - x; y -= x >> 15; return y; } double fxp_log10_low(double x) { int xint = (int) (x * 65536.0 + 0.5); int lnum = fxp_ln(xint); int lden = fxp_ln(655360); return ((double) lnum / (double) lden); } double fxp_log10(double x) { if (x > 32767.0) { if (x > 1073676289.0) { x = x / 1073676289.0; return fxp_log10_low(x) + 9.030873362; } x = x / 32767.0; return fxp_log10_low(x) + 4.515436681; } return fxp_log10_low(x); } float snrVariance(float s[], float n[], int blksz) { int i; double sm = 0, nm = 0, sv = 0, nv = 0, snr; for (i = 0; i < blksz; i++) { sm += s[i]; nm += n[i]; } sm /= blksz; nm /= blksz; for (i = 0; i < blksz; i++) { sv += (s[i] - sm) * (s[i] - sm); nv += (n[i] - nm) * (n[i] - nm); } if (nv != 0.0f) { # 373 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ((void) sizeof (( # 373 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" sv >= nv # 373 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 373 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" sv >= nv # 373 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ; else __assert_fail ( # 373 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" "sv >= nv" # 373 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h", 373, __extension__ __PRETTY_FUNCTION__); })) # 373 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" ; snr = sv / nv; return snr; } else { return 9999.9f; } } float snrPower(float s[], float n[], int blksz) { int i; double sv = 0, nv = 0, snr; for (i = 0; i < blksz; i++) { sv += s[i] * s[i]; nv += n[i] * n[i]; } if (nv != 0.0f) { # 394 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ((void) sizeof (( # 394 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" sv >= nv # 394 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 394 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" sv >= nv # 394 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ; else __assert_fail ( # 394 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" "sv >= nv" # 394 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h", 394, __extension__ __PRETTY_FUNCTION__); })) # 394 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" ; snr = sv / nv; return snr; } else { return 9999.9f; } } float snrPoint(float s[], float n[], int blksz) { int i; double ratio = 0, power = 0; for (i = 0; i < blksz; i++) { if(n[i] == 0) continue; ratio = s[i] / n[i]; if(ratio > 150.0f || ratio < -150.0f) continue; power = ratio * ratio; # 412 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ((void) sizeof (( # 412 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" power >= 1.0f # 412 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 412 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" power >= 1.0f # 412 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ; else __assert_fail ( # 412 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" "power >= 1.0f" # 412 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h", 412, __extension__ __PRETTY_FUNCTION__); })) # 412 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" ; } return 9999.9f; } unsigned long next = 1; int rand(void) { next = next*1103515245 + 12345; return (unsigned int)(next/65536) % 32768; } void srand(unsigned int seed) { next = seed; } float iirIIOutTime(float w[], float x, float a[], float b[], int Na, int Nb) { int timer1 = 0; float *a_ptr, *b_ptr, *w_ptr; float sum = 0; a_ptr = &a[1]; b_ptr = &b[0]; w_ptr = &w[1]; int k, j; timer1 += 71; for (j = 1; j < Na; j++) { w[0] -= *a_ptr++ * *w_ptr++; timer1 += 54; } w[0] += x; w_ptr = &w[0]; for (k = 0; k < Nb; k++) { sum += *b_ptr++ * *w_ptr++; timer1 += 46; } timer1 += 38; # 450 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ((void) sizeof (( # 450 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" (double)timer1*1 / 16000000 <= (double)1 / 100 # 450 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 450 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" (double)timer1*1 / 16000000 <= (double)1 / 100 # 450 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ; else __assert_fail ( # 450 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" "(double)timer1*CYCLE <= (double)DEADLINE" # 450 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h", 450, __extension__ __PRETTY_FUNCTION__); })) # 450 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" ; return sum; } float iirIItOutTime(float w[], float x, float a[], float b[], int Na, int Nb) { int timer1 = 0; float *a_ptr, *b_ptr; float yout = 0; a_ptr = &a[1]; b_ptr = &b[0]; int Nw = Na > Nb ? Na : Nb; yout = (*b_ptr++ * x) + w[0]; int j; timer1 += 105; for (j = 0; j < Nw - 1; j++) { w[j] = w[j + 1]; if (j < Na - 1) { w[j] -= *a_ptr++ * yout; timer1 += 41; } if (j < Nb - 1) { w[j] += *b_ptr++ * x; timer1 += 38; } timer1 += 54; } timer1 += 7; # 477 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ((void) sizeof (( # 477 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" (double)timer1*1 / 16000000 <= (double)1 / 100 # 477 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 477 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" (double)timer1*1 / 16000000 <= (double)1 / 100 # 477 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ; else __assert_fail ( # 477 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" "(double)timer1*CYCLE <= (double)DEADLINE" # 477 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h", 477, __extension__ __PRETTY_FUNCTION__); })) # 477 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" ; return yout; } double iirIItOutTime_double(double w[], double x, double a[], double b[], int Na, int Nb) { int timer1 = 0; double *a_ptr, *b_ptr; double yout = 0; a_ptr = &a[1]; b_ptr = &b[0]; int Nw = Na > Nb ? Na : Nb; yout = (*b_ptr++ * x) + w[0]; int j; timer1 += 105; for (j = 0; j < Nw - 1; j++) { w[j] = w[j + 1]; if (j < Na - 1) { w[j] -= *a_ptr++ * yout; timer1 += 41; } if (j < Nb - 1) { w[j] += *b_ptr++ * x; timer1 += 38; } timer1 += 54; } timer1 += 7; # 504 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ((void) sizeof (( # 504 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" (double)timer1*1 / 16000000 <= (double)1 / 100 # 504 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 504 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" (double)timer1*1 / 16000000 <= (double)1 / 100 # 504 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 ) ; else __assert_fail ( # 504 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" "(double)timer1*CYCLE <= (double)DEADLINE" # 504 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h", 504, __extension__ __PRETTY_FUNCTION__); })) # 504 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/functions.h" ; return yout; } void iirOutBoth(float yf[], float xf[], float af[], float bf[], float *sumf_ref, fxp_t y[], fxp_t x[], fxp_t a[], fxp_t b[], fxp_t *sum_ref, int Na, int Nb) { fxp_t *a_ptr, *y_ptr, *b_ptr, *x_ptr; float *af_ptr, *yf_ptr, *bf_ptr, *xf_ptr; fxp_t sum = 0; float sumf = 0; a_ptr = &a[1]; y_ptr = &y[Na - 1]; b_ptr = &b[0]; x_ptr = &x[Nb - 1]; af_ptr = &af[1]; yf_ptr = &yf[Na - 1]; bf_ptr = &bf[0]; xf_ptr = &xf[Nb - 1]; int i, j; for (i = 0; i < Nb; i++) { sum = fxp_add(sum, fxp_mult(*b_ptr++, *x_ptr--)); sumf += *bf_ptr++ * *xf_ptr--; } for (j = 1; j < Na; j++) { sum = fxp_sub(sum, fxp_mult(*a_ptr++, *y_ptr--)); sumf -= *af_ptr++ * *yf_ptr--; } *sum_ref = sum; *sumf_ref = sumf; } fxp_t iirOutFixedL(fxp_t y[], fxp_t x[], fxp_t xin, fxp_t a[], fxp_t b[], int Na, int Nb) { fxp_t *a_ptr, *y_ptr, *b_ptr, *x_ptr; fxp_t sum = 0; a_ptr = &a[Na - 1]; y_ptr = &y[1]; b_ptr = &b[Nb - 1]; x_ptr = &x[0]; int i, j; for (i = 0; i < Nb - 1; i++) { x[i] = x[i+1]; sum = fxp_add(sum, fxp_mult(*b_ptr--, *x_ptr++)); } x[Nb - 1] = xin; sum = fxp_add(sum, fxp_mult(*b_ptr--, *x_ptr++)); for (j = 1; j < Na - 1; j++) { sum = fxp_sub(sum, fxp_mult(*a_ptr--, *y_ptr++)); y[j] = y[j+1]; } if(Na>1) sum = fxp_sub(sum, fxp_mult(*a_ptr--, *y_ptr++)); y[Na - 1] = sum; return sum; } float iirOutFloatL(float y[], float x[], float xin, float a[], float b[], int Na, int Nb) { float *a_ptr, *y_ptr, *b_ptr, *x_ptr; float sum = 0; a_ptr = &a[Na - 1]; y_ptr = &y[1]; b_ptr = &b[Nb - 1]; x_ptr = &x[0]; int i, j; for (i = 0; i < Nb - 1; i++) { x[i] = x[i+1]; sum += *b_ptr-- * *x_ptr++; } x[Nb - 1] = xin; sum += *b_ptr-- * *x_ptr++; for (j = 1; j < Na - 1; j++) { sum -= *a_ptr-- * *y_ptr++; y[j] = y[j+1]; } if(Na>1) sum -= *a_ptr-- * *y_ptr++; y[Na - 1] = sum; return sum; } float iirOutBothL(float yf[], float xf[], float af[], float bf[], float xfin, fxp_t y[], fxp_t x[], fxp_t a[], fxp_t b[], fxp_t xin, int Na, int Nb) { fxp_t *a_ptr, *y_ptr, *b_ptr, *x_ptr; fxp_t sum = 0; a_ptr = &a[Na - 1]; y_ptr = &y[1]; b_ptr = &b[Nb - 1]; x_ptr = &x[0]; float *af_ptr, *yf_ptr, *bf_ptr, *xf_ptr; float sumf = 0; af_ptr = &af[Na - 1]; yf_ptr = &yf[1]; bf_ptr = &bf[Nb - 1]; xf_ptr = &xf[0]; int i, j; for (i = 0; i < Nb - 1; i++) { x[i] = x[i+1]; sum = fxp_add(sum, fxp_mult(*b_ptr--, *x_ptr++)); xf[i] = xf[i+1]; sumf += *bf_ptr-- * *xf_ptr++; } x[Nb - 1] = xin; sum = fxp_add(sum, fxp_mult(*b_ptr--, *x_ptr++)); xf[Nb - 1] = xfin; sumf += *bf_ptr-- * *xf_ptr++; for (j = 1; j < Na - 1; j++) { sum = fxp_sub(sum, fxp_mult(*a_ptr--, *y_ptr++)); y[j] = y[j+1]; sumf -= *af_ptr-- * *yf_ptr++; yf[j] = yf[j+1]; } if(Na>1) sum = fxp_sub(sum, fxp_mult(*a_ptr--, *y_ptr++)); y[Na - 1] = sum; if(Na>1) sumf -= *af_ptr-- * *yf_ptr++; yf[Na - 1] = sumf; return fxp_to_float(sum) - sumf; } float iirOutBothL2(float yf[], float xf[], float af[], float bf[], float xfin, fxp_t y[], fxp_t x[], fxp_t a[], fxp_t b[], fxp_t xin, int Na, int Nb) { fxp_t *a_ptr, *y_ptr, *b_ptr, *x_ptr; fxp_t sum = 0; a_ptr = &a[Na - 1]; y_ptr = &y[1]; b_ptr = &b[Nb - 1]; x_ptr = &x[0]; float *af_ptr, *yf_ptr, *bf_ptr, *xf_ptr; float sumf = 0; af_ptr = &af[Na - 1]; yf_ptr = &yf[1]; bf_ptr = &bf[Nb - 1]; xf_ptr = &xf[0]; int i=0, j=1; for (i = 0; i < Nb - 1; i++) { x[i] = x[i+1]; sum = fxp_add(sum, fxp_mult(b[Nb - 1 - i], x[i])); xf[i] = xf[i+1]; sumf += bf[Nb - 1 - i] * xf[i]; } x[Nb - 1] = xin; sum = fxp_add(sum, fxp_mult(b[Nb - 1 - i], x[i])); xf[Nb - 1] = xfin; sumf += bf[Nb - 1 - i] * xf[i]; for (j = 1; j < Na - 1; j++) { sum = fxp_sub(sum, fxp_mult(a[Na - j], y[j])); y[j] = y[j+1]; sumf -= af[Na - j] * yf[j]; yf[j] = yf[j+1]; } if(Na>1) sum = fxp_sub(sum, fxp_mult(a[Na - j], y[j])); y[Na - 1] = sum; if(Na>1) sumf -= af[Na - j] * yf[j]; yf[Na - 1] = sumf; return fxp_to_float(sum) - sumf; } # 25 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 1 # 19 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" extern digital_system ds; extern hardware hw; extern int generic_timer; fxp_t fxp_direct_form_1(fxp_t y[], fxp_t x[], fxp_t a[], fxp_t b[], int Na, int Nb) { fxp_t *a_ptr, *y_ptr, *b_ptr, *x_ptr; fxp_t sum = 0; a_ptr = &a[1]; y_ptr = &y[Na - 1]; b_ptr = &b[0]; x_ptr = &x[Nb - 1]; int i, j; for (i = 0; i < Nb; i++) { sum = fxp_add(sum, fxp_mult(*b_ptr++, *x_ptr--)); } for (j = 1; j < Na; j++) { sum = fxp_sub(sum, fxp_mult(*a_ptr++, *y_ptr--)); } fxp_verify_overflow_node(sum, "An Overflow Occurred in the node a0"); sum = fxp_div(sum,a[0]); return fxp_quantize(sum); } fxp_t fxp_direct_form_2(fxp_t w[], fxp_t x, fxp_t a[], fxp_t b[], int Na, int Nb) { fxp_t *a_ptr, *b_ptr, *w_ptr; fxp_t sum = 0; a_ptr = &a[1]; b_ptr = &b[0]; w_ptr = &w[1]; int k, j; for (j = 1; j < Na; j++) { w[0] = fxp_sub(w[0], fxp_mult(*a_ptr++, *w_ptr++)); } w[0] = fxp_add(w[0], x); w[0] = fxp_div(w[0], a[0]); fxp_verify_overflow_node(w[0], "An Overflow Occurred in the node b0"); w_ptr = &w[0]; for (k = 0; k < Nb; k++) { sum = fxp_add(sum, fxp_mult(*b_ptr++, *w_ptr++)); } return fxp_quantize(sum); } fxp_t fxp_transposed_direct_form_2(fxp_t w[], fxp_t x, fxp_t a[], fxp_t b[], int Na, int Nb) { fxp_t *a_ptr, *b_ptr; fxp_t yout = 0; a_ptr = &a[1]; b_ptr = &b[0]; int Nw = Na > Nb ? Na : Nb; yout = fxp_add(fxp_mult(*b_ptr++, x), w[0]); yout = fxp_div(yout, a[0]); int j; for (j = 0; j < Nw - 1; j++) { w[j] = w[j + 1]; if (j < Na - 1) { w[j] = fxp_sub(w[j], fxp_mult(*a_ptr++, yout)); } if (j < Nb - 1) { w[j] = fxp_add(w[j], fxp_mult(*b_ptr++, x)); } } fxp_verify_overflow_node(w[j], "An Overflow Occurred in the node a0"); return fxp_quantize(yout); } double double_direct_form_1(double y[], double x[], double a[], double b[], int Na, int Nb) { double *a_ptr, *y_ptr, *b_ptr, *x_ptr; double sum = 0; a_ptr = &a[1]; y_ptr = &y[Na - 1]; b_ptr = &b[0]; x_ptr = &x[Nb - 1]; int i, j; for (i = 0; i < Nb; i++) { sum += *b_ptr++ * *x_ptr--; } for (j = 1; j < Na; j++) { sum -= *a_ptr++ * *y_ptr--; } sum = (sum / a[0]); return sum; } double double_direct_form_2(double w[], double x, double a[], double b[], int Na, int Nb) { double *a_ptr, *b_ptr, *w_ptr; double sum = 0; a_ptr = &a[1]; b_ptr = &b[0]; w_ptr = &w[1]; int k, j; for (j = 1; j < Na; j++) { w[0] -= *a_ptr++ * *w_ptr++; } w[0] += x; w[0] = w[0] / a[0]; w_ptr = &w[0]; for (k = 0; k < Nb; k++) { sum += *b_ptr++ * *w_ptr++; } return sum; } double double_transposed_direct_form_2(double w[], double x, double a[], double b[], int Na, int Nb) { double *a_ptr, *b_ptr; double yout = 0; a_ptr = &a[1]; b_ptr = &b[0]; int Nw = Na > Nb ? Na : Nb; yout = (*b_ptr++ * x) + w[0]; yout = yout / a[0]; int j; for (j = 0; j < Nw - 1; j++) { w[j] = w[j + 1]; if (j < Na - 1) { w[j] -= *a_ptr++ * yout; } if (j < Nb - 1) { w[j] += *b_ptr++ * x; } } return yout; } float float_direct_form_1(float y[], float x[], float a[], float b[], int Na, int Nb) { float *a_ptr, *y_ptr, *b_ptr, *x_ptr; float sum = 0; a_ptr = &a[1]; y_ptr = &y[Na - 1]; b_ptr = &b[0]; x_ptr = &x[Nb - 1]; int i, j; for (i = 0; i < Nb; i++) { sum += *b_ptr++ * *x_ptr--; } for (j = 1; j < Na; j++) { sum -= *a_ptr++ * *y_ptr--; } sum = (sum / a[0]); return sum; } float float_direct_form_2(float w[], float x, float a[], float b[], int Na, int Nb) { float *a_ptr, *b_ptr, *w_ptr; float sum = 0; a_ptr = &a[1]; b_ptr = &b[0]; w_ptr = &w[1]; int k, j; for (j = 1; j < Na; j++) { w[0] -= *a_ptr++ * *w_ptr++; } w[0] += x; w[0] = w[0] / a[0]; w_ptr = &w[0]; for (k = 0; k < Nb; k++) { sum += *b_ptr++ * *w_ptr++; } return sum; } float float_transposed_direct_form_2(float w[], float x, float a[], float b[], int Na, int Nb) { float *a_ptr, *b_ptr; float yout = 0; a_ptr = &a[1]; b_ptr = &b[0]; int Nw = Na > Nb ? Na : Nb; yout = (*b_ptr++ * x) + w[0]; yout = yout / a[0]; int j; for (j = 0; j < Nw - 1; j++) { w[j] = w[j + 1]; if (j < Na - 1) { w[j] -= *a_ptr++ * yout; } if (j < Nb - 1) { w[j] += *b_ptr++ * x; } } return yout; } double double_direct_form_1_MSP430(double y[], double x[], double a[], double b[], int Na, int Nb){ int timer1 = 0; double *a_ptr, *y_ptr, *b_ptr, *x_ptr; double sum = 0; a_ptr = &a[1]; y_ptr = &y[Na-1]; b_ptr = &b[0]; x_ptr = &x[Nb-1]; int i, j; timer1 += 91; for (i = 0; i < Nb; i++){ sum += *b_ptr++ * *x_ptr--; timer1 += 47; } for (j = 1; j < Na; j++){ sum -= *a_ptr++ * *y_ptr--; timer1 += 57; } timer1 += 3; # 235 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 ((void) sizeof (( # 235 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" (double) timer1 * hw.cycle <= ds.sample_time # 235 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 235 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" (double) timer1 * hw.cycle <= ds.sample_time # 235 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 ) ; else __assert_fail ( # 235 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" "(double) timer1 * hw.cycle <= ds.sample_time" # 235 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h", 235, __extension__ __PRETTY_FUNCTION__); })) # 235 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" ; return sum; } double double_direct_form_2_MSP430(double w[], double x, double a[], double b[], int Na, int Nb) { int timer1 = 0; double *a_ptr, *b_ptr, *w_ptr; double sum = 0; a_ptr = &a[1]; b_ptr = &b[0]; w_ptr = &w[1]; int k, j; timer1 += 71; for (j = 1; j < Na; j++) { w[0] -= *a_ptr++ * *w_ptr++; timer1 += 54; } w[0] += x; w[0] = w[0] / a[0]; w_ptr = &w[0]; for (k = 0; k < Nb; k++) { sum += *b_ptr++ * *w_ptr++; timer1 += 46; } timer1 += 38; # 262 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 ((void) sizeof (( # 262 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" (double) timer1 * hw.cycle <= ds.sample_time # 262 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 262 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" (double) timer1 * hw.cycle <= ds.sample_time # 262 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 ) ; else __assert_fail ( # 262 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" "(double) timer1 * hw.cycle <= ds.sample_time" # 262 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h", 262, __extension__ __PRETTY_FUNCTION__); })) # 262 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" ; return sum; } double double_transposed_direct_form_2_MSP430(double w[], double x, double a[], double b[], int Na, int Nb) { int timer1 = 0; double *a_ptr, *b_ptr; double yout = 0; a_ptr = &a[1]; b_ptr = &b[0]; int Nw = Na > Nb ? Na : Nb; yout = (*b_ptr++ * x) + w[0]; int j; timer1 += 105; for (j = 0; j < Nw - 1; j++) { w[j] = w[j + 1]; if (j < Na - 1) { w[j] -= *a_ptr++ * yout; timer1 += 41; } if (j < Nb - 1) { w[j] += *b_ptr++ * x; timer1 += 38; } timer1 += 54; } timer1 += 7; # 291 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 ((void) sizeof (( # 291 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" (double) timer1 * hw.cycle <= ds.sample_time # 291 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 291 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" (double) timer1 * hw.cycle <= ds.sample_time # 291 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 ) ; else __assert_fail ( # 291 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" "(double) timer1 * hw.cycle <= ds.sample_time" # 291 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h", 291, __extension__ __PRETTY_FUNCTION__); })) # 291 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/realizations.h" ; return yout; } double generic_timing_double_direct_form_1(double y[], double x[], double a[], double b[], int Na, int Nb){ generic_timer += ((6 * hw.assembly.push) + (3 * hw.assembly.in) + (1 * hw.assembly.sbiw) + (1 * hw.assembly.cli) + (3 * hw.assembly.out) + (12 * hw.assembly.std)); double *a_ptr, *y_ptr, *b_ptr, *x_ptr; double sum = 0; a_ptr = &a[1]; y_ptr = &y[Na-1]; b_ptr = &b[0]; x_ptr = &x[Nb-1]; generic_timer += ((12 * hw.assembly.std) + (12 * hw.assembly.ldd) + (2 * hw.assembly.subi) + (2 * hw.assembly.sbci) + (4 * hw.assembly.lsl) + (4 * hw.assembly.rol) + (2 * hw.assembly.add) + (2 * hw.assembly.adc) + (1 * hw.assembly.adiw)); int i, j; generic_timer += ((2 * hw.assembly.std) + (1 * hw.assembly.rjmp)); for (i = 0; i < Nb; i++){ generic_timer += ((20 * hw.assembly.ldd) + (24 * hw.assembly.mov) + (2 * hw.assembly.subi) + (1 * hw.assembly.sbci) + (1 * hw.assembly.sbc) + (10 * hw.assembly.std) + (2 * hw.assembly.ld) + (2 * hw.assembly.rcall) + (1 * hw.assembly.adiw) + (1 * hw.assembly.cp) + (1 * hw.assembly.cpc) + (1 * hw.assembly.adiw) + (1 * hw.assembly.brge) + (1 * hw.assembly.rjmp)); sum += *b_ptr++ * *x_ptr--; } generic_timer += ((2 * hw.assembly.ldi) + (2 * hw.assembly.std) + (1 * hw.assembly.rjmp)); for (j = 1; j < Na; j++){ generic_timer += ((22 * hw.assembly.ldd) + (24 * hw.assembly.mov) + (2 * hw.assembly.subi) + (8 * hw.assembly.std) + (1 * hw.assembly.sbci) + (2 * hw.assembly.ld) + (2 * hw.assembly.rcall) + (1 * hw.assembly.sbc) + (1 * hw.assembly.adiw) + (1 * hw.assembly.cp) + (1 * hw.assembly.cpc) + (1 * hw.assembly.adiw) + (1 * hw.assembly.brge) + (1 * hw.assembly.rjmp)); sum -= *a_ptr++ * *y_ptr--; } generic_timer += ((4 * hw.assembly.ldd) + (4 * hw.assembly.mov) + (1 * hw.assembly.adiw) + (1 * hw.assembly.in) + (1 * hw.assembly.cli) + (3 * hw.assembly.out) + (6 * hw.assembly.pop) + (1 * hw.assembly.ret)); return sum; } double generic_timing_double_direct_form_2(double w[], double x, double a[], double b[], int Na, int Nb) { generic_timer += ((8 * hw.assembly.push) + (14 * hw.assembly.std) + (3 * hw.assembly.out) + (3 * hw.assembly.in) + (1 * hw.assembly.sbiw) + (1 * hw.assembly.cli)); double *a_ptr, *b_ptr, *w_ptr; double sum = 0; a_ptr = &a[1]; b_ptr = &b[0]; w_ptr = &w[1]; int k, j; generic_timer += ((10 * hw.assembly.std) + (6 * hw.assembly.ldd) + (2 * hw.assembly.adiw)); generic_timer += ((2 * hw.assembly.ldi) + (2 * hw.assembly.std) + (1 * hw.assembly.rjmp)); for (j = 1; j < Na; j++) { w[0] -= *a_ptr++ * *w_ptr++; generic_timer += ((23 * hw.assembly.ldd) + (32 * hw.assembly.mov) + (9 * hw.assembly.std) + (2 * hw.assembly.subi) + (3 * hw.assembly.ld) + (2 * hw.assembly.rcall) + (2 * hw.assembly.sbci) + (1 * hw.assembly.st) + (1 * hw.assembly.adiw) + (1 * hw.assembly.cp) + (1 * hw.assembly.cpc) + (1 * hw.assembly.brge)); } w[0] += x; w_ptr = &w[0]; generic_timer += ((13 * hw.assembly.ldd) + (12 * hw.assembly.mov) + (5 * hw.assembly.std) + (1 * hw.assembly.st) + (1 * hw.assembly.ld) + (1 * hw.assembly.rcall)); generic_timer += ((2 * hw.assembly.std) + (1 * hw.assembly.rjmp)); for (k = 0; k < Nb; k++) { sum += *b_ptr++ * *w_ptr++; generic_timer += ((20 * hw.assembly.ldd) + (24 * hw.assembly.mov) + (10 * hw.assembly.std) + (2 * hw.assembly.rcall) + (2 * hw.assembly.ld) + (2 * hw.assembly.subi) + (2 * hw.assembly.sbci) + (1 * hw.assembly.adiw) + (1 * hw.assembly.cp) + (1 * hw.assembly.cpc) + (1 * hw.assembly.brge) + (1 * hw.assembly.rjmp)); } generic_timer += ((4 * hw.assembly.ldd) + (4 * hw.assembly.mov) + (1 * hw.assembly.adiw) + (1 * hw.assembly.in) + (1 * hw.assembly.cli) + (3 * hw.assembly.out) + (8 * hw.assembly.pop) + (1 * hw.assembly.ret)); return sum; } double generic_timing_double_transposed_direct_form_2(double w[], double x, double a[], double b[], int Na, int Nb) { generic_timer += ((8 * hw.assembly.push) + (14 * hw.assembly.std) + (3 * hw.assembly.out) + (3 * hw.assembly.in) + (1 * hw.assembly.sbiw) + (1 * hw.assembly.cli)); double *a_ptr, *b_ptr; double yout = 0; a_ptr = &a[1]; b_ptr = &b[0]; int Nw = Na > Nb ? Na : Nb; yout = (*b_ptr++ * x) + w[0]; int j; generic_timer += ((15 * hw.assembly.std) + (22 * hw.assembly.ldd) + (24 * hw.assembly.mov) + (2 * hw.assembly.rcall) + (2 * hw.assembly.ld) + (1 * hw.assembly.cp) + (1 * hw.assembly.cpc) + (1 * hw.assembly.subi) + (1 * hw.assembly.sbci) + (1 * hw.assembly.brge) + (1 * hw.assembly.adiw)); generic_timer += ((2 * hw.assembly.std) + (1 * hw.assembly.rjmp)); for (j = 0; j < Nw - 1; j++) { w[j] = w[j + 1]; if (j < Na - 1) { w[j] -= *a_ptr++ * yout; } if (j < Nb - 1) { w[j] += *b_ptr++ * x; } generic_timer += ((70 * hw.assembly.mov) + (65 * hw.assembly.ldd) + (12 * hw.assembly.lsl) + (12 * hw.assembly.rol) + (15 * hw.assembly.std) + (6 * hw.assembly.add) + (6 * hw.assembly.adc) + (2 * hw.assembly.adiw) + (3 * hw.assembly.cpc) + (3 * hw.assembly.cp) + (5 * hw.assembly.ld) + (4 * hw.assembly.rcall) + (5 * hw.assembly.subi) + (3 * hw.assembly.rjmp) + (2 * hw.assembly.brlt) + (3 * hw.assembly.st) + (2 * hw.assembly.sbci) + (3 * hw.assembly.sbc) + (1 * hw.assembly.brge)); } generic_timer += ((4 * hw.assembly.ldd) + (4 * hw.assembly.mov) + (8 * hw.assembly.pop) + (3 * hw.assembly.out) + (1 * hw.assembly.in) + (1 * hw.assembly.cli) + (1 * hw.assembly.adiw) + (1 * hw.assembly.ret)); return yout; } void double_direct_form_1_impl2(double x[], int x_size, double b[], int b_size, double a[], int a_size, double y[]){ int i = 0; int j = 0; double v[x_size]; for(i = 0; i < x_size; i++){ v[i] = 0; for(j = 0; j < b_size; j++){ if (j > i) break; v[i] = v[i] + x[i-j] * b[j]; } } y[0] = v[0]; for(i = 1; i < x_size; i++){ y[i] = 0; y[i] = y[i] + v[i]; for(j = 1; j < a_size; j++){ if (j > i) break; y[i] = y[i] + y[i-j] * ((-1) * a[j]); } } } void fxp_direct_form_1_impl2(fxp_t x[], int x_size, fxp_t b[], int b_size, fxp_t a[], int a_size, fxp_t y[]){ int i = 0; int j = 0; fxp_t v[x_size]; for(i = 0; i < x_size; i++){ v[i] = 0; for(j = 0; j < b_size; j++){ if (j > i) break; v[i] = fxp_add(v[i], fxp_mult(x[i-j], b[j])); } } y[0] = v[0]; for(i = 1; i < x_size; i++){ y[i] = 0; y[i] = fxp_add(y[i], v[i]); for(j = 1; j < a_size; j++){ if (j > i) break; y[i] = fxp_add(y[i], fxp_mult(y[i-j] , -a[j])); } } } # 26 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/delta-operator.h" 1 # 19 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/delta-operator.h" # 1 "/usr/include/assert.h" 1 3 4 # 20 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/delta-operator.h" 2 # 1 "/usr/include/assert.h" 1 3 4 # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/delta-operator.h" 2 int nchoosek(int n, int k){ if (k == 0) return 1; return (n * nchoosek(n - 1, k - 1)) / k; } void generate_delta_coefficients(double vetor[], double out[], int n, double delta){ int i,j; int N = n - 1; double sum_delta_operator; for(i=0; i<=N; i++) { sum_delta_operator = 0; for(j=0; j<=i; j++) { sum_delta_operator = sum_delta_operator + vetor[j]*nchoosek(N-j,i-j); } out[i] = internal_pow(delta,N-i)*sum_delta_operator; } } void get_delta_transfer_function(double b[], double b_out[], int b_size, double a[], double a_out[], int a_size, double delta){ generate_delta_coefficients(b, b_out, b_size, delta); generate_delta_coefficients(a, a_out, a_size, delta); } void get_delta_transfer_function_with_base(double b[], double b_out[], int b_size, double a[], double a_out[], int a_size, double delta){ int i,j; int N = a_size - 1; int M = b_size - 1; double sum_delta_operator; for(i=0; i<=N; i++) { sum_delta_operator = 0; for(j=0; j<=i; j++) { sum_delta_operator = sum_delta_operator + a[j]*nchoosek(N-j,i-j); } a_out[i] = internal_pow(delta,N-i)*sum_delta_operator; } for(i=0; i<=M; i++) { sum_delta_operator = 0; for(j=0; j<=i; j++) { sum_delta_operator = sum_delta_operator + b[j]*nchoosek(M-j,i-j); } b_out[i] = internal_pow(delta,M-i)*sum_delta_operator; } } # 27 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/closed-loop.h" 1 # 28 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/closed-loop.h" void ft_closedloop_series(double c_num[], int Nc_num, double c_den[], int Nc_den, double model_num[], int Nmodel_num, double model_den[], int Nmodel_den, double ans_num[], int Nans_num, double ans_den[], int Nans_den){ Nans_num = Nc_num + Nmodel_num - 1; Nans_den = Nc_den + Nmodel_den - 1 ; double den_mult [Nans_den]; poly_mult(c_num, Nc_num, model_num, Nmodel_num, ans_num, Nans_num); poly_mult(c_den, Nc_den, model_den, Nmodel_den, den_mult, Nans_den ); poly_sum(ans_num, Nans_num , den_mult, Nans_den , ans_den, Nans_den); } void ft_closedloop_sensitivity(double c_num[], int Nc_num, double c_den[], int Nc_den, double model_num[], int Nmodel_num, double model_den[], int Nmodel_den, double ans_num[], int Nans_num, double ans_den[], int Nans_den){ int Nans_num_p = Nc_num + Nmodel_num-1; Nans_den = Nc_den + Nmodel_den-1; Nans_num = Nc_den + Nmodel_den-1; double num_mult [Nans_num_p]; poly_mult(c_den, Nc_den, model_den, Nmodel_den, ans_num, Nans_num); poly_mult(c_num, Nc_num, model_num, Nmodel_num, num_mult, Nans_num_p); poly_sum(ans_num, Nans_num, num_mult, Nans_num_p, ans_den, Nans_den); } void ft_closedloop_feedback(double c_num[], int Nc_num, double c_den[], int Nc_den, double model_num[], int Nmodel_num, double model_den[], int Nmodel_den, double ans_num[], int Nans_num, double ans_den[], int Nans_den){ Nans_num = Nc_den + Nmodel_num - 1; Nans_den = Nc_den + Nmodel_den - 1; int Nnum_mult = Nc_num + Nmodel_num - 1; double den_mult [Nans_den]; double num_mult [Nnum_mult]; poly_mult(c_num, Nc_num, model_num, Nmodel_num, num_mult, Nnum_mult); poly_mult(c_den, Nc_den, model_den, Nmodel_den, den_mult, Nans_den); poly_sum(num_mult, Nnum_mult, den_mult, Nans_den, ans_den, Nans_den); poly_mult(c_den, Nc_den, model_num, Nmodel_num, ans_num, Nans_num); } int check_stability_closedloop(double a[], int n, double plant_num[], int p_num_size, double plant_den[], int p_den_size){ int columns = n; double m[2 * n - 1][n]; int i,j; int first_is_positive = 0; double * p_num = plant_num; double * p_den = plant_den; double sum = 0; for (i=0; i < n; i++){ sum += a[i]; } __DSVERIFIER_assert(sum > 0); sum = 0; for (i=0; i < n; i++){ sum += a[i] * internal_pow(-1, n-1-i); } sum = sum * internal_pow(-1, n-1); __DSVERIFIER_assert(sum > 0); __DSVERIFIER_assert(internal_abs(a[n-1]) < a[0]); for (i=0; i < 2 * n - 1; i++){ for (j=0; j < columns; j++){ m[i][j] = 0; if (i == 0){ m[i][j] = a[j]; continue; } if (i % 2 != 0 ){ int x; for(x=0; x<columns;x++){ m[i][x] = m[i-1][columns-x-1]; } columns = columns - 1; j = columns; }else{ __DSVERIFIER_assert(m[i-2][0] > 0); m[i][j] = m[i-2][j] - (m[i-2][columns] / m[i-2][0]) * m[i-1][j]; __DSVERIFIER_assert((m[0][0] >= 0) && (m[i][0] >= 0)); } } } return 1; } # 28 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" 1 # 17 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" extern digital_system ds; extern digital_system plant; extern digital_system control; extern implementation impl; extern filter_parameters filter; extern hardware hw; void initialization(){ if (impl.frac_bits >= 32){ printf("impl.frac_bits must be less than word width!\n"); } if (impl.int_bits >= 32 - impl.frac_bits){ printf("impl.int_bits must be less than word width subtracted by precision!\n"); # 33 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" 3 4 ((void) sizeof (( # 33 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" 0 # 33 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 33 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" 0 # 33 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" 3 4 ) ; else __assert_fail ( # 33 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" "0" # 33 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h", 33, __extension__ __PRETTY_FUNCTION__); })) # 33 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" ; } if(impl.frac_bits >= 31){ _fxp_one = 0x7fffffff; }else{ _fxp_one = (0x00000001 << impl.frac_bits); } _fxp_half = (0x00000001 << (impl.frac_bits - 1)); _fxp_minus_one = -(0x00000001 << impl.frac_bits); _fxp_min = -(0x00000001 << (impl.frac_bits + impl.int_bits - 1)); _fxp_max = (0x00000001 << (impl.frac_bits + impl.int_bits - 1)) - 1; _fxp_fmask = ((((int32_t) 1) << impl.frac_bits) - 1); _fxp_imask = ((0x80000000) >> (32 - impl.frac_bits - 1)); _dbl_min = _fxp_min; _dbl_min /= (1 << impl.frac_bits); _dbl_max = _fxp_max; _dbl_max /= (1 << impl.frac_bits); if ((impl.scale == 0) || (impl.scale == 1)){ impl.scale = 1; return; } if (impl.min != 0){ impl.min = impl.min / impl.scale; } if (impl.max != 0){ impl.max = impl.max / impl.scale; } # 80 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/initialization.h" } # 29 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/state-space.h" 1 # 19 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/state-space.h" extern digital_system_state_space _controller; extern int nStates; extern int nInputs; extern int nOutputs; double double_state_space_representation(void){ double result1[4][4]; double result2[4][4]; int i, j; for(i=0; i<4;i++){ for(j=0; j<4;j++){ result1[i][j]=0; result2[i][j]=0; } } double_matrix_multiplication(nOutputs,nStates,nStates,1,_controller.C,_controller.states,result1); double_matrix_multiplication(nOutputs,nInputs,nInputs,1,_controller.D,_controller.inputs,result2); double_add_matrix(nOutputs, 1, result1, result2, _controller.outputs); double_matrix_multiplication(nStates,nStates,nStates,1,_controller.A,_controller.states,result1); double_matrix_multiplication(nStates,nInputs,nInputs,1,_controller.B,_controller.inputs,result2); double_add_matrix(nStates, 1, result1, result2, _controller.states); return _controller.outputs[0][0]; } double fxp_state_space_representation(void){ fxp_t result1[4][4]; fxp_t result2[4][4]; int i, j; for(i=0; i<4;i++){ for(j=0; j<4;j++){ result1[i][j]=0; result2[i][j]=0; } } fxp_t A_fpx[4][4]; fxp_t B_fpx[4][4]; fxp_t C_fpx[4][4]; fxp_t D_fpx[4][4]; fxp_t states_fpx[4][4]; fxp_t inputs_fpx[4][4]; fxp_t outputs_fpx[4][4]; for(i=0; i<4;i++){ for(j=0; j<4;j++){ A_fpx[i][j]=0; } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ B_fpx[i][j]=0; } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ C_fpx[i][j]=0; } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ D_fpx[i][j]=0; } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ states_fpx[i][j]=0; } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ inputs_fpx[i][j]=0; } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ outputs_fpx[i][j]=0; } } for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ A_fpx[i][j]= fxp_double_to_fxp(_controller.A[i][j]); } } for(i=0; i<nStates;i++){ for(j=0; j<nInputs;j++){ B_fpx[i][j]= fxp_double_to_fxp(_controller.B[i][j]); } } for(i=0; i<nOutputs;i++){ for(j=0; j<nStates;j++){ C_fpx[i][j]= fxp_double_to_fxp(_controller.C[i][j]); } } for(i=0; i<nOutputs;i++){ for(j=0; j<nInputs;j++){ D_fpx[i][j]= fxp_double_to_fxp(_controller.D[i][j]); } } for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ states_fpx[i][j]= fxp_double_to_fxp(_controller.states[i][j]); } } for(i=0; i<nInputs;i++){ for(j=0; j<1;j++){ inputs_fpx[i][j]= fxp_double_to_fxp(_controller.inputs[i][j]); } } for(i=0; i<nOutputs;i++){ for(j=0; j<1;j++){ outputs_fpx[i][j]= fxp_double_to_fxp(_controller.outputs[i][j]); } } fxp_matrix_multiplication(nOutputs,nStates,nStates,1,C_fpx,states_fpx,result1); fxp_matrix_multiplication(nOutputs,nInputs,nInputs,1,D_fpx,inputs_fpx,result2); fxp_add_matrix(nOutputs, 1, result1, result2, outputs_fpx); fxp_matrix_multiplication(nStates,nStates,nStates,1,A_fpx,states_fpx,result1); fxp_matrix_multiplication(nStates,nInputs,nInputs,1,B_fpx,inputs_fpx,result2); fxp_add_matrix(nStates, 1, result1, result2, states_fpx); for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ _controller.states[i][j]= fxp_to_double(states_fpx[i][j]); } } for(i=0; i<nOutputs;i++){ for(j=0; j<1;j++){ _controller.outputs[i][j]= fxp_to_double(outputs_fpx[i][j]); } } return _controller.outputs[0][0]; } # 30 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/filter_functions.h" 1 # 20 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/core/filter_functions.h" double sinTyl(double x, int precision){ double sine; double xsquared = x*x; double aux; if (precision < 0) { printf("Warning: Function sinTyl from bmc/core/filter_functions.h: " "Precision must be a positive integer. Assuming 0 precision\n"); precision = 0; } if (precision >= 0) { aux = 0; sine = aux; if (precision >= 1) { aux = x; sine += aux; if (precision >= 2) { aux = aux*xsquared; sine -= aux/6; if (precision >= 3) { aux = aux*xsquared; sine +=aux/120; if(precision >=4) { aux = aux*xsquared; sine -=aux/5040; if(precision >= 5) { aux = aux*xsquared; sine +=aux/362880; if(precision >= 6) { aux = aux*xsquared; sine -=aux/39916800; if (precision >= 7) printf("Warning: Function sinTyl " "from bmc/core/filter_functions.h: Precision " "representation exceeded. Assuming maximum precision of 6\n"); } } } } } } } return sine; } double cosTyl(double x, int precision){ double cosine; double xsquared = x*x; double aux; if (precision < 0) { printf("Warning: Function cosTyl from bmc/core/filter_functions.h: " "Precision must be a positive integer. Assuming 0 precision\n"); precision = 0; } if (precision >= 0) { aux = 0; cosine = aux; if (precision >= 1) { aux = 1; cosine = 1; if (precision >= 2) { aux = xsquared; cosine -= aux/2; if (precision >= 3) { aux = aux*xsquared; cosine += aux/24; if(precision >=4) { aux = aux*xsquared; cosine -=aux/720; if(precision >= 5) { aux = aux*xsquared; cosine +=aux/40320; if(precision >= 6) { aux = aux*xsquared; cosine -=aux/3628800; if (precision >= 7) printf("Warning: Function sinTyl " "from bmc/core/filter_functions.h: Precision " "representation exceeded. Assuming maximum precision of 6\n"); } } } } } } } return cosine; } double atanTyl(double x, int precision){ double atangent; double xsquared = x*x; double aux; if (precision < 0) { printf("Warning: Function sinTyl from bmc/core/filter_functions.h: " "Precision must be a positive integer. Assuming 0 precision\n"); precision = 0; } if (precision >= 0) { aux = 0; atangent = aux; if (precision >= 1) { aux = x; atangent = aux; if (precision >= 2) { aux = xsquared; atangent -= aux/3; if (precision >= 3) { aux = aux*xsquared; atangent += aux/5; if(precision >=4) { aux = aux*xsquared; atangent -=aux/7; if (precision >= 7) printf("Warning: Function sinTyl from bmc/core/filter_functions.h: " "Precision representation exceeded. Assuming maximum precision of 4\n"); } } } } } return atangent; } float sqrt1(const float x) { const float xhalf = 0.5f*x; union { float x; int i; } u; u.x = x; u.i = 0x5f3759df - (u.i >> 1); return x*u.x*(1.5f - xhalf*u.x*u.x); } float sqrt2(const float x) { union { int i; float x; } u; u.x = x; u.i = (1<<29) + (u.i >> 1) - (1<<22); return u.x; } float fabsolut(float x) { if (x < 0) x = -x; return x; } static float sqrt3(float val) { float x = val/10; float dx; double diff; double min_tol = 0.00001; int i, flag; flag = 0; if (val == 0 ) x = 0; else { for (i=1;i<20;i++) { if (!flag) { dx = (val - (x*x)) / (2.0 * x); x = x + dx; diff = val - (x*x); if (fabsolut(diff) <= min_tol) flag = 1; } else x =x; } } return (x); } # 31 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_overflow.h" 1 # 19 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_overflow.h" int nondet_int(); float nondet_float(); extern digital_system ds; extern implementation impl; int verify_overflow(void) { fxp_t a_fxp[ds.a_size]; fxp_t b_fxp[ds.b_size]; fxp_double_to_fxp_array(ds.a, a_fxp, ds.a_size); fxp_double_to_fxp_array(ds.b, b_fxp, ds.b_size); # 73 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_overflow.h" fxp_t min_fxp = fxp_double_to_fxp(impl.min); fxp_t max_fxp = fxp_double_to_fxp(impl.max); fxp_t y[X_SIZE_VALUE]; fxp_t x[X_SIZE_VALUE]; int i; for (i = 0; i < X_SIZE_VALUE; ++i) { y[i] = 0; x[i] = nondet_int(); __DSVERIFIER_assume(x[i] >= min_fxp && x[i] <= max_fxp); } int Nw = 0; Nw = ds.a_size > ds.b_size ? ds.a_size : ds.b_size; fxp_t yaux[ds.a_size]; fxp_t xaux[ds.b_size]; fxp_t waux[Nw]; for (i = 0; i < ds.a_size; ++i) { yaux[i] = 0; } for (i = 0; i < ds.b_size; ++i) { xaux[i] = 0; } for (i = 0; i < Nw; ++i) { waux[i] = 0; } fxp_t xk, temp; fxp_t *aptr, *bptr, *xptr, *yptr, *wptr; int j; for (i = 0; i < X_SIZE_VALUE; ++i) { shiftL(x[i], xaux, ds.b_size); y[i] = fxp_direct_form_1(yaux, xaux, a_fxp, b_fxp, ds.a_size, ds.b_size); shiftL(y[i], yaux, ds.a_size); # 174 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_overflow.h" } overflow_mode = 1; fxp_verify_overflow_array(y, X_SIZE_VALUE); return 0; } # 33 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 1 # 15 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" extern digital_system ds; extern implementation impl; extern digital_system_state_space _controller; extern int nStates; extern int nInputs; extern int nOutputs; int verify_limit_cycle_state_space(void){ double stateMatrix[4][4]; double outputMatrix[4][4]; double arrayLimitCycle[4]; double result1[4][4]; double result2[4][4]; int i, j, k; for(i=0; i<4;i++){ for(j=0; j<4;j++){ result1[i][j]=0; result2[i][j]=0; stateMatrix[i][j]=0; outputMatrix[i][j]=0; } } double_matrix_multiplication(nOutputs,nStates,nStates,1,_controller.C,_controller.states,result1); double_matrix_multiplication(nOutputs,nInputs,nInputs,1,_controller.D,_controller.inputs,result2); double_add_matrix(nOutputs, 1, result1, result2, _controller.outputs); k = 0; for (i = 1; i < 0; i++) { double_matrix_multiplication(nStates,nStates,nStates,1,_controller.A,_controller.states,result1); double_matrix_multiplication(nStates,nInputs,nInputs,1,_controller.B,_controller.inputs,result2); double_add_matrix(nStates, 1, result1, result2, _controller.states); double_matrix_multiplication(nOutputs,nStates,nStates,1,_controller.C,_controller.states,result1); double_matrix_multiplication(nOutputs,nInputs,nInputs,1,_controller.D,_controller.inputs,result2); double_add_matrix(nOutputs, 1, result1, result2, _controller.outputs); int l; for(l = 0; l < nStates; l++){ stateMatrix[l][k] = _controller.states[l][0]; } for(l = 0; l < nOutputs; l++){ stateMatrix[l][k] = _controller.outputs[l][0]; } k++; } printf("#matrix STATES -------------------------------"); print_matrix(stateMatrix,nStates,0); printf("#matrix OUTPUTS -------------------------------"); print_matrix(outputMatrix,nOutputs,0); # 93 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 3 4 ((void) sizeof (( # 93 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 0 # 93 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 93 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 0 # 93 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 3 4 ) ; else __assert_fail ( # 93 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" "0" # 93 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h", 93, __extension__ __PRETTY_FUNCTION__); })) # 93 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" ; for(i=0; i<nStates;i++){ for(j=0; j<0;j++){ arrayLimitCycle[j] = stateMatrix[i][j]; } double_check_persistent_limit_cycle(arrayLimitCycle,0); } for(i=0; i<nOutputs;i++){ for(j=0; j<0;j++){ arrayLimitCycle[j] = outputMatrix[i][j]; } double_check_persistent_limit_cycle(arrayLimitCycle,0); } # 110 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 3 4 ((void) sizeof (( # 110 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 0 # 110 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 110 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 0 # 110 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 3 4 ) ; else __assert_fail ( # 110 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" "0" # 110 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h", 110, __extension__ __PRETTY_FUNCTION__); })) # 110 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" ; } int verify_limit_cycle(void){ overflow_mode = 3; int i; int Set_xsize_at_least_two_times_Na = 2 * ds.a_size; printf("X_SIZE must be at least 2 * ds.a_size"); __DSVERIFIER_assert(X_SIZE_VALUE >= Set_xsize_at_least_two_times_Na); fxp_t a_fxp[ds.a_size]; fxp_t b_fxp[ds.b_size]; fxp_double_to_fxp_array(ds.a, a_fxp, ds.a_size); fxp_double_to_fxp_array(ds.b, b_fxp, ds.b_size); # 168 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" fxp_t y[X_SIZE_VALUE]; fxp_t x[X_SIZE_VALUE]; fxp_t min_fxp = fxp_double_to_fxp(impl.min); fxp_t max_fxp = fxp_double_to_fxp(impl.max); fxp_t xaux[ds.b_size]; int nondet_constant_input = nondet_int(); __DSVERIFIER_assume(nondet_constant_input >= min_fxp && nondet_constant_input <= max_fxp); for (i = 0; i < X_SIZE_VALUE; ++i) { x[i] = nondet_constant_input; y[i] = 0; } for (i = 0; i < ds.b_size; ++i) { xaux[i] = nondet_constant_input; } int Nw = 0; Nw = ds.a_size > ds.b_size ? ds.a_size : ds.b_size; fxp_t yaux[ds.a_size]; fxp_t y0[ds.a_size]; fxp_t waux[Nw]; fxp_t w0[Nw]; for (i = 0; i < ds.a_size; ++i) { yaux[i] = nondet_int(); __DSVERIFIER_assume(yaux[i] >= min_fxp && yaux[i] <= max_fxp); y0[i] = yaux[i]; } # 213 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" fxp_t xk, temp; fxp_t *aptr, *bptr, *xptr, *yptr, *wptr; int j; for(i=0; i<X_SIZE_VALUE; ++i){ shiftL(x[i], xaux, ds.b_size); y[i] = fxp_direct_form_1(yaux, xaux, a_fxp, b_fxp, ds.a_size, ds.b_size); shiftL(y[i], yaux, ds.a_size); # 278 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle.h" } fxp_check_persistent_limit_cycle(y, X_SIZE_VALUE); return 0; } # 34 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error.h" 1 # 17 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error.h" extern digital_system ds; extern implementation impl; int verify_error(void){ overflow_mode = 2; double a_cascade[100]; int a_cascade_size; double b_cascade[100]; int b_cascade_size; fxp_t a_fxp[ds.a_size]; fxp_t b_fxp[ds.b_size]; fxp_double_to_fxp_array(ds.a, a_fxp, ds.a_size); fxp_double_to_fxp_array(ds.b, b_fxp, ds.b_size); # 69 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error.h" fxp_t min_fxp = fxp_double_to_fxp(impl.min); fxp_t max_fxp = fxp_double_to_fxp(impl.max); fxp_t y[X_SIZE_VALUE]; fxp_t x[X_SIZE_VALUE]; double yf[X_SIZE_VALUE]; double xf[X_SIZE_VALUE]; int Nw = 0; Nw = ds.a_size > ds.b_size ? ds.a_size : ds.b_size; fxp_t yaux[ds.a_size]; fxp_t xaux[ds.b_size]; fxp_t waux[Nw]; double yfaux[ds.a_size]; double xfaux[ds.b_size]; double wfaux[Nw]; int i; for (i = 0; i < ds.a_size; ++i) { yaux[i] = 0; yfaux[i] = 0; } for (i = 0; i < ds.b_size; ++i) { xaux[i] = 0; xfaux[i] = 0; } for (i = 0; i < Nw; ++i) { waux[i] = 0; wfaux[i] = 0; } for (i = 0; i < X_SIZE_VALUE; ++i) { y[i] = 0; x[i] = nondet_int(); __DSVERIFIER_assume(x[i] >= min_fxp && x[i] <= max_fxp); yf[i] = 0.0f; xf[i] = fxp_to_double(x[i]); } for (i = 0; i < X_SIZE_VALUE; ++i) { shiftL(x[i], xaux, ds.b_size); y[i] = fxp_direct_form_1(yaux, xaux, a_fxp, b_fxp, ds.a_size, ds.b_size); shiftL(y[i], yaux, ds.a_size); shiftLDouble(xf[i], xfaux, ds.b_size); yf[i] = double_direct_form_1(yfaux, xfaux, ds.a, ds.b, ds.a_size, ds.b_size); shiftLDouble(yf[i], yfaux, ds.a_size); # 169 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error.h" double absolute_error = yf[i] - fxp_to_double(y[i]); __DSVERIFIER_assert(absolute_error < (impl.max_error) && absolute_error > (-impl.max_error)); } return 0; } # 35 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" 1 # 13 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" extern digital_system ds; extern implementation impl; int verify_zero_input_limit_cycle(void){ overflow_mode = 3; int i,j; int Set_xsize_at_least_two_times_Na = 2 * ds.a_size; printf("X_SIZE must be at least 2 * ds.a_size"); # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" 3 4 ((void) sizeof (( # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" X_SIZE_VALUE >= Set_xsize_at_least_two_times_Na # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" X_SIZE_VALUE >= Set_xsize_at_least_two_times_Na # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" 3 4 ) ; else __assert_fail ( # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" "X_SIZE_VALUE >= Set_xsize_at_least_two_times_Na" # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h", 23, __extension__ __PRETTY_FUNCTION__); })) # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" ; fxp_t a_fxp[ds.a_size]; fxp_t b_fxp[ds.b_size]; fxp_double_to_fxp_array(ds.a, a_fxp, ds.a_size); fxp_double_to_fxp_array(ds.b, b_fxp, ds.b_size); # 71 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" fxp_t min_fxp = fxp_double_to_fxp(impl.min); fxp_t max_fxp = fxp_double_to_fxp(impl.max); fxp_t y[X_SIZE_VALUE]; fxp_t x[X_SIZE_VALUE]; for (i = 0; i < X_SIZE_VALUE; ++i) { y[i] = 0; x[i] = 0; } int Nw = 0; Nw = ds.a_size > ds.b_size ? ds.a_size : ds.b_size; fxp_t yaux[ds.a_size]; fxp_t xaux[ds.b_size]; fxp_t waux[Nw]; fxp_t y0[ds.a_size]; fxp_t w0[Nw]; for (i = 0; i < ds.a_size; ++i) { yaux[i] = nondet_int(); __DSVERIFIER_assume(yaux[i] >= min_fxp && yaux[i] <= max_fxp); y0[i] = yaux[i]; } # 111 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" for (i = 0; i < ds.b_size; ++i) { xaux[i] = 0; } fxp_t xk, temp; fxp_t *aptr, *bptr, *xptr, *yptr, *wptr; for(i=0; i<X_SIZE_VALUE; ++i){ shiftL(x[i], xaux, ds.b_size); y[i] = fxp_direct_form_1(yaux, xaux, a_fxp, b_fxp, ds.a_size, ds.b_size); shiftL(y[i], yaux, ds.a_size); # 188 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_zero_input_limit_cycle.h" } fxp_check_persistent_limit_cycle(y, X_SIZE_VALUE); return 0; } # 36 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" 1 # 16 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" int nondet_int(); float nondet_float(); extern digital_system ds; extern implementation impl; extern hardware hw; int generic_timer = 0; int verify_generic_timing(void) { double y[X_SIZE_VALUE]; double x[X_SIZE_VALUE]; int i; for (i = 0; i < X_SIZE_VALUE; ++i) { y[i] = 0; x[i] = nondet_float(); __DSVERIFIER_assume(x[i] >= impl.min && x[i] <= impl.max); } int Nw = 0; Nw = ds.a_size > ds.b_size ? ds.a_size : ds.b_size; double yaux[ds.a_size]; double xaux[ds.b_size]; double waux[Nw]; for (i = 0; i < ds.a_size; ++i) { yaux[i] = 0; } for (i = 0; i < ds.b_size; ++i) { xaux[i] = 0; } for (i = 0; i < Nw; ++i) { waux[i] = 0; } double xk, temp; double *aptr, *bptr, *xptr, *yptr, *wptr; int j; generic_timer += ((2 * hw.assembly.std) + (1 * hw.assembly.rjmp)); double initial_timer = generic_timer; for (i = 0; i < X_SIZE_VALUE; ++i) { generic_timer += ((2 * hw.assembly.ldd) + (1 * hw.assembly.adiw) + (2 * hw.assembly.std)); generic_timer += ((2 * hw.assembly.ldd) + (1 * hw.assembly.cpi) + (1 * hw.assembly.cpc) + (1 * hw.assembly.brlt)); generic_timing_shift_l_double(x[i], xaux, ds.b_size); y[i] = generic_timing_double_direct_form_1(yaux, xaux, ds.a, ds.b, ds.a_size, ds.b_size); generic_timing_shift_l_double(y[i], yaux, ds.a_size); # 88 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" double spent_time = (((double) generic_timer) * hw.cycle); # 89 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" 3 4 ((void) sizeof (( # 89 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" spent_time <= ds.sample_time # 89 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 89 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" spent_time <= ds.sample_time # 89 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" 3 4 ) ; else __assert_fail ( # 89 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" "spent_time <= ds.sample_time" # 89 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h", 89, __extension__ __PRETTY_FUNCTION__); })) # 89 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_generic_timing.h" ; generic_timer = initial_timer; } return 0; } # 37 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_timing_msp430.h" 1 # 16 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_timing_msp430.h" int nondet_int(); float nondet_float(); extern digital_system ds; extern implementation impl; int verify_timing_msp_430(void) { double y[X_SIZE_VALUE]; double x[X_SIZE_VALUE]; int i; for (i = 0; i < X_SIZE_VALUE; ++i) { y[i] = 0; x[i] = nondet_float(); __DSVERIFIER_assume(x[i] >= impl.min && x[i] <= impl.max); } int Nw = 0; Nw = ds.a_size > ds.b_size ? ds.a_size : ds.b_size; double yaux[ds.a_size]; double xaux[ds.b_size]; double waux[Nw]; for (i = 0; i < ds.a_size; ++i) { yaux[i] = 0; } for (i = 0; i < ds.b_size; ++i) { xaux[i] = 0; } for (i = 0; i < Nw; ++i) { waux[i] = 0; } double xk, temp; double *aptr, *bptr, *xptr, *yptr, *wptr; int j; for (i = 0; i < X_SIZE_VALUE; ++i) { shiftL(x[i], xaux, ds.b_size); y[i] = double_direct_form_1_MSP430(yaux, xaux, ds.a, ds.b, ds.a_size, ds.b_size); shiftL(y[i], yaux, ds.a_size); # 121 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_timing_msp430.h" } return 0; } # 38 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" 1 # 21 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" extern digital_system ds; extern implementation impl; int verify_stability(void){ overflow_mode = 0; fxp_t a_fxp[ds.a_size]; fxp_double_to_fxp_array(ds.a, a_fxp, ds.a_size); double _a[ds.a_size]; fxp_to_double_array(_a, a_fxp, ds.a_size); # 37 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" 3 4 ((void) sizeof (( # 37 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" check_stability(_a, ds.a_size) # 37 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 37 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" check_stability(_a, ds.a_size) # 37 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" 3 4 ) ; else __assert_fail ( # 37 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" "check_stability(_a, ds.a_size)" # 37 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h", 37, __extension__ __PRETTY_FUNCTION__); })) # 37 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" ; # 83 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability.h" return 0; } # 39 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_minimum_phase.h" 1 # 21 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_minimum_phase.h" extern digital_system ds; extern implementation impl; int verify_minimum_phase(void){ overflow_mode = 0; fxp_t b_fxp[ds.b_size]; fxp_double_to_fxp_array(ds.b, b_fxp, ds.b_size); double _b[ds.b_size]; fxp_to_double_array(_b, b_fxp, ds.b_size); __DSVERIFIER_assert(check_stability(_b, ds.b_size)); # 85 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_minimum_phase.h" return 0; } # 40 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability_closedloop.h" 1 # 17 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability_closedloop.h" extern digital_system plant; extern digital_system plant_cbmc; extern digital_system controller; int verify_stability_closedloop_using_dslib(void){ double * c_num = controller.b; int c_num_size = controller.b_size; double * c_den = controller.a; int c_den_size = controller.a_size; fxp_t c_num_fxp[controller.b_size]; fxp_double_to_fxp_array(c_num, c_num_fxp, controller.b_size); fxp_t c_den_fxp[controller.a_size]; fxp_double_to_fxp_array(c_den, c_den_fxp, controller.a_size); double c_num_qtz[controller.b_size]; fxp_to_double_array(c_num_qtz, c_num_fxp, controller.b_size); double c_den_qtz[controller.a_size]; fxp_to_double_array(c_den_qtz, c_den_fxp, controller.a_size); # 48 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability_closedloop.h" double * p_num = plant_cbmc.b; int p_num_size = plant.b_size; double * p_den = plant_cbmc.a; int p_den_size = plant.a_size; double ans_num[100]; int ans_num_size = controller.b_size + plant.b_size - 1; double ans_den[100]; int ans_den_size = controller.a_size + plant.a_size - 1; # 68 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_stability_closedloop.h" printf("Verifying stability for closedloop function\n"); __DSVERIFIER_assert(check_stability_closedloop(ans_den, ans_den_size, p_num, p_num_size, p_den, p_den_size)); return 0; } # 41 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle_closedloop.h" 1 # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle_closedloop.h" extern digital_system plant; extern digital_system plant_cbmc; extern digital_system controller; double nondet_double(); int verify_limit_cycle_closed_loop(void){ overflow_mode = 3; double * c_num = controller.b; int c_num_size = controller.b_size; double * c_den = controller.a; int c_den_size = controller.a_size; fxp_t c_num_fxp[controller.b_size]; fxp_double_to_fxp_array(c_num, c_num_fxp, controller.b_size); fxp_t c_den_fxp[controller.a_size]; fxp_double_to_fxp_array(c_den, c_den_fxp, controller.a_size); double c_num_qtz[controller.b_size]; fxp_to_double_array(c_num_qtz, c_num_fxp, controller.b_size); double c_den_qtz[controller.a_size]; fxp_to_double_array(c_den_qtz, c_den_fxp, controller.a_size); # 58 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle_closedloop.h" double * p_num = plant_cbmc.b; int p_num_size = plant.b_size; double * p_den = plant_cbmc.a; int p_den_size = plant.a_size; double ans_num[100]; int ans_num_size = controller.b_size + plant.b_size - 1; double ans_den[100]; int ans_den_size = controller.a_size + plant.a_size - 1; int i; double y[X_SIZE_VALUE]; double x[X_SIZE_VALUE]; double xaux[ans_num_size]; double nondet_constant_input = nondet_double(); __DSVERIFIER_assume(nondet_constant_input >= impl.min && nondet_constant_input <= impl.max); for (i = 0; i < X_SIZE_VALUE; ++i) { x[i] = nondet_constant_input; y[i] = 0; } for (i = 0; i < ans_num_size; ++i) { xaux[i] = nondet_constant_input; } double yaux[ans_den_size]; double y0[ans_den_size]; int Nw = ans_den_size > ans_num_size ? ans_den_size : ans_num_size; double waux[Nw]; double w0[Nw]; for (i = 0; i < ans_den_size; ++i) { yaux[i] = nondet_int(); __DSVERIFIER_assume(yaux[i] >= impl.min && yaux[i] <= impl.max); y0[i] = yaux[i]; } # 112 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle_closedloop.h" double xk, temp; double *aptr, *bptr, *xptr, *yptr, *wptr; int j; for(i=0; i<X_SIZE_VALUE; ++i){ shiftLDouble(x[i], xaux, ans_num_size); y[i] = double_direct_form_1(yaux, xaux, ans_den, ans_num, ans_den_size, ans_num_size); shiftLDouble(y[i], yaux, ans_den_size); # 137 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_limit_cycle_closedloop.h" } double_check_persistent_limit_cycle(y, X_SIZE_VALUE); return 0; } # 42 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_closedloop.h" 1 # 23 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_closedloop.h" extern digital_system plant; extern digital_system plant_cbmc; extern digital_system controller; int verify_error_closedloop(void){ overflow_mode = 3; double * c_num = controller.b; int c_num_size = controller.b_size; double * c_den = controller.a; int c_den_size = controller.a_size; fxp_t c_num_fxp[controller.b_size]; fxp_double_to_fxp_array(c_num, c_num_fxp, controller.b_size); fxp_t c_den_fxp[controller.a_size]; fxp_double_to_fxp_array(c_den, c_den_fxp, controller.a_size); double c_num_qtz[controller.b_size]; fxp_to_double_array(c_num_qtz, c_num_fxp, controller.b_size); double c_den_qtz[controller.a_size]; fxp_to_double_array(c_den_qtz, c_den_fxp, controller.a_size); # 56 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_closedloop.h" double * p_num = plant_cbmc.b; int p_num_size = plant.b_size; double * p_den = plant_cbmc.a; int p_den_size = plant.a_size; double ans_num_double[100]; double ans_num_qtz[100]; int ans_num_size = controller.b_size + plant.b_size - 1; double ans_den_qtz[100]; double ans_den_double[100]; int ans_den_size = controller.a_size + plant.a_size - 1; # 77 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_closedloop.h" int i; double y_qtz[X_SIZE_VALUE]; double y_double[X_SIZE_VALUE]; double x_qtz[X_SIZE_VALUE]; double x_double[X_SIZE_VALUE]; double xaux_qtz[ans_num_size]; double xaux_double[ans_num_size]; double xaux[ans_num_size]; double nondet_constant_input = nondet_double(); __DSVERIFIER_assume(nondet_constant_input >= impl.min && nondet_constant_input <= impl.max); for (i = 0; i < X_SIZE_VALUE; ++i) { x_qtz[i] = nondet_constant_input; x_double[i] = nondet_constant_input; y_qtz[i] = 0; y_double[i] = 0; } for (i = 0; i < ans_num_size; ++i) { xaux_qtz[i] = nondet_constant_input; xaux_double[i] = nondet_constant_input; } double yaux_qtz[ans_den_size]; double yaux_double[ans_den_size]; double y0_qtz[ans_den_size]; double y0_double[ans_den_size]; int Nw = ans_den_size > ans_num_size ? ans_den_size : ans_num_size; double waux_qtz[Nw]; double waux_double[Nw]; double w0_qtz[Nw]; double w0_double[Nw]; for (i = 0; i < ans_den_size; ++i) { yaux_qtz[i] = 0; yaux_double[i] = 0; } for(i=0; i<X_SIZE_VALUE; ++i){ shiftLDouble(x_qtz[i], xaux_qtz, ans_num_size); y_qtz[i] = double_direct_form_1(yaux_qtz, xaux_qtz, ans_den_qtz, ans_num_qtz, ans_den_size, ans_num_size); shiftLDouble(y_qtz[i], yaux_qtz, ans_den_size); shiftLDouble(x_double[i], xaux_double, ans_num_size); y_double[i] = double_direct_form_1(yaux_double, xaux_double, ans_den_double, ans_num_double, ans_den_size, ans_num_size); shiftLDouble(y_double[i], yaux_double, ans_den_size); # 156 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_closedloop.h" double absolute_error = y_double[i] - fxp_to_double(y_qtz[i]); __DSVERIFIER_assert(absolute_error < (impl.max_error) && absolute_error > (-impl.max_error)); } return 0; } # 43 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" 1 # 20 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" extern digital_system_state_space _controller; extern double error_limit; extern int closed_loop; double new_state[4][4]; double new_stateFWL[4][4]; digital_system_state_space _controller_fxp; digital_system_state_space _controller_double; double ss_system_quantization_error(fxp_t inputs){ digital_system_state_space __backupController; int i; int j; _controller.inputs[0][0] = inputs; for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ __backupController.A[i][j]= (_controller.A[i][j]); } } for(i=0; i<nStates;i++){ for(j=0; j<nInputs;j++){ __backupController.B[i][j]= (_controller.B[i][j]); } } for(i=0; i<nOutputs;i++){ for(j=0; j<nStates;j++){ __backupController.C[i][j]= (_controller.C[i][j]); } } for(i=0; i<nOutputs;i++){ for(j=0; j<nInputs;j++){ __backupController.D[i][j]= (_controller.D[i][j]); } } for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ __backupController.states[i][j]= (_controller.states[i][j]); } } for(i=0; i<nInputs;i++){ for(j=0; j<1;j++){ __backupController.inputs[i][j]= (_controller.inputs[i][j]); } } for(i=0; i<nOutputs;i++){ for(j=0; j<1;j++){ __backupController.outputs[i][j]= (_controller.outputs[i][j]); } } double __quant_error = 0.0; for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ _controller.states[i][j]= (new_state[i][j]); } } double output_double = double_state_space_representation(); for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ new_state[i][j]= (_controller.states[i][j]); } } __backupController.inputs[0][0] = inputs; for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ _controller.A[i][j] = __backupController.A[i][j]; } } for(i=0; i<nStates;i++){ for(j=0; j<nInputs;j++){ _controller.B[i][j] = __backupController.B[i][j]; } } for(i=0; i<nOutputs;i++){ for(j=0; j<nStates;j++){ _controller.C[i][j] = __backupController.C[i][j]; } } for(i=0; i<nOutputs;i++){ for(j=0; j<nInputs;j++){ _controller.D[i][j] = __backupController.D[i][j]; } } for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ _controller.states[i][j] = __backupController.states[i][j]; } } for(i=0; i<nInputs;i++){ for(j=0; j<1;j++){ _controller.inputs[i][j] = __backupController.inputs[i][j]; } } for(i=0; i<nOutputs;i++){ for(j=0; j<1;j++){ _controller.outputs[i][j] = __backupController.outputs[i][j]; } } for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ _controller.states[i][j]= (new_stateFWL[i][j]); } } double output_fxp = fxp_state_space_representation(); for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ new_stateFWL[i][j]= (_controller.states[i][j]); } } __quant_error = output_double - output_fxp; return __quant_error; } double fxp_ss_closed_loop_quantization_error(double reference){ double reference_aux[4][4]; double result1[4][4]; double temp_result1[4][4]; double result2[4][4]; double temp_states[4][4]; fxp_t K_fxp[4][4]; fxp_t states_fxp[4][4]; fxp_t result_fxp[4][4]; unsigned int i; unsigned int j; unsigned int k; short unsigned int flag = 0; for(i=0; i<nOutputs;i++){ for(j=0; j<nInputs;j++){ if(_controller_fxp.D[i][j] != 0){ flag = 1; } } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ reference_aux[i][j]=0; K_fxp[i][j] = 0; } } for(i=0; i<nInputs;i++){ reference_aux[i][0]= reference; } for(i=0; i<4;i++){ states_fxp[i][0]=0; } for(i=0; i<nStates;i++){ K_fxp[0][i]= fxp_double_to_fxp(_controller_fxp.K[0][i]); } for(i=0; i<4;i++){ for(j=0; j<4;j++){ result1[i][j]=0; result2[i][j]=0; } } for(k=0; k<nStates;k++) { states_fxp[k][0]= fxp_double_to_fxp(_controller_fxp.states[k][0]); } fxp_matrix_multiplication(nOutputs,nStates,nStates,1,K_fxp,states_fxp,result_fxp); fxp_t reference_fxp[4][4]; fxp_t result_fxp2[4][4]; for(k=0;k<nInputs;k++) { reference_fxp[k][0] =fxp_double_to_fxp(fxp_quantize(reference_aux[k][0])); } fxp_sub_matrix(nInputs,1, reference_fxp, result_fxp, result_fxp2); for(k=0; k<nInputs;k++) { _controller_fxp.inputs[k][0] = fxp_to_double(fxp_quantize(result_fxp2[k][0])); } double_matrix_multiplication(nOutputs,nStates,nStates,1,_controller_fxp.C,_controller_fxp.states,result1); if(flag == 1) { double_matrix_multiplication(nOutputs,nInputs,nInputs,1,_controller_fxp.D,_controller_fxp.inputs,result2); } double_add_matrix(nOutputs,1,result1,result2,_controller_fxp.outputs); double_matrix_multiplication(nStates,nStates,nStates,1,_controller_fxp.A,_controller_fxp.states,result1); double_matrix_multiplication(nStates,nInputs,nInputs,1,_controller_fxp.B,_controller_fxp.inputs,result2); double_add_matrix(nStates,1,result1,result2,_controller_fxp.states); return _controller_fxp.outputs[0][0]; } double ss_closed_loop_quantization_error(double reference){ double reference_aux[4][4]; double result1[4][4]; double result2[4][4]; unsigned int i; unsigned int j; short unsigned int flag = 0; for(i=0; i<nOutputs;i++){ for(j=0; j<nInputs;j++){ if(_controller_double.D[i][j] != 0){ flag = 1; } } } for(i=0; i<nInputs;i++){ for(j=0; j<1;j++){ reference_aux[i][j]= reference; } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ result1[i][j]=0; result2[i][j]=0; } } double_matrix_multiplication(nOutputs,nStates,nStates,1,_controller_double.K,_controller_double.states,result1); double_sub_matrix(nInputs,1,reference_aux,result1, _controller_double.inputs); double_matrix_multiplication(nOutputs,nStates,nStates,1,_controller_double.C,_controller_double.states,result1); if(flag == 1) double_matrix_multiplication(nOutputs,nInputs,nInputs,1,_controller_double.D,_controller_double.inputs,result2); double_add_matrix(nOutputs,1,result1,result2,_controller_double.outputs); double_matrix_multiplication(nStates,nStates,nStates,1,_controller_double.A,_controller_double.states,result1); double_matrix_multiplication(nStates,nInputs,nInputs,1,_controller_double.B,_controller_double.inputs,result2); double_add_matrix(nStates,1,result1,result2,_controller_double.states); return _controller_double.outputs[0][0]; } int verify_error_state_space(void){ int i,j; for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ new_state[i][j]= (_controller.states[i][j]); } } for(i=0; i<nStates;i++){ for(j=0; j<1;j++){ new_stateFWL[i][j]= (_controller.states[i][j]); } } _controller_fxp = _controller; _controller_double = _controller; overflow_mode = 0; fxp_t x[0]; fxp_t min_fxp = fxp_double_to_fxp(impl.min); fxp_t max_fxp = fxp_double_to_fxp(impl.max); double nondet_constant_input = nondet_double(); __DSVERIFIER_assume(nondet_constant_input >= min_fxp && nondet_constant_input <= max_fxp); for (i = 0; i < 0; ++i) { x[i] = nondet_constant_input; } double __quant_error; if(closed_loop){ for (i = 0; i < 0; ++i) { __quant_error = ss_closed_loop_quantization_error(x[i]) - fxp_ss_closed_loop_quantization_error(x[i]); # 354 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" 3 4 ((void) sizeof (( # 354 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" __quant_error < error_limit && __quant_error > ((-1)*error_limit) # 354 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 354 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" __quant_error < error_limit && __quant_error > ((-1)*error_limit) # 354 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" 3 4 ) ; else __assert_fail ( # 354 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" "__quant_error < error_limit && __quant_error > ((-1)*error_limit)" # 354 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h", 354, __extension__ __PRETTY_FUNCTION__); })) # 354 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" ; } } else { for (i=0; i < 0; i++) { __quant_error = ss_system_quantization_error(x[i]); # 361 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" 3 4 ((void) sizeof (( # 361 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" __quant_error < error_limit && __quant_error > ((-1)*error_limit) # 361 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 361 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" __quant_error < error_limit && __quant_error > ((-1)*error_limit) # 361 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" 3 4 ) ; else __assert_fail ( # 361 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" "__quant_error < error_limit && __quant_error > ((-1)*error_limit)" # 361 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h", 361, __extension__ __PRETTY_FUNCTION__); })) # 361 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_error_state_space.h" ; } } return 0; } # 44 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" 1 # 17 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" extern digital_system_state_space _controller; extern double error_limit; extern int closed_loop; double fxp_ss_closed_loop_safety(){ double reference[4][4]; double result1[4][4]; double result2[4][4]; fxp_t K_fpx[4][4]; fxp_t outputs_fpx[4][4]; fxp_t result_fxp[4][4]; unsigned int i; unsigned int j; unsigned int k; short unsigned int flag = 0; for(i=0; i<nOutputs;i++){ for(j=0; j<nInputs;j++){ if(_controller.D[i][j] != 0){ flag = 1; } } } for(i=0; i<nInputs;i++){ for(j=0; j<1;j++){ reference[i][j]= (_controller.inputs[i][j]); } } for(i=0; i<nInputs;i++){ for(j=0; j<nOutputs;j++){ K_fpx[i][j]=0; } } for(i=0; i<nOutputs;i++){ for(j=0; j<1;j++){ outputs_fpx[i][j]=0; } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ result_fxp[i][j]=0; } } for(i=0; i<nInputs;i++){ for(j=0; j<nOutputs;j++){ K_fpx[i][j]= fxp_double_to_fxp(_controller.K[i][j]); } } for(i=0; i<4;i++){ for(j=0; j<4;j++){ result1[i][j]=0; result2[i][j]=0; } } for (i = 1; i < 0; i++) { double_matrix_multiplication(nOutputs,nStates,nStates,1,_controller.C,_controller.states,result1); if(flag == 1){ double_matrix_multiplication(nOutputs,nInputs,nInputs,1,_controller.D,_controller.inputs,result2); } double_add_matrix(nOutputs, 1, result1, result2, _controller.outputs); for(k=0; k<nOutputs;k++){ for(j=0; j<1;j++){ outputs_fpx[k][j]= fxp_double_to_fxp(_controller.outputs[k][j]); } } fxp_matrix_multiplication(nInputs,nOutputs,nOutputs,1,K_fpx,outputs_fpx,result_fxp); for(k=0; k<nInputs;k++){ for(j=0; j<1;j++){ result1[k][j]= fxp_to_double(result_fxp[k][j]); } } printf("### fxp: U (before) = %.9f", _controller.inputs[0][0]); printf("### fxp: reference = %.9f", reference[0][0]); printf("### fxp: result1 = %.9f", result1[0][0]); printf("### fxp: reference - result1 = %.9f", (reference[0][0] - result1[0][0])); double_sub_matrix(nInputs, 1, reference, result1, _controller.inputs); printf("### fxp: Y = %.9f", _controller.outputs[0][0]); printf("### fxp: U (after) = %.9f \n### \n### ", _controller.inputs[0][0]); double_matrix_multiplication(nStates,nStates,nStates,1,_controller.A,_controller.states,result1); double_matrix_multiplication(nStates,nInputs,nInputs,1,_controller.B,_controller.inputs,result2); double_add_matrix(nStates, 1, result1, result2, _controller.states); } return _controller.outputs[0][0]; } int verify_safety_state_space(void){ fxp_t output_fxp = fxp_ss_closed_loop_safety(); double output_double = fxp_to_double(output_fxp); # 140 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" 3 4 ((void) sizeof (( # 140 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" output_double <= error_limit # 140 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 140 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" output_double <= error_limit # 140 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" 3 4 ) ; else __assert_fail ( # 140 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" "output_double <= error_limit" # 140 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h", 140, __extension__ __PRETTY_FUNCTION__); })) # 140 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_safety_state_space.h" ; return 0; } # 45 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 1 # 14 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" extern digital_system_state_space _controller; int verify_controllability(void){ int i; int j; fxp_t A_fpx[4][4]; fxp_t B_fpx[4][4]; fxp_t controllabilityMatrix[4][4]; fxp_t backup[4][4]; fxp_t backupSecond[4][4]; double controllabilityMatrix_double[4][4]; for(i=0; i<nStates;i++){ for(j=0; j<(nStates*nInputs);j++){ A_fpx[i][j] = 0.0; B_fpx[i][j] = 0.0; controllabilityMatrix[i][j] = 0.0; backup[i][j] = 0.0; backupSecond[i][j] = 0.0; controllabilityMatrix_double[i][j] = 0.0; } } for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ A_fpx[i][j]= fxp_double_to_fxp(_controller.A[i][j]); } } for(i=0; i<nStates;i++){ for(j=0; j<nInputs;j++){ B_fpx[i][j]= fxp_double_to_fxp(_controller.B[i][j]); } } if(nInputs > 1){ int l = 0; for(j=0; j<(nStates*nInputs);){ fxp_exp_matrix(nStates,nStates,A_fpx,l,backup); l++; fxp_matrix_multiplication(nStates,nStates,nStates,nInputs,backup,B_fpx,backupSecond); for(int k = 0; k < nInputs; k++){ for(i = 0; i<nStates;i++){ controllabilityMatrix[i][j]= backupSecond[i][k]; } j++; } } for(i=0; i<nStates;i++){ for(j=0; j<(nStates*nInputs);j++){ backup[i][j]= 0.0; } } fxp_transpose(controllabilityMatrix,backup,nStates,(nStates*nInputs)); fxp_t mimo_controllabilityMatrix_fxp[4][4]; fxp_matrix_multiplication(nStates,(nStates*nInputs),(nStates*nInputs),nStates,controllabilityMatrix,backup,mimo_controllabilityMatrix_fxp); for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ controllabilityMatrix_double[i][j]= fxp_to_double(mimo_controllabilityMatrix_fxp[i][j]); } } # 91 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ((void) sizeof (( # 91 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" determinant(controllabilityMatrix_double,nStates) != 0 # 91 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 91 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" determinant(controllabilityMatrix_double,nStates) != 0 # 91 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ) ; else __assert_fail ( # 91 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" "determinant(controllabilityMatrix_double,nStates) != 0" # 91 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h", 91, __extension__ __PRETTY_FUNCTION__); })) # 91 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" ; } else { for(j=0; j<nStates;j++){ fxp_exp_matrix(nStates,nStates,A_fpx,j,backup); fxp_matrix_multiplication(nStates,nStates,nStates,nInputs,backup,B_fpx,backupSecond); for(i = 0; i<nStates;i++){ controllabilityMatrix[i][j]= backupSecond[i][0]; } } for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ controllabilityMatrix_double[i][j]= fxp_to_double(controllabilityMatrix[i][j]); } } # 113 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ((void) sizeof (( # 113 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" determinant(controllabilityMatrix_double,nStates) != 0 # 113 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 113 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" determinant(controllabilityMatrix_double,nStates) != 0 # 113 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ) ; else __assert_fail ( # 113 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" "determinant(controllabilityMatrix_double,nStates) != 0" # 113 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h", 113, __extension__ __PRETTY_FUNCTION__); })) # 113 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" ; } return 0; } int verify_controllability_double(void){ int i; int j; double controllabilityMatrix[4][4]; double backup[4][4]; double backupSecond[4][4]; double controllabilityMatrix_double[4][4]; if(nInputs > 1){ int l = 0; for(j=0; j<(nStates*nInputs);){ double_exp_matrix(nStates,nStates,_controller.A,l,backup); l++; double_matrix_multiplication(nStates,nStates,nStates,nInputs,backup,_controller.B,backupSecond); for(int k = 0; k < nInputs; k++){ for(i = 0; i<nStates;i++){ controllabilityMatrix[i][j]= backupSecond[i][k]; } j++; } } for(i=0; i<nStates;i++){ for(j=0; j<(nStates*nInputs);j++){ backup[i][j]= 0.0; } } transpose(controllabilityMatrix,backup,nStates,(nStates*nInputs)); double mimo_controllabilityMatrix_double[4][4]; double_matrix_multiplication(nStates,(nStates*nInputs),(nStates*nInputs),nStates,controllabilityMatrix,backup,mimo_controllabilityMatrix_double); # 154 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ((void) sizeof (( # 154 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" determinant(mimo_controllabilityMatrix_double,nStates) != 0 # 154 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 154 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" determinant(mimo_controllabilityMatrix_double,nStates) != 0 # 154 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ) ; else __assert_fail ( # 154 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" "determinant(mimo_controllabilityMatrix_double,nStates) != 0" # 154 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h", 154, __extension__ __PRETTY_FUNCTION__); })) # 154 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" ; } else { for(j=0; j<nStates;j++){ double_exp_matrix(nStates,nStates,_controller.A,j,backup); double_matrix_multiplication(nStates,nStates,nStates,nInputs,backup,_controller.B,backupSecond); for(i = 0; i<nStates;i++){ controllabilityMatrix[i][j]= backupSecond[i][0]; } } # 163 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ((void) sizeof (( # 163 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" determinant(controllabilityMatrix,nStates) != 0 # 163 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 163 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" determinant(controllabilityMatrix,nStates) != 0 # 163 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 ) ; else __assert_fail ( # 163 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" "determinant(controllabilityMatrix,nStates) != 0" # 163 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h", 163, __extension__ __PRETTY_FUNCTION__); })) # 163 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_controllability.h" ; } return 0; } # 46 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" 1 # 17 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" extern digital_system_state_space _controller; int verify_observability(void){ int i; int j; fxp_t A_fpx[4][4]; fxp_t C_fpx[4][4]; fxp_t observabilityMatrix[4][4]; fxp_t backup[4][4]; fxp_t backupSecond[4][4]; double observabilityMatrix_double[4][4]; for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ observabilityMatrix[i][j]= 0; A_fpx[i][j]=0; C_fpx[i][j]= 0; backup[i][j]= 0; backupSecond[i][j]= 0; } } for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ A_fpx[i][j]= fxp_double_to_fxp(_controller.A[i][j]); } } for(i=0; i<nOutputs;i++){ for(j=0; j<nStates;j++){ C_fpx[i][j]= fxp_double_to_fxp(_controller.C[i][j]); } } if(nOutputs > 1){ int l; j = 0; for(l=0; l<nStates;){ fxp_exp_matrix(nStates,nStates,A_fpx,l,backup); l++; fxp_matrix_multiplication(nOutputs,nStates,nStates,nStates,C_fpx,backup,backupSecond); for(int k = 0; k < nOutputs; k++){ for(i = 0; i<nStates;i++){ observabilityMatrix[j][i]= backupSecond[k][i]; } j++; } } # 80 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" for(i=0; i<nStates;i++){ for(j=0; j<(nStates*nOutputs);j++){ backup[i][j]= 0.0; } } fxp_transpose(observabilityMatrix,backup,(nStates*nOutputs),nStates); # 99 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" fxp_t mimo_observabilityMatrix_fxp[4][4]; fxp_matrix_multiplication(nStates,(nStates*nOutputs),(nStates*nOutputs),nStates,backup,observabilityMatrix,mimo_observabilityMatrix_fxp); # 112 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ observabilityMatrix_double[i][j]= fxp_to_double(mimo_observabilityMatrix_fxp[i][j]); } } # 119 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" 3 4 ((void) sizeof (( # 119 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" determinant(observabilityMatrix_double,nStates) != 0 # 119 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 119 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" determinant(observabilityMatrix_double,nStates) != 0 # 119 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" 3 4 ) ; else __assert_fail ( # 119 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" "determinant(observabilityMatrix_double,nStates) != 0" # 119 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h", 119, __extension__ __PRETTY_FUNCTION__); })) # 119 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" ; }else{ for(i=0; i<nStates;i++){ fxp_exp_matrix(nStates,nStates,A_fpx,i,backup); fxp_matrix_multiplication(nOutputs,nStates,nStates,nStates,C_fpx,backup,backupSecond); for(j = 0; j<nStates;j++){ observabilityMatrix[i][j]= backupSecond[0][j]; } } for(i=0; i<nStates;i++){ for(j=0; j<nStates;j++){ observabilityMatrix_double[i][j]= fxp_to_double(observabilityMatrix[i][j]); } } # 134 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" 3 4 ((void) sizeof (( # 134 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" determinant(observabilityMatrix_double,nStates) != 0 # 134 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" 3 4 ) ? 1 : 0), __extension__ ({ if ( # 134 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" determinant(observabilityMatrix_double,nStates) != 0 # 134 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" 3 4 ) ; else __assert_fail ( # 134 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" "determinant(observabilityMatrix_double,nStates) != 0" # 134 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" 3 4 , "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h", 134, __extension__ __PRETTY_FUNCTION__); })) # 134 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_observability.h" ; } return 0; } # 47 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 # 1 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_magnitude.h" 1 # 16 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_magnitude.h" extern filter_parameters filter; extern implementation impl; extern digital_system ds; # 28 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/engine/verify_magnitude.h" void resp_mag(double* num, int lnum, double* den, int lden, double* res, int N) { double w; int m, i; double out_numRe[N + 1]; double out_numIm[N + 1]; double out_denRe[N + 1]; double out_denIm[N + 1]; double old_out_Re; double zero_test; for (w = 0, i = 0; w <= 3.14159265358979323846; w += 3.14159265358979323846 / N, ++i) { out_numRe[i] = num[0]; out_numIm[i] = 0; for (m = 1; m < lnum; ++m) { old_out_Re = out_numRe[i]; out_numRe[i] = cosTyl(w, 6) * out_numRe[i] - sinTyl(w, 6) * out_numIm[i] + num[m]; out_numIm[i] = sinTyl(w, 6) * old_out_Re + cosTyl(w, 6) * out_numIm[i]; } out_denRe[i] = den[0]; out_denIm[i] = 0; for (m = 1; m < lden; ++m) { old_out_Re = out_denRe[i]; out_denRe[i] = cosTyl(w, 6) * out_denRe[i] - sinTyl(w, 6) * out_denIm[i] + den[m]; out_denIm[i] = sinTyl(w, 6) * old_out_Re + cosTyl(w, 6) * out_denIm[i]; } res[i] = sqrt3(out_numRe[i] * out_numRe[i] + out_numIm[i] * out_numIm[i]); zero_test = sqrt3(out_denRe[i] * out_denRe[i] + out_denIm[i] * out_denIm[i]); __DSVERIFIER_assume(zero_test != 0); res[i] = res[i] / zero_test; } } int verify_magnitude(void) { int freq_response_samples = 100; double w; double w_incr = 1.0 / freq_response_samples; double res[freq_response_samples+1]; int i,j; fxp_t a_fxp[ds.a_size]; fxp_double_to_fxp_array(ds.a, a_fxp, ds.a_size); double _a[ds.a_size]; fxp_to_double_array(_a, a_fxp, ds.a_size); fxp_t b_fxp[ds.b_size]; fxp_double_to_fxp_array(ds.b, b_fxp, ds.b_size); double _b[ds.b_size]; fxp_to_double_array(_b, b_fxp, ds.b_size); resp_mag(ds.b, ds.b_size, ds.a, ds.a_size, res, freq_response_samples); if (filter.type == 1) { for (i = 0, w = 0; (w <= 1.0); ++i, w += w_incr) { if (w <= filter.wp) { __DSVERIFIER_assert_msg(res[i] >= filter.Ap, "|----------------Passband Failure-------------|"); } else if (w == filter.wc) { __DSVERIFIER_assert_msg(res[i] <= filter.Ac, "|-------------Cutoff Frequency Failure--------|"); } else if ((w >= filter.wr) && (w <= 1)) { __DSVERIFIER_assert_msg(res[i] <= filter.Ar, "|----------------Stopband Failure-------------|"); } } } else if (filter.type == 2) { for (i = 0, w = 0; (w <= 1.0); ++i, w += w_incr) { if (w <= filter.wr) { __DSVERIFIER_assert_msg(res[i] <= filter.Ar, "|----------------Stopband Failure-------------|"); } else if (w == filter.wc) { __DSVERIFIER_assert_msg(res[i] <= filter.Ac, "|-------------Cutoff Frequency Failure--------|"); } else if ((w > filter.wp) && (w <= 1)) { __DSVERIFIER_assert_msg(res[i] >= filter.Ap, "|----------------Passband Failure-------------|"); } } } else { __DSVERIFIER_assert(0); } return 0; } # 48 "/home/yashchopda/Desktop/dsverifier-v2.0.3-esbmc-v4.0-cbmc-5.6/bmc/dsverifier.h" 2 extern digital_system ds; extern digital_system plant; digital_system plant_cbmc; extern digital_system controller; extern implementation impl; extern hardware hw; extern digital_system_state_space _controller; extern filter_parameters filter; unsigned int nondet_uint(); extern void initials(); void validation(); void call_verification_task(void * verification_task); void call_closedloop_verification_task(void * closedloop_verification_task); float nondet_float(); double nondet_double(); int main(){ initialization(); validation(); if (1 == 0) rounding_mode = 0; else if (1 == 1) rounding_mode = 1; else if (1 == 2) rounding_mode = 2; if (7 == 3) { call_verification_task(&verify_overflow); } else if (7 == 2) { call_verification_task(&verify_limit_cycle); } else if (7 == 6) { call_verification_task(&verify_error); } else if (7 == 1) { call_verification_task(&verify_zero_input_limit_cycle); } else if (7 == 4) { call_verification_task(&verify_timing_msp_430); } else if (7 == 5) { call_verification_task(&verify_generic_timing); } else if (7 == 7) { call_verification_task(&verify_stability); } else if (7 == 8) { call_verification_task(&verify_minimum_phase); } else if (7 == 9) { call_closedloop_verification_task(&verify_stability_closedloop_using_dslib); } else if (7 == 10) { call_closedloop_verification_task(&verify_limit_cycle_closed_loop); } else if (7 == 11) { call_closedloop_verification_task(&verify_error_closedloop); } else if (7 == 12) { verify_error_state_space(); } else if (7 == 16) { verify_safety_state_space(); } else if (7 == 13) { verify_controllability(); } else if (7 == 14) { verify_observability(); } else if (7 == 15) { verify_limit_cycle_state_space(); } else if (7 == 18) { call_verification_task(&verify_magnitude); } return 0; } void validation() { if (7 == 12 || 7 == 16 || 7 == 15 || 7 == 13 || 7 == 14) { if (0 == 0) { printf("\n\n********************************************************************************************\n"); printf("* set a K_SIZE to use this property in DSVerifier (use: -DK_SIZE=VALUE) *\n"); printf("********************************************************************************************\n"); __DSVERIFIER_assert(0); exit(1); } initials(); return; } if (((7 != 9) && (7 != 10) && (7 != 11)) && (ds.a_size == 0 || ds.b_size == 0)) { printf("\n\n****************************************************************************\n"); printf("* set (ds and impl) parameters to check with DSVerifier *\n"); printf("****************************************************************************\n"); __DSVERIFIER_assert(0); } if ((7 == 9) || (7 == 10) || (7 == 11)) { if (controller.a_size == 0 || plant.b_size == 0 || impl.int_bits == 0 ) { printf("\n\n*****************************************************************************************************\n"); printf("* set (controller, plant, and impl) parameters to check CLOSED LOOP with DSVerifier *\n"); printf("*****************************************************************************************************\n"); __DSVERIFIER_assert(0); } else { printf("\n\n*****************************************************************************************************\n"); printf("* set (controller and impl) parameters so that they do not overflow *\n"); printf("*****************************************************************************************************\n"); unsigned j; for (j = 0; j < controller.a_size; ++j) { const double value=controller.a[j]; __DSVERIFIER_assert(value <= _dbl_max); __DSVERIFIER_assert(value >= _dbl_min); } for (j = 0; j < controller.b_size; ++j) { const double value=controller.b[j]; __DSVERIFIER_assert(value <= _dbl_max); __DSVERIFIER_assert(value >= _dbl_min); } } if (controller.b_size > 0) { unsigned j, zeros=0; for (j = 0; j < controller.b_size; ++j) { if (controller.b[j]==0) ++zeros; } if (zeros == controller.b_size) { printf("\n\n*****************************************************************************************************\n"); printf("* The controller numerator must not be zero *\n"); printf("*****************************************************************************************************\n"); __DSVERIFIER_assert(0); } } if (controller.a_size > 0) { unsigned j, zeros=0; for (j = 0; j < controller.a_size; ++j) { if (controller.a[j]==0) ++zeros; } if (zeros == controller.a_size) { printf("\n\n*****************************************************************************************************\n"); printf("* The controller denominator must not be zero *\n"); printf("*****************************************************************************************************\n"); __DSVERIFIER_assert(0); } } if (0 == 0) { printf("\n\n***************************************************************************************************************\n"); printf("* set a connection mode to check CLOSED LOOP with DSVerifier (use: --connection-mode TYPE) *\n"); printf("***************************************************************************************************************\n"); __DSVERIFIER_assert(0); } } if (7 == 0) { printf("\n\n***************************************************************************************\n"); printf("* set the property to check with DSVerifier (use: --property NAME) *\n"); printf("***************************************************************************************\n"); __DSVERIFIER_assert(0); } if ((7 == 3) || (7 == 2) || (7 == 1) || (7 == 10) || (7 == 11) || (7 == 4 || 7 == 5) || 7 == 6) { if ((5 == 0) && !(0 == 1)) { printf("\n\n********************************************************************************************\n"); printf("* set a X_SIZE to use this property in DSVerifier (use: --x-size VALUE) *\n"); printf("********************************************************************************************\n"); __DSVERIFIER_assert(0); } else if (0 == 1) { X_SIZE_VALUE = nondet_uint(); __DSVERIFIER_assume( X_SIZE_VALUE > (2 * ds.a_size)); } else if (5 < 0) { printf("\n\n********************************************************************************************\n"); printf("* set a X_SIZE > 0 *\n"); printf("********************************************************************************************\n"); __DSVERIFIER_assert(0); } else { X_SIZE_VALUE = 5; } } if ((1 == 0) && (7 != 9) && (7 != 18)) { printf("\n\n*********************************************************************************************\n"); printf("* set the realization to check with DSVerifier (use: --realization NAME) *\n"); printf("*********************************************************************************************\n"); __DSVERIFIER_assert(0); } if (7 == 6 || 7 == 11) { if (impl.max_error == 0) { printf("\n\n***********************************************************************\n"); printf("* provide the maximum expected error (use: impl.max_error) *\n"); printf("***********************************************************************\n"); __DSVERIFIER_assert(0); } } if (7 == 4 || 7 == 5) { if (7 == 5 || 7 == 4) { if (hw.clock == 0l) { printf("\n\n***************************\n"); printf("* Clock could not be zero *\n"); printf("***************************\n"); __DSVERIFIER_assert(0); } hw.cycle = ((double) 1.0 / hw.clock); if (hw.cycle < 0) { printf("\n\n*********************************************\n"); printf("* The cycle time could not be representable *\n"); printf("*********************************************\n"); __DSVERIFIER_assert(0); } if (ds.sample_time == 0) { printf("\n\n*****************************************************************************\n"); printf("* provide the sample time of the digital system (ds.sample_time) *\n"); printf("*****************************************************************************\n"); __DSVERIFIER_assert(0); } } } if (7 == 18) { if (!((filter.Ap > 0) && (filter.Ac >0) && (filter.Ar >0))) { printf("\n\n*****************************************************************************\n"); printf("* set values bigger than 0 for Ap, Ac and Ar* \n"); printf("*****************************************************************************\n"); __DSVERIFIER_assert(0); } } if ((1 == 7) || (1 == 8) || (1 == 9) || (1 == 10) || (1 == 11) || (1 == 12)) { printf("\n\n******************************************\n"); printf("* Temporarily the cascade modes are disabled *\n"); printf("**********************************************\n"); __DSVERIFIER_assert(0); } } void call_verification_task(void * verification_task) { int i = 0; _Bool base_case_executed = 0; if (0 == 2) { for(i=0; i<ds.b_size; i++) { if (ds.b_uncertainty[i] > 0) { double factor = ds.b_uncertainty[i]; factor = factor < 0 ? factor * (-1) : factor; double min = ds.b[i] - factor; double max = ds.b[i] + factor; if ((factor == 0) && (base_case_executed == 1)) { continue; } else if ((factor == 0) && (base_case_executed == 0)) { base_case_executed = 1; } ds.b[i] = nondet_double(); __DSVERIFIER_assume((ds.b[i] >= min) && (ds.b[i] <= max)); } } for(i=0; i<ds.a_size; i++) { if (ds.a_uncertainty[i] > 0) { double factor = ds.a_uncertainty[i]; factor = factor < 0 ? factor * (-1) : factor; double min = ds.a[i] - factor; double max = ds.a[i] + factor; if ((factor == 0) && (base_case_executed == 1)) { continue; } else if ((factor == 0) && (base_case_executed == 0)) { base_case_executed = 1; } ds.a[i] = nondet_double(); __DSVERIFIER_assume((ds.a[i] >= min) && (ds.a[i] <= max)); } } } else { int i=0; for(i=0; i<ds.b_size; i++) { if (ds.b_uncertainty[i] > 0) { double factor = ((ds.b[i] * ds.b_uncertainty[i]) / 100); factor = factor < 0 ? factor * (-1) : factor; double min = ds.b[i] - factor; double max = ds.b[i] + factor; if ((factor == 0) && (base_case_executed == 1)) { continue; } else if ((factor == 0) && (base_case_executed == 0)) { base_case_executed = 1; } ds.b[i] = nondet_double(); __DSVERIFIER_assume((ds.b[i] >= min) && (ds.b[i] <= max)); } } for(i=0; i<ds.a_size; i++) { if (ds.a_uncertainty[i] > 0) { double factor = ((ds.a[i] * ds.a_uncertainty[i]) / 100); factor = factor < 0 ? factor * (-1) : factor; double min = ds.a[i] - factor; double max = ds.a[i] + factor; if ((factor == 0) && (base_case_executed == 1)) { continue; } else if ((factor == 0) && (base_case_executed == 0)) { base_case_executed = 1; } ds.a[i] = nondet_double(); __DSVERIFIER_assume((ds.a[i] >= min) && (ds.a[i] <= max)); } } } ((void(*)())verification_task)(); } void call_closedloop_verification_task(void * closedloop_verification_task) { _Bool base_case_executed = 0; int i=0; for(i=0; i<plant.b_size; i++) { if (plant.b_uncertainty[i] > 0) { double factor = ((plant.b[i] * plant.b_uncertainty[i]) / 100); factor = factor < 0 ? factor * (-1) : factor; double min = plant.b[i] - factor; double max = plant.b[i] + factor; if ((factor == 0) && (base_case_executed == 1)) { continue; } else if ((factor == 0) && (base_case_executed == 0)) { base_case_executed = 1; } plant_cbmc.b[i] = nondet_double(); __DSVERIFIER_assume((plant_cbmc.b[i] >= min) && (plant_cbmc.b[i] <= max)); }else{ plant_cbmc.b[i] = plant.b[i]; } } for(i=0; i<plant.a_size; i++) { if (plant.a_uncertainty[i] > 0) { double factor = ((plant.a[i] * plant.a_uncertainty[i]) / 100); factor = factor < 0 ? factor * (-1) : factor; double min = plant.a[i] - factor; double max = plant.a[i] + factor; if ((factor == 0) && (base_case_executed == 1)) { continue; } else if ((factor == 0) && (base_case_executed == 0)) { base_case_executed = 1; } plant_cbmc.a[i] = nondet_double(); __DSVERIFIER_assume((plant_cbmc.a[i] >= min) && (plant_cbmc.a[i] <= max)); } else { plant_cbmc.a[i] = plant.a[i]; } } ((void(*)())closedloop_verification_task)(); } # 2 "benchmarks/ds-08-impl2.c" 2 digital_system ds = { .b = { 0.0096, -0.009 }, .b_size = 2, .a = { 0.02, 0.0 }, .a_size = 2, .sample_time = 0.02 }; implementation impl = { .int_bits = 4, .frac_bits = 12, .max = 1.0, .min = -1.0 };
the_stack_data/815033.c
int peakIndexInMountainArray(int* A, int ASize){ int lo = 0, hi = ASize - 1; while (lo < hi) { int mi = lo + (hi - lo) / 2; if (A[mi] < A[mi + 1]) { lo = mi + 1; } else { hi = mi; } } // return lo; return hi; }
the_stack_data/341135.c
//12 tane sayı var rastgele yazılmış ondan sonra bunların ortalamasını alıyoruz sonra input alıp //o sayı ile bu sayıları karşılaştırıyoruz #include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ int k,l,m,n,o,p,r,s,t,x,y,z; k=1,l=2,m=3,n=4,o=5,p=7,r=100,s=120,t=720,x=1440,y=1858,z=1283; printf("total=%d\n",k+l+m+x+y+z); k += r; printf("k ile r topladık k ya attık ve sonra çıkardık yine k verdi=%0.3f\n",(float) k-r); printf("%0.3f\n",(float)y/r/t/x*s); int c; printf("sayi gir: \n"); scanf("%d",&c); float total=k+l+m+x+y+z+n+o+p+r+s+t; float avg=(k+l+m+x+y+z+n+o+p+r+s+t)/12; printf("%0.3f,%d,%0.3f\n",total,c,avg); if(c>=avg){ if (c==avg) printf("equal\n"); else printf("greater than total\n"); } else printf("lower than total\n"); return 0; }
the_stack_data/126421.c
#include<stdio.h> #include<stdlib.h> #include<limits.h> void swap(int *a, int *b) { int temp; temp=*a; *a=*b; *b=temp; } void bub_sort(int a[], int b[], int n) { int i,j; for(i=0;i<n;i++) { for(j=0;j<n-1-i;j++) { if(a[j] > a[j+1]) { swap(&a[j],&a[j+1]); swap(&b[j],&b[j+1]); } } } } int main() { int i,j,n,f=0; printf("enter the no. of processes\n"); scanf("%d",&n); int tq; printf("enter the time quantum\n"); scanf("%d",&tq); int at[n]; int bt[n]; int ct[n]; int tat[n]; int wt[n]; int bt1[n]; printf("enter the arrival time\n"); for(i=0;i<n;i++) { scanf("%d",&at[i]); if(at[i]!=0) f=1; } printf("enter the burst time\n"); for(i=0;i<n;i++) scanf("%d",&bt[i]); if(f==1) bub_sort(at,bt,n); for(i=0;i<n;i++) bt1[i]=bt[i]; int counter=0,finish=0; //calculating completion time for(i=0;i<n;i++) ct[i]=0; while(1) { if(finish==n) break; for(i=0;i<n;i++) { if(counter>=at[i]) { if(bt[i]!=0 && bt[i]<tq) { counter+=bt[i]; bt[i]=0; } else if(bt[i]!=0 && bt[i]>=tq) { counter+=tq; bt[i]-=tq; } } else { counter=at[i]; continue; } if(bt[i]==0 && ct[i]==0) //compute ct { ct[i]=counter; finish++; } } } for(i=0;i<n;i++) { tat[i]=ct[i]-at[i]; wt[i]=tat[i]-bt1[i]; } float sum1=0, sum2=0; printf("Pno\tAT\tBT\tCT\tTAT\tWT\n"); for(i=0;i<n;i++) { printf("%d\t%d\t%d\t%d\t%d\t%d\n",i+1,at[i],bt1[i],ct[i],tat[i],wt[i]); sum1+=tat[i]; sum2+=wt[i]; } printf("average tat =%f\t average wt=%f\n",(float)(sum1/(float)n),(float)(sum2/(float)n)); return 0; }
the_stack_data/101367.c
/* Write a c program that will create the processes according to the following tree structure. Then print the process id and parent process id of all the processes. structure :- A(Root) B(parent:- A) C(parent:- A) D(parent:- B) E(parent:- B) F(parent:- C) */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main() { int T1, T2; printf("PPID: %lu, PID: %lu, Process A ...(i.e Parent Process created)\n", (long unsigned) getppid(), (long unsigned) getpid()); if(fork() == 0) { printf("PPID: %lu, PID: %lu, Process C... (i.e Child of Process A created)\n", (long unsigned) getppid(), (long unsigned) getpid()); if(fork() == 0) { printf("PPID: %lu, PID: %lu, Process F...(i.e child of process C cteated)\n", (long unsigned) getppid(), (long unsigned) getpid()); } wait(NULL); } else if(fork() == 0) { printf("PPID: %lu, PID: %lu, Process B...(i.e child of process A created)\n",(long unsigned) getppid(), (long unsigned) getpid()); if(fork() == 0) { printf("PPID: %lu, PID: %lu, Process D...(i.e child of process B created)\n", (long unsigned) getppid(), (long unsigned) getpid()); } else if(fork() == 0) { printf("PPID: %lu, PID: %lu, Process E...(i.e child of process B created)\n", (long unsigned) getppid(), (long unsigned) getpid()); } wait(NULL); } wait(NULL); return 0; }
the_stack_data/145453684.c
// BUG: unable to handle kernel paging request in dummy_set_vf_trust // https://syzkaller.appspot.com/bug?id=9cbfe5395ef15b0d7ffc7a572adb5cb2b251496c // status:open // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff}; int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); intptr_t res = 0; res = syscall(__NR_socket, 0x10000000a, 1, 0); if (res != -1) r[0] = res; res = syscall(__NR_socket, 0x10, 3, 0); if (res != -1) r[1] = res; memcpy((void*)0x20001bc0, "dummy0\000\000\000\000\000\000\000\000\000\000", 16); *(uint32_t*)0x20001bd0 = 0; res = syscall(__NR_ioctl, r[0], 0x8933, 0x20001bc0); if (res != -1) r[2] = *(uint32_t*)0x20001bd0; *(uint64_t*)0x200000c0 = 0; *(uint32_t*)0x200000c8 = 0; *(uint64_t*)0x200000d0 = 0x20000040; *(uint64_t*)0x20000040 = 0x20000180; memcpy((void*)0x20000180, "\x50\x00\x00\x00\x13\x00\x33\x02\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00", 20); *(uint32_t*)0x20000194 = r[2]; memcpy((void*)0x20000198, "\x00\x00\x00\x00\x00\x00\x00\x00\x30\x00\x16\x00\x2c\x00\x01\x00\x28" "\x00\x09\x00\x00\x00\x20\xff\x00\x00\x00\xfa\x78\x41\x18\x7f\xff\xe1" "\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\xfd\x76\xdf\xaf\x4c\x46\x2e\x88\x73\x45\xa8\x8f\x36\x22\x9a\x2c\x69" "\xe0\x27\xc5\x2e\x53\xca\xbb\x0b\x14\x4f\xa6\x40\x5c\x99\x9d\xfe\x87" "\x23\x88\x1c\xa6\x05\x30\x94\xea\xd0\xb3\xbe\x5c\x50\x93\x10\xf6\x9a" "\x7f\xe1\x26\xf7\x8d\xdd\x21\xb1\xa4\xd7\x34\xde\xc8\xe5\x3b\xf8\xb8" "\x1e\x8b\xdb\x9f\x21\xc4\x54\x93\x35\x03\x97\x04\xfe\xe8\x78\xef\x32" "\x3f\xa4\xa7\x29\xd1\x67\x0a\x60\x0d\x04\x29\xec\x6c\x82\x96\x4f\x37" "\x99\x40\x18\x98\x42\x95\x62\xd7\xdf\xf6\x39\xe3\x3c\xbe\x17\x9c\x2f" "\xe5\x98\x33\xec\xc8\x27\xef\x8d\xf8\x6f\x4d\x11\xe9\x50\x76\x03\x2f" "\xc2\x22\x4d\x52\x35\x59\x46\xac\xd9\xc3\x86\x67\x5d\x3a\x46\x42\x05" "\xb1\xc1\xd6\x4d\xfe\xce\xff\xd9\xec\x1f\x93\x61\xc8\xa4\x29\x34", 220); *(uint64_t*)0x20000048 = 0x50; *(uint64_t*)0x200000d8 = 1; *(uint64_t*)0x200000e0 = 0; *(uint64_t*)0x200000e8 = 0; *(uint32_t*)0x200000f0 = 0; syscall(__NR_sendmsg, r[1], 0x200000c0, 0); return 0; }
the_stack_data/115765329.c
#include <stdlib.h> #include <stdint.h> #include <assert.h> extern uint32_t platform_is_in_irq_context( void ); extern uint32_t platform_is_in_fiq_context( void ); uint32_t platform_is_in_interrupt_context( void ) { return ((platform_is_in_fiq_context()) || (platform_is_in_irq_context())); } // eof
the_stack_data/544890.c
#include<stdio.h> #include<math.h> #include <string.h> #define max(a,b) (a>b)?a:b #define min(a,b) (a<b)?a:b int n, a[65536]; int N(int l, int r) { int s = 0; int j; for (j = l; j <= r; j++)s = (s+a[j]) % n; return s; } int M(int l, int r) { int p = 1; int j; for (j = l; j <= r; j++)p = (p*a[j]) % n; return p; } int H(int l, int r) { int o = a[l]; int j; for (j = l + 1; j <= r; j++)o = o ^ a[j]; return o; } int main() { int K, l[65536], r[65536], i; scanf("%d%d", &n, &K); for (i = 0; i <= n - 1; i++)scanf("%d", &a[i]); for (i = 1; i <= K; i++)scanf("%d%d", &l[i], &r[i]); for (i = 1; i <= K; i++)printf("%d\n", H(min(N(l[i], r[i]), M(l[i], r[i])), max(N(l[i], r[i]), M(l[i], r[i])))); }
the_stack_data/950399.c
// Measure launch overhead / join time for processes (fork) or threads // (pthread_create), with optional malloc-ing before the launch to assess // effects on launch time. // // Eli Bendersky [http://eli.thegreenplace.net] // This code is in the public domain. #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/resource.h> #include <sys/time.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> static inline unsigned long long time_ns() { struct timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts)) { exit(1); } return ((unsigned long long)ts.tv_sec) * 1000000000LLU + (unsigned long long)ts.tv_nsec; } // Memory we're going to optionally allocating with malloc prioir to launching a // task. Marked volatile to thwart compiler optimizations. volatile char* v; #define min(a, b) \ ({ \ __typeof__(a) _a = (a); \ __typeof__(b) _b = (b); \ _a < _b ? _a : _b; \ }) void* threadfunc(void* p) { (void)p; return 0; } void die_with_usage(char** argv) { printf("Usage: %s <thread|fork> <mem size in MB>\n", argv[0]); exit(0); } int main(int argc, char** argv) { printf("pid = %d\n", getpid()); if (argc < 3) { die_with_usage(argv); } // If use_thread = 0, measuring pthread launch performance; otherwise // measuring fork performance. int use_thread = 0; if (!strcmp(argv[1], "thread")) { use_thread = 1; } else if (!strcmp(argv[1], "fork")) { use_thread = 0; } else { die_with_usage(argv); } int MEMSIZEMB = atoi(argv[2]); if (MEMSIZEMB > 0) { // Allocate and touch memory to make sure it's paged in. int MEMSIZE = MEMSIZEMB * 1e6; v = malloc(MEMSIZE); if (!v) { perror("malloc"); exit(1); } for (int i = 0; i < MEMSIZE; ++i) { v[i] = i; } } int N = 10000; unsigned long long minlaunch = 999999; unsigned long long totallaunch = 0; unsigned long long minjoin = 999999; unsigned long long totaljoin = 0; for (int i = 0; i < N; ++i) { pthread_t tid; unsigned long long t1 = time_ns(); if (use_thread) { if (pthread_create(&tid, NULL, threadfunc, NULL)) { perror("pthread_create"); exit(1); } } else { if (fork() == 0) { // Child. Just exit. exit(0); } // Parent. Fall through to measurement. } // Parent process, or thread. unsigned long long elapsed = time_ns() - t1; minlaunch = min(minlaunch, elapsed); totallaunch += elapsed; // Let some time pass to not count the actual child running time in // elapsed for the teardown. usleep(500); t1 = time_ns(); if (use_thread) { if (pthread_join(tid, NULL)) { perror("pthread_join"); exit(1); } } else { if (wait(NULL) == -1) { perror("wait"); exit(1); } } elapsed = time_ns() - t1; minjoin = min(minjoin, elapsed); totaljoin += elapsed; } printf("After %d iterations:\n minlaunch = %llu\n minjoin = %llu\n", N, minlaunch, minjoin); printf("Average:\n launch = %.2lf\n join = %.2lf\n", (double)totallaunch / N, (double)totaljoin / N); struct rusage ru; if (getrusage(RUSAGE_SELF, &ru)) { perror("getrusage"); } else { printf("From getrusage:\n"); printf(" max rss (KiB): %ld\n", ru.ru_maxrss); } printf("Press <enter> to exit.\n"); getchar(); return 0; }
the_stack_data/44681.c
/* -*- compile-command: "gcc -Wall -Werror -static show_stack.c -o show_stack" -*- */ #include <stdio.h> int main(int argc, char **argv) { int stack_value = 0; fprintf(stderr, "post-execve, stack is ~%p\n", &stack_value); return 0; }
the_stack_data/82709.c
#include <stdio.h> int a, b, c, d, e, f, g, h; int main() { a = 1; b = 65; c = b; b *= 100; // Since a == 1, this line and the following three lines b -= -100000; // can be executed unconditionally. The lines 7-8 and c = b; // label L1 from the previous iteration has been removed. c -= -17000; while (1) { // Replaces L2 f = 1; d = 2; do { // Replaces L5 e = 2; do { // Replaces L4 g = d; g *= e; g -= b; if (!g) f = 0; // Replaces lines 19-20, removes L3 e -= -1; g = e; g -= b; } while (g); // Replaces line 24 d -= -1; g = d; g -= b; } while (g); // Replaces line 28 if (!f) h -= -1; // Replaces lines 29-30, removes L6 g = b; g -= c; if (!g) goto END; // Replaces lines 33-34, removes L7 b -= -17; } // Replaces line 36 END: printf("h: %d\n", h); }
the_stack_data/92326910.c
//===----------------------------------------------------------------------===// // // LLVM Fault Injection Tool // // Runtime Library Core // //===----------------------------------------------------------------------===// // // Copyright (C) 2019. rollrat. All Rights Reserved. // //===----------------------------------------------------------------------===// #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define MAX_INDEX 65535 #define PRINT_MESSAGE 1 #define SETTING_FILE_NAME "setting" #define RESULT_FILE_NAME "result" typedef uint32_t major_type; // profile option // 0: profile, 1: fault-inject static int run_fault_injection = 0; // fault option static int injection_type = 0; static int count_of_determine = 0; // print option static int trace_function = -1; static int trace_index = -1; static int trace_dependency = -1; static int trace_register = -2; // profile static int determine_count = 0; static FILE *log_file; void fault_inject_init() { // Open write file. log_file = fopen(RESULT_FILE_NAME, "w"); #if PRINT_MESSAGE fprintf(log_file, "[Fault Injector] RTL-Core Init!\n"); #endif srand(time(NULL)); // Read setting file. { FILE *fp; char op_name[255]; int op_option = 0; if ((fp = fopen(SETTING_FILE_NAME, "r")) == NULL) { fprintf(log_file, "[Fault Injector] Setting file not found.\n"); exit(1); } while (fscanf(fp, "%s %d", op_name, &op_option) != EOF) { #define DECALE_OPTION(name) if (!strcmp(op_name, #name)) {name = op_option; continue;} DECALE_OPTION(run_fault_injection) DECALE_OPTION(injection_type) DECALE_OPTION(count_of_determine) DECALE_OPTION(trace_function) DECALE_OPTION(trace_index) DECALE_OPTION(trace_dependency) DECALE_OPTION(trace_register) } fclose(fp); } // // TODO: Initialize vars. // if (run_fault_injection == 0) return; } static void print_log(uint32_t f_index, uint32_t index, uint32_t reg_num, uint32_t dependency, uint32_t size, char *value, char *opcode, int simple, const char *str) { fprintf(log_file, "[Fault Injector] %s: f_index=%02d, index=%02d, reg_num=%02d, dependency=%d", str, f_index, index, reg_num, dependency); if (simple == 0) { fprintf(log_file, ", opcode=%7s, size=%02d, value=", opcode, size); if (size == 1) { fprintf(log_file, "%d", *value); } else { int sz = size / 8; for (int i = 0; i < sz; i++) fprintf(log_file, "%02X", value[sz - i - 1] & 0xFF); } } fprintf(log_file, "\n"); } void fault_inject_trace(uint32_t f_index, uint32_t index, uint32_t reg_num, uint32_t dependency, uint32_t size, char *value, char *opcode) { if (trace_function >= 0 && f_index != trace_function) return; if (trace_index >= 0 && index != trace_index) return; if (trace_dependency >= 0 && dependency != trace_dependency) return; if (trace_register >= -1 && reg_num != trace_register) return; print_log(f_index, index, reg_num, dependency, size, value, opcode, 0, "trace"); } #pragma region Inject Determine static int determine(double rate) { return (double)rand() / RAND_MAX < rate; } major_type fault_inject_determine(major_type f_index, major_type index, major_type reg_num, major_type dependency) { determine_count += 1; if (run_fault_injection == 0) return 0; return determine((double)1 / count_of_determine); } #pragma endregion #pragma region Fault Inject static int get_fault_inject_pos(int sz) { return rand() % sz; } static int get_fault_inject_bit() { return rand() % (sizeof(char) * 8); } void fault_inject_flipbit(char *value) { *value ^= (1 << get_fault_inject_bit()); } void fault_inject_set0(char *value) { *value &= ~(1 << get_fault_inject_bit()); } void fault_inject_set1(char *value) { *value |= (1 << get_fault_inject_bit()); } void fault_inject(uint32_t f_index, uint32_t index, uint32_t reg_num, uint32_t dependency, uint32_t size, char *value, char *opcode) { print_log(f_index, index, reg_num, dependency, size, value, opcode, 0, "inject_before"); if (size == 1) *value ^= 1; else { int pos = get_fault_inject_pos(size / 8); switch (injection_type) { case 0: fault_inject_flipbit(&value[pos]); break; case 1: fault_inject_set0(&value[pos]); break; case 2: fault_inject_set1(&value[pos]); break; } } print_log(f_index, index, reg_num, dependency, size, value, opcode, 0, " inject_after"); } #pragma endregion void fault_inject_finish() { #if PRINT_MESSAGE fprintf(log_file, "[Fault Injector] RTL-Core Finish!\n"); #endif fprintf(log_file, "[Fault Injector] determine=%d\n", determine_count); // Save result file. fclose(log_file); }
the_stack_data/154832113.c
/* * unwfw2 - Extract firmware images of Hue bridges. * * Copyright 2019 Andreas Oberritter * * 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. * * Example of usage: * make * ./unfw2 firmware.fw2 */ #define _GNU_SOURCE #include <assert.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <openssl/evp.h> #include <openssl/pem.h> struct fw2_part { unsigned int size_be; unsigned short type_be; unsigned int zero; char version[16]; } __attribute__((packed)); struct fw2_header { char product_id[7]; unsigned char nb_parts; unsigned int size_be; char description[22]; } __attribute__((packed)); static bool load_pkey(EVP_PKEY **pkey) { EVP_PKEY *ret; BIO *bp; bp = BIO_new_file("certs/RSA_rel_01_pub.pem", "r"); if (bp == NULL) return false; ret = PEM_read_bio_PUBKEY(bp, pkey, NULL, NULL); BIO_free(bp); return ret != NULL; } static bool load_aes_key(unsigned char buf[32]) { const char keyfile[] = "certs/enc.k"; struct stat st; ssize_t ret; int fd; if (stat(keyfile, &st) != 0 || (st.st_mode & S_IFMT) != S_IFREG || st.st_size != 32) return false; fd = open(keyfile, O_RDONLY); if (fd < 0) { perror(keyfile); return false; } ret = TEMP_FAILURE_RETRY(read(fd, buf, 32)); if (ret < 0) perror("read"); close(fd); return ret == 32; } static void save_buf(const char *path, const unsigned char *buf, size_t size, mode_t mode) { FILE *f; f = fopen(path, "w"); assert(f != NULL); fwrite(buf, size, 1, f); fclose(f); chmod(path, mode); } static void process_mem(const void *mem, size_t size) { const struct fw2_header *fw = mem; const char *version = "Invalid"; char filename[FILENAME_MAX]; unsigned int signed_size; unsigned char key[32]; size_t count = 0; assert(size >= sizeof(struct fw2_header)); assert(fw->product_id[sizeof(fw->product_id) - 1] == '\0'); assert(fw->description[sizeof(fw->description) - 1] == '\0'); signed_size = be32toh(fw->size_be); printf("Product ID: %s\n", fw->product_id); printf("Description: %s\n", fw->description); printf("Size: %d\n", signed_size); assert(size >= signed_size); mem += sizeof(struct fw2_header); size -= sizeof(struct fw2_header); while (count < fw->nb_parts && size > 0) { const struct fw2_part *pt = mem; unsigned int pt_size = be32toh(pt->size_be); unsigned int pt_type = be16toh(pt->type_be); size_t offset = mem - (const void *)fw; const char *ext = ".bin"; assert(pt->version[sizeof(pt->version) - 1] == '\0'); assert(pt->zero == 0); version = pt->version; printf("--- 8< ---\n"); printf("Offset: %#lx\n", offset); printf("Version: %s\n", version); printf("Size: %d\n", pt_size); if (pt_type == 0xfe) ext = "pem"; else if (pt_type == 0x103) ext = "tgz.aes"; mem += sizeof(struct fw2_part); size -= sizeof(struct fw2_part); assert(size >= pt_size); if (pt_type == 0x103 && (pt_size & 0xf) == 0 && load_aes_key(key)) { EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); int block_size, decrypt_size, tmp_size; void *dest; int ret; ret = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, mem); assert(ret == 1); block_size = EVP_CIPHER_CTX_block_size(ctx); decrypt_size = pt_size - block_size; dest = malloc(decrypt_size); assert(dest != NULL); ret = EVP_DecryptUpdate(ctx, dest, &decrypt_size, mem + block_size, decrypt_size); assert(ret == 1); ret = EVP_DecryptFinal_ex(ctx, dest + decrypt_size, &tmp_size); assert(ret == 1); decrypt_size += tmp_size; EVP_CIPHER_CTX_free(ctx); ext = "tgz"; sprintf(filename, "%s-%s-0x%06zx.%s", fw->product_id, version, offset, ext); save_buf(filename, dest, decrypt_size, 0644); free(dest); } else { sprintf(filename, "%s-%s-0x%06zx.%s", fw->product_id, version, offset, ext); save_buf(filename, mem, pt_size, 0644); } mem += pt_size; size -= pt_size; count++; } if (size > 0) { sprintf(filename, "%s-%s.sig", fw->product_id, version); save_buf(filename, mem, size, 0644); EVP_PKEY *pkey = NULL; if (load_pkey(&pkey)) { EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); int ret = 1; assert(size == (size_t)EVP_PKEY_size(pkey)); ret &= EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey); ret &= EVP_DigestVerifyUpdate(mdctx, fw, signed_size); ret &= EVP_DigestVerifyFinal(mdctx, mem, EVP_PKEY_size(pkey)); EVP_MD_CTX_free(mdctx); EVP_PKEY_free(pkey); printf("--- 8< ---\n"); printf("Signature: %s\n", (ret == 1) ? "OK" : "Invalid"); } } } static bool process_file(int fd) { struct stat st; void *mem; if (fstat(fd, &st) < 0) { perror("fstat"); return false; } mem = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0); if (mem == MAP_FAILED) { perror("mmap"); return false; } process_mem(mem, st.st_size); munmap(mem, st.st_size); return true; } int main(int argc, char *argv[]) { bool ok; int i; for (i = 1; i < argc; i++) { int fd = open(argv[i], O_RDONLY); if (fd < 0) { perror(argv[i]); return 1; } ok = process_file(fd); close(fd); if (!ok) return 1; } return 0; }
the_stack_data/124972.c
#include <stddef.h> void *memset(void *ptr, int value, size_t size) { unsigned char *buf = (unsigned char *) ptr; for(size_t i = 0; i < size; ++i) buf[i] = (unsigned char) value; return ptr; }
the_stack_data/107953770.c
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #if defined(ALCS_ENABLED) || defined(COAP_COMM_ENABLED) || defined(DEV_BIND_ENABLED) #include <string.h> #include "iot_import.h" #include "mbedtls/aes.h" #define AES_BLOCK_SIZE 16 typedef struct { mbedtls_aes_context ctx; uint8_t iv[16]; } platform_aes_t; p_HAL_Aes128_t HAL_Aes128_Init( _IN_ const uint8_t *key, _IN_ const uint8_t *iv, _IN_ AES_DIR_t dir) { int ret = 0; platform_aes_t *p_aes128 = NULL; if(!key || !iv) return p_aes128; p_aes128 = (platform_aes_t *)calloc(1, sizeof(platform_aes_t)); if(!p_aes128) return p_aes128; mbedtls_aes_init(&p_aes128->ctx); if (dir == HAL_AES_ENCRYPTION) { ret = mbedtls_aes_setkey_enc(&p_aes128->ctx, key, 128); } else { ret = mbedtls_aes_setkey_dec(&p_aes128->ctx, key, 128); } if (ret == 0) { memcpy(p_aes128->iv, iv, 16); }else { free(p_aes128); p_aes128 = NULL; } return (p_HAL_Aes128_t *)p_aes128; } int HAL_Aes128_Destroy(_IN_ p_HAL_Aes128_t aes) { if(!aes) return -1; mbedtls_aes_free(&((platform_aes_t *)aes)->ctx); free(aes); return 0; } int HAL_Aes128_Cbc_Encrypt( _IN_ p_HAL_Aes128_t aes, _IN_ const void *src, _IN_ size_t blockNum, _OU_ void *dst) { int i = 0; int ret = ret; platform_aes_t *p_aes128 = (platform_aes_t *)aes; if(!aes || !src || !dst) return -1; for (i = 0; i < blockNum; ++i) { ret = mbedtls_aes_crypt_cbc(&p_aes128->ctx, MBEDTLS_AES_ENCRYPT, AES_BLOCK_SIZE, p_aes128->iv, src, dst); src += 16; dst += 16; } return ret; } int HAL_Aes128_Cbc_Decrypt( _IN_ p_HAL_Aes128_t aes, _IN_ const void *src, _IN_ size_t blockNum, _OU_ void *dst) { int i = 0; int ret = -1; platform_aes_t *p_aes128 = (platform_aes_t *)aes; if(!aes || !src || !dst) return ret; for (i = 0; i < blockNum; ++i) { ret = mbedtls_aes_crypt_cbc(&p_aes128->ctx, MBEDTLS_AES_DECRYPT, AES_BLOCK_SIZE, p_aes128->iv, src, dst); src += 16; dst += 16; } return ret; } #if defined(MBEDTLS_CIPHER_MODE_CFB) int HAL_Aes128_Cfb_Encrypt( _IN_ p_HAL_Aes128_t aes, _IN_ const void *src, _IN_ size_t length, _OU_ void *dst) { size_t offset = 0; int ret = -1; platform_aes_t *p_aes128 = (platform_aes_t *)aes; if(!aes || !src || !dst) return ret; ret = mbedtls_aes_crypt_cfb128(&p_aes128->ctx, MBEDTLS_AES_ENCRYPT, length, &offset, p_aes128->iv, src, dst); return ret; } #endif #if defined(MBEDTLS_CIPHER_MODE_CFB) int HAL_Aes128_Cfb_Decrypt( _IN_ p_HAL_Aes128_t aes, _IN_ const void *src, _IN_ size_t length, _OU_ void *dst) { size_t offset = 0; int ret = -1; platform_aes_t *p_aes128 = (platform_aes_t *)aes; if(!aes || !src || !dst) return ret; ret = mbedtls_aes_crypt_cfb128(&p_aes128->ctx, MBEDTLS_AES_DECRYPT, length, &offset, p_aes128->iv, src, dst); return ret; } #endif #endif
the_stack_data/162642972.c
#if 0 todo código a ser "desligado" aqui #endif //https://pt.stackoverflow.com/q/179837/101
the_stack_data/83481.c
#include <stdio.h> #include <stdlib.h> int const SIZE = 9; int helper(const void* a, const void* b) { return *(int*)a - *(int*)b; //comparison } int main() { int i = 0, answer = 0, array[SIZE]; for (i = 0; i < SIZE; ++i) { scanf("array[%d]=", &array[i]); } qsort(array, SIZE, sizeof(int), helper); for (i = SIZE - 1; i > 0; --i) { if (array[i] == array[i - 1]) { answer = array[i]; break; } } printf("The largest number occurring more than 2 times: %d", answer); return 0; }
the_stack_data/73575852.c
#include<stdio.h> int main(){ printf("hello world"); }
the_stack_data/104827188.c
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifdef SUPPORT_TLS #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_ENTROPY_C) #if defined(MBEDTLS_TEST_NULL_ENTROPY) #warning "**** WARNING! MBEDTLS_TEST_NULL_ENTROPY defined! " #warning "**** THIS BUILD HAS NO DEFINED ENTROPY SOURCES " #warning "**** THIS BUILD IS *NOT* SUITABLE FOR PRODUCTION USE " #endif #include "mbedtls/entropy.h" #include "mbedtls/entropy_poll.h" #include <string.h> #if defined(MBEDTLS_FS_IO) #include <stdio.h> #endif #if defined(MBEDTLS_ENTROPY_NV_SEED) #include "mbedtls/platform.h" #endif #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #include "mbedtls/debug.h" #define mbedtls_printf tls_info #endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_SELF_TEST */ #if defined(MBEDTLS_HAVEGE_C) #include "mbedtls/havege.h" #endif /* Implementation that should never be optimized out by the compiler */ static void mbedtls_zeroize( void *v, size_t n ) { volatile unsigned char *p = v; while( n-- ) *p++ = 0; } #define ENTROPY_MAX_LOOP 256 /**< Maximum amount to loop before error */ void mbedtls_entropy_init( mbedtls_entropy_context *ctx ) { memset( ctx, 0, sizeof(mbedtls_entropy_context) ); #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_init( &ctx->mutex ); #endif #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) mbedtls_sha512_starts( &ctx->accumulator, 0 ); #else mbedtls_sha256_starts( &ctx->accumulator, 0 ); #endif #if defined(MBEDTLS_HAVEGE_C) mbedtls_havege_init( &ctx->havege_data ); #endif #if defined(MBEDTLS_TEST_NULL_ENTROPY) mbedtls_entropy_add_source( ctx, mbedtls_null_entropy_poll, NULL, 1, MBEDTLS_ENTROPY_SOURCE_STRONG ); #endif #if !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) #if !defined(MBEDTLS_NO_PLATFORM_ENTROPY) mbedtls_entropy_add_source( ctx, mbedtls_platform_entropy_poll, NULL, MBEDTLS_ENTROPY_MIN_PLATFORM, MBEDTLS_ENTROPY_SOURCE_STRONG ); #endif #if defined(MBEDTLS_TIMING_C) mbedtls_entropy_add_source( ctx, mbedtls_hardclock_poll, NULL, MBEDTLS_ENTROPY_MIN_HARDCLOCK, MBEDTLS_ENTROPY_SOURCE_WEAK ); #endif #if defined(MBEDTLS_HAVEGE_C) mbedtls_entropy_add_source( ctx, mbedtls_havege_poll, &ctx->havege_data, MBEDTLS_ENTROPY_MIN_HAVEGE, MBEDTLS_ENTROPY_SOURCE_STRONG ); #endif #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) mbedtls_entropy_add_source( ctx, mbedtls_hardware_poll, NULL, MBEDTLS_ENTROPY_MIN_HARDWARE, MBEDTLS_ENTROPY_SOURCE_STRONG ); #endif #if defined(MBEDTLS_ENTROPY_NV_SEED) mbedtls_entropy_add_source( ctx, mbedtls_nv_seed_poll, NULL, MBEDTLS_ENTROPY_BLOCK_SIZE, MBEDTLS_ENTROPY_SOURCE_STRONG ); #endif #endif /* MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES */ } void mbedtls_entropy_free( mbedtls_entropy_context *ctx ) { #if defined(MBEDTLS_HAVEGE_C) mbedtls_havege_free( &ctx->havege_data ); #endif #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_free( &ctx->mutex ); #endif mbedtls_zeroize( ctx, sizeof( mbedtls_entropy_context ) ); } int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx, mbedtls_entropy_f_source_ptr f_source, void *p_source, size_t threshold, int strong ) { int index, ret = 0; #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif index = ctx->source_count; if( index >= MBEDTLS_ENTROPY_MAX_SOURCES ) { ret = MBEDTLS_ERR_ENTROPY_MAX_SOURCES; goto exit; } ctx->source[index].f_source = f_source; ctx->source[index].p_source = p_source; ctx->source[index].threshold = threshold; ctx->source[index].strong = strong; ctx->source_count++; exit: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif return( ret ); } /* * Entropy accumulator update */ static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id, const unsigned char *data, size_t len ) { unsigned char header[2]; unsigned char tmp[MBEDTLS_ENTROPY_BLOCK_SIZE]; size_t use_len = len; const unsigned char *p = data; if( use_len > MBEDTLS_ENTROPY_BLOCK_SIZE ) { #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) mbedtls_sha512( data, len, tmp, 0 ); #else mbedtls_sha256( data, len, tmp, 0 ); #endif p = tmp; use_len = MBEDTLS_ENTROPY_BLOCK_SIZE; } header[0] = source_id; header[1] = use_len & 0xFF; #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) mbedtls_sha512_update( &ctx->accumulator, header, 2 ); mbedtls_sha512_update( &ctx->accumulator, p, use_len ); #else mbedtls_sha256_update( &ctx->accumulator, header, 2 ); mbedtls_sha256_update( &ctx->accumulator, p, use_len ); #endif return( 0 ); } int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx, const unsigned char *data, size_t len ) { int ret; #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif ret = entropy_update( ctx, MBEDTLS_ENTROPY_SOURCE_MANUAL, data, len ); #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif return( ret ); } /* * Run through the different sources to add entropy to our accumulator */ static int entropy_gather_internal( mbedtls_entropy_context *ctx ) { int ret, i, have_one_strong = 0; unsigned char buf[MBEDTLS_ENTROPY_MAX_GATHER]; size_t olen; if( ctx->source_count == 0 ) return( MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED ); /* * Run through our entropy sources */ for( i = 0; i < ctx->source_count; i++ ) { if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG ) have_one_strong = 1; olen = 0; if( ( ret = ctx->source[i].f_source( ctx->source[i].p_source, buf, MBEDTLS_ENTROPY_MAX_GATHER, &olen ) ) != 0 ) { return( ret ); } /* * Add if we actually gathered something */ if( olen > 0 ) { entropy_update( ctx, (unsigned char) i, buf, olen ); ctx->source[i].size += olen; } } if( have_one_strong == 0 ) return( MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE ); return( 0 ); } /* * Thread-safe wrapper for entropy_gather_internal() */ int mbedtls_entropy_gather( mbedtls_entropy_context *ctx ) { int ret; #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif ret = entropy_gather_internal( ctx ); #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif return( ret ); } int mbedtls_entropy_func( void *data, unsigned char *output, size_t len ) { int ret, count = 0, i, done; mbedtls_entropy_context *ctx = (mbedtls_entropy_context *) data; unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE]; if( len > MBEDTLS_ENTROPY_BLOCK_SIZE ) return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED ); #if defined(MBEDTLS_ENTROPY_NV_SEED) /* Update the NV entropy seed before generating any entropy for outside * use. */ if( ctx->initial_entropy_run == 0 ) { ctx->initial_entropy_run = 1; if( ( ret = mbedtls_entropy_update_nv_seed( ctx ) ) != 0 ) return( ret ); } #endif #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif /* * Always gather extra entropy before a call */ do { if( count++ > ENTROPY_MAX_LOOP ) { ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED; goto exit; } if( ( ret = entropy_gather_internal( ctx ) ) != 0 ) goto exit; done = 1; for( i = 0; i < ctx->source_count; i++ ) if( ctx->source[i].size < ctx->source[i].threshold ) done = 0; } while( ! done ); memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE ); #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) mbedtls_sha512_finish( &ctx->accumulator, buf ); /* * Reset accumulator and counters and recycle existing entropy */ memset( &ctx->accumulator, 0, sizeof( mbedtls_sha512_context ) ); mbedtls_sha512_starts( &ctx->accumulator, 0 ); mbedtls_sha512_update( &ctx->accumulator, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ); /* * Perform second SHA-512 on entropy */ mbedtls_sha512( buf, MBEDTLS_ENTROPY_BLOCK_SIZE, buf, 0 ); #else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */ mbedtls_sha256_finish( &ctx->accumulator, buf ); /* * Reset accumulator and counters and recycle existing entropy */ memset( &ctx->accumulator, 0, sizeof( mbedtls_sha256_context ) ); mbedtls_sha256_starts( &ctx->accumulator, 0 ); mbedtls_sha256_update( &ctx->accumulator, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ); /* * Perform second SHA-256 on entropy */ mbedtls_sha256( buf, MBEDTLS_ENTROPY_BLOCK_SIZE, buf, 0 ); #endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */ for( i = 0; i < ctx->source_count; i++ ) ctx->source[i].size = 0; memcpy( output, buf, len ); ret = 0; exit: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif return( ret ); } #if defined(MBEDTLS_ENTROPY_NV_SEED) int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx ) { int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ]; /* Read new seed and write it to NV */ if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 ) return( ret ); if( mbedtls_nv_seed_write( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 ) return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR ); /* Manually update the remaining stream with a separator value to diverge */ memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE ); mbedtls_entropy_update_manual( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ); return( 0 ); } #endif /* MBEDTLS_ENTROPY_NV_SEED */ #if defined(MBEDTLS_FS_IO) int mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *path ) { int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; FILE *f; unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE]; if( ( f = fopen( path, "wb" ) ) == NULL ) return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR ); if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 ) goto exit; if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) != MBEDTLS_ENTROPY_BLOCK_SIZE ) { ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; goto exit; } ret = 0; exit: fclose( f ); return( ret ); } int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path ) { FILE *f; size_t n; unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ]; if( ( f = fopen( path, "rb" ) ) == NULL ) return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR ); fseek( f, 0, SEEK_END ); n = (size_t) ftell( f ); fseek( f, 0, SEEK_SET ); if( n > MBEDTLS_ENTROPY_MAX_SEED_SIZE ) n = MBEDTLS_ENTROPY_MAX_SEED_SIZE; if( fread( buf, 1, n, f ) != n ) { fclose( f ); return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR ); } fclose( f ); mbedtls_entropy_update_manual( ctx, buf, n ); return( mbedtls_entropy_write_seed_file( ctx, path ) ); } #endif /* MBEDTLS_FS_IO */ #if defined(MBEDTLS_SELF_TEST) #if !defined(MBEDTLS_TEST_NULL_ENTROPY) /* * Dummy source function */ static int entropy_dummy_source( void *data, unsigned char *output, size_t len, size_t *olen ) { ((void) data); memset( output, 0x2a, len ); *olen = len; return( 0 ); } #endif /* !MBEDTLS_TEST_NULL_ENTROPY */ #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) static int mbedtls_entropy_source_self_test_gather( unsigned char *buf, size_t buf_len ) { int ret = 0; size_t entropy_len = 0; size_t olen = 0; size_t attempts = buf_len; while( attempts > 0 && entropy_len < buf_len ) { if( ( ret = mbedtls_hardware_poll( NULL, buf + entropy_len, buf_len - entropy_len, &olen ) ) != 0 ) return( ret ); entropy_len += olen; attempts--; } if( entropy_len < buf_len ) { ret = 1; } return( ret ); } static int mbedtls_entropy_source_self_test_check_bits( const unsigned char *buf, size_t buf_len ) { unsigned char set= 0xFF; unsigned char unset = 0x00; size_t i; for( i = 0; i < buf_len; i++ ) { set &= buf[i]; unset |= buf[i]; } return( set == 0xFF || unset == 0x00 ); } /* * A test to ensure hat the entropy sources are functioning correctly * and there is no obvious failure. The test performs the following checks: * - The entropy source is not providing only 0s (all bits unset) or 1s (all * bits set). * - The entropy source is not providing values in a pattern. Because the * hardware could be providing data in an arbitrary length, this check polls * the hardware entropy source twice and compares the result to ensure they * are not equal. * - The error code returned by the entropy source is not an error. */ int mbedtls_entropy_source_self_test( int verbose ) { int ret = 0; unsigned char buf0[2 * sizeof( unsigned long long int )]; unsigned char buf1[2 * sizeof( unsigned long long int )]; if( verbose != 0 ) mbedtls_printf( " ENTROPY_BIAS test: " ); memset( buf0, 0x00, sizeof( buf0 ) ); memset( buf1, 0x00, sizeof( buf1 ) ); if( ( ret = mbedtls_entropy_source_self_test_gather( buf0, sizeof( buf0 ) ) ) != 0 ) goto cleanup; if( ( ret = mbedtls_entropy_source_self_test_gather( buf1, sizeof( buf1 ) ) ) != 0 ) goto cleanup; /* Make sure that the returned values are not all 0 or 1 */ if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf0, sizeof( buf0 ) ) ) != 0 ) goto cleanup; if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf1, sizeof( buf1 ) ) ) != 0 ) goto cleanup; /* Make sure that the entropy source is not returning values in a * pattern */ ret = memcmp( buf0, buf1, sizeof( buf0 ) ) == 0; cleanup: if( verbose != 0 ) { if( ret != 0 ) mbedtls_printf( "failed\n" ); else mbedtls_printf( "passed\n" ); mbedtls_printf( "\n" ); } return( ret != 0 ); } #endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */ /* * The actual entropy quality is hard to test, but we can at least * test that the functions don't cause errors and write the correct * amount of data to buffers. */ int mbedtls_entropy_self_test( int verbose ) { int ret = 1; #if !defined(MBEDTLS_TEST_NULL_ENTROPY) mbedtls_entropy_context ctx; unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 }; unsigned char acc[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 }; size_t i, j; #endif /* !MBEDTLS_TEST_NULL_ENTROPY */ if( verbose != 0 ) mbedtls_printf( " ENTROPY test: " ); #if !defined(MBEDTLS_TEST_NULL_ENTROPY) mbedtls_entropy_init( &ctx ); /* First do a gather to make sure we have default sources */ if( ( ret = mbedtls_entropy_gather( &ctx ) ) != 0 ) goto cleanup; ret = mbedtls_entropy_add_source( &ctx, entropy_dummy_source, NULL, 16, MBEDTLS_ENTROPY_SOURCE_WEAK ); if( ret != 0 ) goto cleanup; if( ( ret = mbedtls_entropy_update_manual( &ctx, buf, sizeof buf ) ) != 0 ) goto cleanup; /* * To test that mbedtls_entropy_func writes correct number of bytes: * - use the whole buffer and rely on ASan to detect overruns * - collect entropy 8 times and OR the result in an accumulator: * any byte should then be 0 with probably 2^(-64), so requiring * each of the 32 or 64 bytes to be non-zero has a false failure rate * of at most 2^(-58) which is acceptable. */ for( i = 0; i < 8; i++ ) { if( ( ret = mbedtls_entropy_func( &ctx, buf, sizeof( buf ) ) ) != 0 ) goto cleanup; for( j = 0; j < sizeof( buf ); j++ ) acc[j] |= buf[j]; } for( j = 0; j < sizeof( buf ); j++ ) { if( acc[j] == 0 ) { ret = 1; goto cleanup; } } #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) if( ( ret = mbedtls_entropy_source_self_test( 0 ) ) != 0 ) goto cleanup; #endif cleanup: mbedtls_entropy_free( &ctx ); #endif /* !MBEDTLS_TEST_NULL_ENTROPY */ if( verbose != 0 ) { if( ret != 0 ) mbedtls_printf( "failed\n" ); else mbedtls_printf( "passed\n" ); mbedtls_printf( "\n" ); } return( ret != 0 ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_ENTROPY_C */ #endif
the_stack_data/45509.c
// This file is part of CPAchecker, // a tool for configurable software verification: // https://cpachecker.sosy-lab.org // // SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 extern int __VERIFIER_nondet_int(); void bubblesort(int array[], int length) { int tmp = 0; for (int i = 0; i < length ; i++) { for (int j = 1; j < length - i ; j++) { if (array[j] > array[j+1]) { tmp = array[j]; array[j] = array[j+1]; array[j+1] = tmp; } } } } int main(){ int first = __VERIFIER_nondet_int(); int second = __VERIFIER_nondet_int(); int third = __VERIFIER_nondet_int(); int a[] = {first,second,third}; bubblesort(a, 3); //POST-CONDITION check if array a is sorted if(a[0] <= a[1] && a[1] <= a[2]) { goto EXIT; } else { goto ERROR; } EXIT: return 0; ERROR: return 1; }
the_stack_data/193892249.c
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> int vfprintf(FILE *stream, const char *format, va_list arg) { int i; char *s = malloc(4096); i = vsprintf(s, format, arg); i = fwrite(s, 1, i, stream); free(s); return i; }
the_stack_data/12638375.c
// ---------------------------------------- // PROJECT EULER PROBLEM # // https://projecteuler.net/problem=# // ---------------------------------------- #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <inttypes.h> #include <math.h> #include <time.h> #include <string.h> int main(int argc, char *argv[]) { }
the_stack_data/968593.c
void foo(void); void foo(void) { float f = 0.0 + 9.87; }
the_stack_data/15941.c
#include <stdio.h> #include <stdlib.h> #include <string.h> char* getenv(const char* name); int main(int args, char* argv[]){ printf("Content-Type: text/html\r\n\r\n"); printf("<h2>Hello from C CGI</h2>"); return 0; }
the_stack_data/29825017.c
// // AOJ0051.c // // // Created by n_knuu on 2014/03/19. // // #include <stdio.h> #include <stdlib.h> int main(void) { char array[8]; int num,i,j,k; char reverse[8],temp; scanf("%d\n",&num); for (i=0; i<num; i++) { scanf("%s\n",array); for (j=0; j<8; j++) { for (k=0; k<7-j; k++) { if (array[k]>array[k+1]) { temp=array[k]; array[k]=array[k+1]; array[k+1]=temp; } } } for (j=0; j<8; j++) reverse[j]=array[7-j]; printf("%d\n",atoi(reverse)-atoi(array)); } return 0; }
the_stack_data/54824295.c
/* * Authored by Alex Hultman, 2018-2019. * Intellectual property of third-party. * 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. */ #ifdef LIBUS_USE_OPENSSL #include "libusockets.h" #include "internal/internal.h" /* This module contains the entire OpenSSL implementation * of the SSL socket and socket context interfaces. */ #include <openssl/ssl.h> #include <openssl/bio.h> #include <openssl/err.h> /* We do not want to block the loop with tons and tons of CPU-intensive work. * Spread it out during many loop iterations, prioritizing already open connections, * they are far easier on CPU */ static const int MAX_HANDSHAKES_PER_LOOP_ITERATION = 5; struct loop_ssl_data { char *ssl_read_input, *ssl_read_output; unsigned int ssl_read_input_length; unsigned int ssl_read_input_offset; struct us_socket_t *ssl_socket; int last_write_was_msg_more; int msg_more; // these are used to throttle SSL handshakes per loop iteration long long last_iteration_nr; int handshake_budget; BIO *shared_rbio; BIO *shared_wbio; BIO_METHOD *shared_biom; }; struct us_internal_ssl_socket_context_t { struct us_socket_context_t sc; // this thing can be shared with other socket contexts via socket transfer! // maybe instead of holding once you hold many, a vector or set // when a socket that belongs to another socket context transfers to a new socket context SSL_CTX *ssl_context; int is_parent; // här måste det vara! struct us_internal_ssl_socket_t *(*on_open)(struct us_internal_ssl_socket_t *, int is_client, char *ip, int ip_length); struct us_internal_ssl_socket_t *(*on_data)(struct us_internal_ssl_socket_t *, char *data, int length); struct us_internal_ssl_socket_t *(*on_close)(struct us_internal_ssl_socket_t *); }; // same here, should or shouldn't it contain s? struct us_internal_ssl_socket_t { struct us_socket_t s; SSL *ssl; int ssl_write_wants_read; // we use this for now }; int passphrase_cb(char *buf, int size, int rwflag, void *u) { const char *passphrase = (const char *) u; int passphrase_length = strlen(passphrase); memcpy(buf, passphrase, passphrase_length); // put null at end? no? return passphrase_length; } int BIO_s_custom_create(BIO *bio) { BIO_set_init(bio, 1); return 1; } long BIO_s_custom_ctrl(BIO *bio, int cmd, long num, void *user) { switch(cmd) { case BIO_CTRL_FLUSH: return 1; default: return 0; } } int BIO_s_custom_write(BIO *bio, const char *data, int length) { struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) BIO_get_data(bio); //printf("BIO_s_custom_write\n"); loop_ssl_data->last_write_was_msg_more = loop_ssl_data->msg_more || length == 16413; int written = us_socket_write(0, loop_ssl_data->ssl_socket, data, length, loop_ssl_data->last_write_was_msg_more); if (!written) { BIO_set_flags(bio, BIO_get_flags(bio) | BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_WRITE); return -1; } //printf("BIO_s_custom_write returns: %d\n", ret); return written; } int BIO_s_custom_read(BIO *bio, char *dst, int length) { struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) BIO_get_data(bio); //printf("BIO_s_custom_read\n"); if (!loop_ssl_data->ssl_read_input_length) { BIO_set_flags(bio, BIO_get_flags(bio) | BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_READ); return -1; } if ((unsigned int) length > loop_ssl_data->ssl_read_input_length) { length = loop_ssl_data->ssl_read_input_length; } memcpy(dst, loop_ssl_data->ssl_read_input + loop_ssl_data->ssl_read_input_offset, length); loop_ssl_data->ssl_read_input_offset += length; loop_ssl_data->ssl_read_input_length -= length; return length; } struct us_internal_ssl_socket_t *ssl_on_open(struct us_internal_ssl_socket_t *s, int is_client, char *ip, int ip_length) { struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); struct us_loop_t *loop = us_socket_context_loop(0, &context->sc); struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; s->ssl = SSL_new(context->ssl_context); s->ssl_write_wants_read = 0; SSL_set_bio(s->ssl, loop_ssl_data->shared_rbio, loop_ssl_data->shared_wbio); BIO_up_ref(loop_ssl_data->shared_rbio); BIO_up_ref(loop_ssl_data->shared_wbio); if (is_client) { SSL_set_connect_state(s->ssl); } else { SSL_set_accept_state(s->ssl); } return (struct us_internal_ssl_socket_t *) context->on_open(s, is_client, ip, ip_length); } struct us_internal_ssl_socket_t *ssl_on_close(struct us_internal_ssl_socket_t *s) { struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); SSL_free(s->ssl); return context->on_close(s); } struct us_internal_ssl_socket_t *ssl_on_end(struct us_internal_ssl_socket_t *s) { struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); // whatever state we are in, a TCP FIN is always an answered shutdown return us_internal_ssl_socket_close(s); } // this whole function needs a complete clean-up struct us_internal_ssl_socket_t *ssl_on_data(struct us_internal_ssl_socket_t *s, void *data, int length) { // note: this context can change when we adopt the socket! struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); struct us_loop_t *loop = us_socket_context_loop(0, &context->sc); struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; // note: if we put data here we should never really clear it (not in write either, it still should be available for SSL_write to read from!) loop_ssl_data->ssl_read_input = data; loop_ssl_data->ssl_read_input_length = length; loop_ssl_data->ssl_read_input_offset = 0; loop_ssl_data->ssl_socket = &s->s; loop_ssl_data->msg_more = 0; if (us_internal_ssl_socket_is_shut_down(s)) { int ret; if ((ret = SSL_shutdown(s->ssl)) == 1) { // two phase shutdown is complete here //printf("Two step SSL shutdown complete\n"); return us_internal_ssl_socket_close(s); } else if (ret < 0) { int err = SSL_get_error(s->ssl, ret); if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) { // we need to clear the error queue in case these added to the thread local queue ERR_clear_error(); } } // no further processing of data when in shutdown state return s; } // bug checking: this loop needs a lot of attention and clean-ups and check-ups int read = 0; restart: while (1) { int just_read = SSL_read(s->ssl, loop_ssl_data->ssl_read_output + LIBUS_RECV_BUFFER_PADDING + read, LIBUS_RECV_BUFFER_LENGTH - read); if (just_read <= 0) { int err = SSL_get_error(s->ssl, just_read); // as far as I know these are the only errors we want to handle if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) { // clear per thread error queue if it may contain something if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) { ERR_clear_error(); } // terminate connection here return us_internal_ssl_socket_close(s); } else { // emit the data we have and exit // assume we emptied the input buffer fully or error here as well! if (loop_ssl_data->ssl_read_input_length) { return us_internal_ssl_socket_close(s); } // cannot emit zero length to app if (!read) { break; } s = context->on_data(s, loop_ssl_data->ssl_read_output + LIBUS_RECV_BUFFER_PADDING, read); if (us_socket_is_closed(0, &s->s)) { return s; } break; } } read += just_read; // at this point we might be full and need to emit the data to application and start over if (read == LIBUS_RECV_BUFFER_LENGTH) { // emit data and restart s = context->on_data(s, loop_ssl_data->ssl_read_output + LIBUS_RECV_BUFFER_PADDING, read); if (us_socket_is_closed(0, &s->s)) { return s; } read = 0; goto restart; } } // trigger writable if we failed last write with want read if (s->ssl_write_wants_read) { s->ssl_write_wants_read = 0; // make sure to update context before we call (context can change if the user adopts the socket!) context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); s = (struct us_internal_ssl_socket_t *) context->sc.on_writable(&s->s); // cast here! // if we are closed here, then exit if (us_socket_is_closed(0, &s->s)) { return s; } } // check this then? if (SSL_get_shutdown(s->ssl) & SSL_RECEIVED_SHUTDOWN) { //printf("SSL_RECEIVED_SHUTDOWN\n"); //exit(-2); // not correct anyways! s = us_internal_ssl_socket_close(s); //us_ } return s; } /* Lazily inits loop ssl data first time */ void us_internal_init_loop_ssl_data(struct us_loop_t *loop) { if (!loop->data.ssl_data) { struct loop_ssl_data *loop_ssl_data = malloc(sizeof(struct loop_ssl_data)); loop_ssl_data->ssl_read_output = malloc(LIBUS_RECV_BUFFER_LENGTH + LIBUS_RECV_BUFFER_PADDING * 2); OPENSSL_init_ssl(0, NULL); loop_ssl_data->shared_biom = BIO_meth_new(BIO_TYPE_MEM, "µS BIO"); BIO_meth_set_create(loop_ssl_data->shared_biom, BIO_s_custom_create); BIO_meth_set_write(loop_ssl_data->shared_biom, BIO_s_custom_write); BIO_meth_set_read(loop_ssl_data->shared_biom, BIO_s_custom_read); BIO_meth_set_ctrl(loop_ssl_data->shared_biom, BIO_s_custom_ctrl); loop_ssl_data->shared_rbio = BIO_new(loop_ssl_data->shared_biom); loop_ssl_data->shared_wbio = BIO_new(loop_ssl_data->shared_biom); BIO_set_data(loop_ssl_data->shared_rbio, loop_ssl_data); BIO_set_data(loop_ssl_data->shared_wbio, loop_ssl_data); // reset handshake budget (doesn't matter what loop nr we start on) loop_ssl_data->last_iteration_nr = 0; loop_ssl_data->handshake_budget = MAX_HANDSHAKES_PER_LOOP_ITERATION; loop->data.ssl_data = loop_ssl_data; } } /* Called by loop free, clears any loop ssl data */ void us_internal_free_loop_ssl_data(struct us_loop_t *loop) { struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; if (loop_ssl_data) { free(loop_ssl_data->ssl_read_output); BIO_free(loop_ssl_data->shared_rbio); BIO_free(loop_ssl_data->shared_wbio); BIO_meth_free(loop_ssl_data->shared_biom); free(loop_ssl_data); } } // we ignore reading data for ssl sockets that are // in init state, if our so called budget for doing // so won't allow it. here we actually use // the kernel buffering to our advantage int ssl_ignore_data(struct us_internal_ssl_socket_t *s) { // fast path just checks for init if (!SSL_in_init(s->ssl)) { return 0; } // this path is run for all ssl sockets that are in init and just got data event from polling struct us_loop_t *loop = s->s.context->loop; struct loop_ssl_data *loop_ssl_data = loop->data.ssl_data; // reset handshake budget if new iteration if (loop_ssl_data->last_iteration_nr != us_loop_iteration_number(loop)) { loop_ssl_data->last_iteration_nr = us_loop_iteration_number(loop); loop_ssl_data->handshake_budget = MAX_HANDSHAKES_PER_LOOP_ITERATION; } if (loop_ssl_data->handshake_budget) { loop_ssl_data->handshake_budget--; return 0; } // ignore this data event return 1; } /* Per-context functions */ struct us_internal_ssl_socket_context_t *us_internal_create_child_ssl_socket_context(struct us_internal_ssl_socket_context_t *context, int context_ext_size) { struct us_socket_context_options_t options = {0}; struct us_internal_ssl_socket_context_t *child_context = (struct us_internal_ssl_socket_context_t *) us_create_socket_context(0, context->sc.loop, sizeof(struct us_internal_ssl_socket_context_t) + context_ext_size, options); // I think this is the only thing being shared child_context->ssl_context = context->ssl_context; child_context->is_parent = 0; return child_context; } struct us_internal_ssl_socket_context_t *us_internal_create_ssl_socket_context(struct us_loop_t *loop, int context_ext_size, struct us_socket_context_options_t options) { us_internal_init_loop_ssl_data(loop); struct us_socket_context_options_t no_options = {0}; struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_create_socket_context(0, loop, sizeof(struct us_internal_ssl_socket_context_t) + context_ext_size, no_options); context->ssl_context = SSL_CTX_new(TLS_method()); context->is_parent = 1; // only parent ssl contexts may need to ignore data context->sc.ignore_data = (int (*)(struct us_socket_t *)) ssl_ignore_data; // options SSL_CTX_set_read_ahead(context->ssl_context, 1); SSL_CTX_set_mode(context->ssl_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); //SSL_CTX_set_mode(context->ssl_context, SSL_MODE_ENABLE_PARTIAL_WRITE); // this lowers performance a bit in benchmarks if (options.ssl_prefer_low_memory_usage) { SSL_CTX_set_mode(context->ssl_context, SSL_MODE_RELEASE_BUFFERS); } //SSL_CTX_set_mode(context->ssl_context, SSL_MODE_RELEASE_BUFFERS); SSL_CTX_set_options(context->ssl_context, SSL_OP_NO_SSLv3); SSL_CTX_set_options(context->ssl_context, SSL_OP_NO_TLSv1); // these are going to be extended if (options.passphrase) { SSL_CTX_set_default_passwd_cb_userdata(context->ssl_context, (void *) options.passphrase); SSL_CTX_set_default_passwd_cb(context->ssl_context, passphrase_cb); } if (options.cert_file_name) { if (SSL_CTX_use_certificate_chain_file(context->ssl_context, options.cert_file_name) != 1) { return 0; } } if (options.key_file_name) { if (SSL_CTX_use_PrivateKey_file(context->ssl_context, options.key_file_name, SSL_FILETYPE_PEM) != 1) { return 0; } } if (options.ca_file_name) { STACK_OF(X509_NAME) *ca_list; ca_list = SSL_load_client_CA_file(options.ca_file_name); if(ca_list == NULL) { return 0; } SSL_CTX_set_client_CA_list(context->ssl_context, ca_list); if (SSL_CTX_load_verify_locations(context->ssl_context, options.ca_file_name, NULL) != 1) { return 0; } SSL_CTX_set_verify(context->ssl_context, SSL_VERIFY_PEER, NULL); } if (options.dh_params_file_name) { /* Set up ephemeral DH parameters. */ DH *dh_2048 = NULL; FILE *paramfile; paramfile = fopen(options.dh_params_file_name, "r"); if (paramfile) { dh_2048 = PEM_read_DHparams(paramfile, NULL, NULL, NULL); fclose(paramfile); } else { return 0; } if (dh_2048 == NULL) { return 0; } if (SSL_CTX_set_tmp_dh(context->ssl_context, dh_2048) != 1) { return 0; } /* OWASP Cipher String 'A+' (https://www.owasp.org/index.php/TLS_Cipher_String_Cheat_Sheet) */ if (SSL_CTX_set_cipher_list(context->ssl_context, "DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256") != 1) { return 0; } } return context; } void us_internal_ssl_socket_context_free(struct us_internal_ssl_socket_context_t *context) { if (context->is_parent) { SSL_CTX_free(context->ssl_context); } us_socket_context_free(0, &context->sc); } struct us_listen_socket_t *us_internal_ssl_socket_context_listen(struct us_internal_ssl_socket_context_t *context, const char *host, int port, int options, int socket_ext_size) { return us_socket_context_listen(0, &context->sc, host, port, options, sizeof(struct us_internal_ssl_socket_t) - sizeof(struct us_socket_t) + socket_ext_size); } struct us_internal_ssl_socket_t *us_internal_ssl_socket_context_connect(struct us_internal_ssl_socket_context_t *context, const char *host, int port, int options, int socket_ext_size) { return (struct us_internal_ssl_socket_t *) us_socket_context_connect(0, &context->sc, host, port, options, sizeof(struct us_internal_ssl_socket_t) - sizeof(struct us_socket_t) + socket_ext_size); } void us_internal_ssl_socket_context_on_open(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_open)(struct us_internal_ssl_socket_t *s, int is_client, char *ip, int ip_length)) { us_socket_context_on_open(0, &context->sc, (struct us_socket_t *(*)(struct us_socket_t *, int, char *, int)) ssl_on_open); context->on_open = on_open; } void us_internal_ssl_socket_context_on_close(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_close)(struct us_internal_ssl_socket_t *s)) { us_socket_context_on_close(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *)) ssl_on_close); context->on_close = on_close; } void us_internal_ssl_socket_context_on_data(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_data)(struct us_internal_ssl_socket_t *s, char *data, int length)) { us_socket_context_on_data(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *, char *, int)) ssl_on_data); context->on_data = on_data; } void us_internal_ssl_socket_context_on_writable(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_writable)(struct us_internal_ssl_socket_t *s)) { us_socket_context_on_writable(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *)) on_writable); } void us_internal_ssl_socket_context_on_timeout(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_timeout)(struct us_internal_ssl_socket_t *s)) { us_socket_context_on_timeout(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *)) on_timeout); } void us_internal_ssl_socket_context_on_end(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_end)(struct us_internal_ssl_socket_t *)) { us_socket_context_on_end(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *)) ssl_on_end); } void *us_internal_ssl_socket_context_ext(struct us_internal_ssl_socket_context_t *context) { return context + 1; } /* Per socket functions */ int us_internal_ssl_socket_write(struct us_internal_ssl_socket_t *s, const char *data, int length, int msg_more) { if (us_socket_is_closed(0, &s->s) || us_internal_ssl_socket_is_shut_down(s)) { return 0; } struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); struct us_loop_t *loop = us_socket_context_loop(0, &context->sc); struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; // it makes literally no sense to touch this here! it should start at 0 and ONLY be set and reset by the on_data function! // the way is is now, triggering a write from a read will essentially delete all input data! // what we need to do is to check if this ever is non-zero and print a warning loop_ssl_data->ssl_read_input_length = 0; loop_ssl_data->ssl_socket = &s->s; loop_ssl_data->msg_more = msg_more; loop_ssl_data->last_write_was_msg_more = 0; //printf("Calling SSL_write\n"); int written = SSL_write(s->ssl, data, length); //printf("Returning from SSL_write\n"); loop_ssl_data->msg_more = 0; if (loop_ssl_data->last_write_was_msg_more && !msg_more) { us_socket_flush(0, &s->s); } if (written > 0) { return written; } else { int err = SSL_get_error(s->ssl, written); if (err == SSL_ERROR_WANT_READ) { // here we need to trigger writable event next ssl_read! s->ssl_write_wants_read = 1; } else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) { // these two errors may add to the error queue, which is per thread and must be cleared ERR_clear_error(); // all errors here except for want write are critical and should not happen } return 0; } } void *us_internal_ssl_socket_ext(struct us_internal_ssl_socket_t *s) { return s + 1; } int us_internal_ssl_socket_is_shut_down(struct us_internal_ssl_socket_t *s) { return us_socket_is_shut_down(0, &s->s) || SSL_get_shutdown(s->ssl) & SSL_SENT_SHUTDOWN; } void us_internal_ssl_socket_shutdown(struct us_internal_ssl_socket_t *s) { if (!us_socket_is_closed(0, &s->s) && !us_internal_ssl_socket_is_shut_down(s)) { struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); struct us_loop_t *loop = us_socket_context_loop(0, &context->sc); struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; // also makes no sense to touch this here! // however the idea is that if THIS socket is not the same as ssl_socket then this data is not for me // but this is not correct as it is currently anyways, any data available should be properly reset loop_ssl_data->ssl_read_input_length = 0; // essentially we need two of these: one for CURRENT CALL and one for CURRENT SOCKET WITH DATA // if those match in the BIO function then you may read, if not then you may not read // we need ssl_read_socket to be set in on_data and checked in the BIO loop_ssl_data->ssl_socket = &s->s; loop_ssl_data->msg_more = 0; // sets SSL_SENT_SHUTDOWN no matter what (not actually true if error!) int ret = SSL_shutdown(s->ssl); if (ret == 0) { ret = SSL_shutdown(s->ssl); } if (ret < 0) { int err = SSL_get_error(s->ssl, ret); if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) { // clear ERR_clear_error(); } // we get here if we are shutting down while still in init us_socket_shutdown(0, &s->s); } } } struct us_internal_ssl_socket_t *us_internal_ssl_socket_close(struct us_internal_ssl_socket_t *s) { return (struct us_internal_ssl_socket_t *) us_socket_close(0, (struct us_socket_t *) s); } struct us_internal_ssl_socket_t *us_internal_ssl_socket_context_adopt_socket(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *s, int ext_size) { // todo: this is completely untested return (struct us_internal_ssl_socket_t *) us_socket_context_adopt_socket(0, &context->sc, &s->s, sizeof(struct us_internal_ssl_socket_t) - sizeof(struct us_socket_t) + ext_size); } #endif
the_stack_data/2542.c
#if 0 mini_exit mini_buf 0 mini_start shrinkelf INCLUDESRC LDSCRIPT text_and_bss OPTFLAG -Os return #endif int main(){ volatile int ret=42; volatile int a1=0; exit(a1); return(ret); }
the_stack_data/31197.c
#include <stdio.h> static inline void solve(){ int n, m; scanf("%d%d", &n, &m); m <<= 3; if(m > (n << 1) + n)puts("Too much"); else if(m >= (n << 1))puts("Yes"); else puts("Not enough"); } int main(){ solve(); return 0; }
the_stack_data/139426.c
// WARNING in __mmdrop // https://syzkaller.appspot.com/bug?id=eda1cb12a055e0a702b7461e5daff135e58e2118 // status:open // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <net/if_arp.h> #include <netinet/in.h> #include <pthread.h> #include <sched.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/futex.h> #include <linux/if_addr.h> #include <linux/if_ether.h> #include <linux/if_link.h> #include <linux/if_tun.h> #include <linux/in6.h> #include <linux/ip.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/tcp.h> #include <linux/veth.h> unsigned long long procid; static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* ctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) && (addr < prog_start || addr > prog_end)) { _longjmp(segv_env, 1); } exit(sig); } static void install_segv_handler(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8); syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = segv_handler; sa.sa_flags = SA_NODEFER | SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #define NONFAILING(...) \ { \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ } static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir(void) { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) exit(1); if (chmod(tmpdir, 0777)) exit(1); if (chdir(tmpdir)) exit(1); } static void thread_start(void* (*fn)(void*), void* arg) { pthread_t th; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); int i; for (i = 0; i < 100; i++) { if (pthread_create(&th, &attr, fn, arg) == 0) { pthread_attr_destroy(&attr); return; } if (errno == EAGAIN) { usleep(50); continue; } break; } exit(1); } typedef struct { int state; } event_t; static void event_init(event_t* ev) { ev->state = 0; } static void event_reset(event_t* ev) { ev->state = 0; } static void event_set(event_t* ev) { if (ev->state) exit(1); __atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG); } static void event_wait(event_t* ev) { while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0); } static int event_isset(event_t* ev) { return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE); } static int event_timedwait(event_t* ev, uint64_t timeout) { uint64_t start = current_time_ms(); uint64_t now = start; for (;;) { uint64_t remain = timeout - (now - start); struct timespec ts; ts.tv_sec = remain / 1000; ts.tv_nsec = (remain % 1000) * 1000 * 1000; syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts); if (__atomic_load_n(&ev->state, __ATOMIC_RELAXED)) return 1; now = current_time_ms(); if (now - start > timeout) return 0; } } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static struct { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; } nlmsg; static void netlink_init(int typ, int flags, const void* data, int size) { memset(&nlmsg, 0, sizeof(nlmsg)); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg.buf; hdr->nlmsg_type = typ; hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; memcpy(hdr + 1, data, size); nlmsg.pos = (char*)(hdr + 1) + NLMSG_ALIGN(size); } static void netlink_attr(int typ, const void* data, int size) { struct nlattr* attr = (struct nlattr*)nlmsg.pos; attr->nla_len = sizeof(*attr) + size; attr->nla_type = typ; memcpy(attr + 1, data, size); nlmsg.pos += NLMSG_ALIGN(attr->nla_len); } static void netlink_nest(int typ) { struct nlattr* attr = (struct nlattr*)nlmsg.pos; attr->nla_type = typ; nlmsg.pos += sizeof(*attr); nlmsg.nested[nlmsg.nesting++] = attr; } static void netlink_done(void) { struct nlattr* attr = nlmsg.nested[--nlmsg.nesting]; attr->nla_len = nlmsg.pos - (char*)attr; } static int netlink_send(int sock) { if (nlmsg.pos > nlmsg.buf + sizeof(nlmsg.buf) || nlmsg.nesting) exit(1); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg.buf; hdr->nlmsg_len = nlmsg.pos - nlmsg.buf; struct sockaddr_nl addr; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; unsigned n = sendto(sock, nlmsg.buf, hdr->nlmsg_len, 0, (struct sockaddr*)&addr, sizeof(addr)); if (n != hdr->nlmsg_len) exit(1); n = recv(sock, nlmsg.buf, sizeof(nlmsg.buf), 0); if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static void netlink_add_device_impl(const char* type, const char* name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); netlink_init(RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); if (name) netlink_attr(IFLA_IFNAME, name, strlen(name)); netlink_nest(IFLA_LINKINFO); netlink_attr(IFLA_INFO_KIND, type, strlen(type)); } static void netlink_add_device(int sock, const char* type, const char* name) { netlink_add_device_impl(type, name); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_veth(int sock, const char* name, const char* peer) { netlink_add_device_impl("veth", name); netlink_nest(IFLA_INFO_DATA); netlink_nest(VETH_INFO_PEER); nlmsg.pos += sizeof(struct ifinfomsg); netlink_attr(IFLA_IFNAME, peer, strlen(peer)); netlink_done(); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_hsr(int sock, const char* name, const char* slave1, const char* slave2) { netlink_add_device_impl("hsr", name); netlink_nest(IFLA_INFO_DATA); int ifindex1 = if_nametoindex(slave1); netlink_attr(IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1)); int ifindex2 = if_nametoindex(slave2); netlink_attr(IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2)); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_device_change(int sock, const char* name, bool up, const char* master, const void* mac, int macsize) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; netlink_init(RTM_NEWLINK, 0, &hdr, sizeof(hdr)); netlink_attr(IFLA_IFNAME, name, strlen(name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(IFLA_ADDRESS, mac, macsize); int err = netlink_send(sock); (void)err; } static int netlink_add_addr(int sock, const char* dev, const void* addr, int addrsize) { struct ifaddrmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120; hdr.ifa_scope = RT_SCOPE_UNIVERSE; hdr.ifa_index = if_nametoindex(dev); netlink_init(RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr, sizeof(hdr)); netlink_attr(IFA_LOCAL, addr, addrsize); netlink_attr(IFA_ADDRESS, addr, addrsize); return netlink_send(sock); } static void netlink_add_addr4(int sock, const char* dev, const char* addr) { struct in_addr in_addr; inet_pton(AF_INET, addr, &in_addr); int err = netlink_add_addr(sock, dev, &in_addr, sizeof(in_addr)); (void)err; } static void netlink_add_addr6(int sock, const char* dev, const char* addr) { struct in6_addr in6_addr; inet_pton(AF_INET6, addr, &in6_addr); int err = netlink_add_addr(sock, dev, &in6_addr, sizeof(in6_addr)); (void)err; } static void netlink_add_neigh(int sock, const char* name, const void* addr, int addrsize, const void* mac, int macsize) { struct ndmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ndm_ifindex = if_nametoindex(name); hdr.ndm_state = NUD_PERMANENT; netlink_init(RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); netlink_attr(NDA_DST, addr, addrsize); netlink_attr(NDA_LLADDR, mac, macsize); int err = netlink_send(sock); (void)err; } static int tunfd = -1; static int tun_frags_enabled; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define TUN_IFACE "syz_tun" #define LOCAL_MAC 0xaaaaaaaaaaaa #define REMOTE_MAC 0xaaaaaaaaaabb #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 240; if (dup2(tunfd, kTunFd) < 0) exit(1); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) exit(1); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) exit(1); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; char sysctl[64]; sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE); write_file(sysctl, "0"); sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE); write_file(sysctl, "0"); int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); netlink_add_addr4(sock, TUN_IFACE, LOCAL_IPV4); netlink_add_addr6(sock, TUN_IFACE, LOCAL_IPV6); uint64_t macaddr = REMOTE_MAC; struct in_addr in_addr; inet_pton(AF_INET, REMOTE_IPV4, &in_addr); netlink_add_neigh(sock, TUN_IFACE, &in_addr, sizeof(in_addr), &macaddr, ETH_ALEN); struct in6_addr in6_addr; inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr); netlink_add_neigh(sock, TUN_IFACE, &in6_addr, sizeof(in6_addr), &macaddr, ETH_ALEN); macaddr = LOCAL_MAC; netlink_device_change(sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN); close(sock); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02x" #define DEV_MAC 0x00aaaaaaaaaa static void initialize_netdevices(void) { char netdevsim[16]; sprintf(netdevsim, "netdevsim%d", (int)procid); struct { const char* type; const char* dev; } devtypes[] = { {"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"}, {"vcan", "vcan0"}, {"bond", "bond0"}, {"team", "team0"}, {"dummy", "dummy0"}, {"nlmon", "nlmon0"}, {"caif", "caif0"}, {"batadv", "batadv0"}, {"vxcan", "vxcan1"}, {"netdevsim", netdevsim}, {"veth", 0}, }; const char* devmasters[] = {"bridge", "bond", "team"}; struct { const char* name; int macsize; bool noipv6; } devices[] = { {"lo", ETH_ALEN}, {"sit0", 0}, {"bridge0", ETH_ALEN}, {"vcan0", 0, true}, {"tunl0", 0}, {"gre0", 0}, {"gretap0", ETH_ALEN}, {"ip_vti0", 0}, {"ip6_vti0", 0}, {"ip6tnl0", 0}, {"ip6gre0", 0}, {"ip6gretap0", ETH_ALEN}, {"erspan0", ETH_ALEN}, {"bond0", ETH_ALEN}, {"veth0", ETH_ALEN}, {"veth1", ETH_ALEN}, {"team0", ETH_ALEN}, {"veth0_to_bridge", ETH_ALEN}, {"veth1_to_bridge", ETH_ALEN}, {"veth0_to_bond", ETH_ALEN}, {"veth1_to_bond", ETH_ALEN}, {"veth0_to_team", ETH_ALEN}, {"veth1_to_team", ETH_ALEN}, {"veth0_to_hsr", ETH_ALEN}, {"veth1_to_hsr", ETH_ALEN}, {"hsr0", 0}, {"dummy0", ETH_ALEN}, {"nlmon0", 0}, {"vxcan1", 0, true}, {"caif0", ETH_ALEN}, {"batadv0", ETH_ALEN}, {netdevsim, ETH_ALEN}, }; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) netlink_add_device(sock, devtypes[i].type, devtypes[i].dev); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { char master[32], slave0[32], veth0[32], slave1[32], veth1[32]; sprintf(slave0, "%s_slave_0", devmasters[i]); sprintf(veth0, "veth0_to_%s", devmasters[i]); netlink_add_veth(sock, slave0, veth0); sprintf(slave1, "%s_slave_1", devmasters[i]); sprintf(veth1, "veth1_to_%s", devmasters[i]); netlink_add_veth(sock, slave1, veth1); sprintf(master, "%s0", devmasters[i]); netlink_device_change(sock, slave0, false, master, 0, 0); netlink_device_change(sock, slave1, false, master, 0, 0); } netlink_device_change(sock, "bridge_slave_0", true, 0, 0, 0); netlink_device_change(sock, "bridge_slave_1", true, 0, 0, 0); netlink_add_veth(sock, "hsr_slave_0", "veth0_to_hsr"); netlink_add_veth(sock, "hsr_slave_1", "veth1_to_hsr"); netlink_add_hsr(sock, "hsr0", "hsr_slave_0", "hsr_slave_1"); netlink_device_change(sock, "hsr_slave_0", true, 0, 0, 0); netlink_device_change(sock, "hsr_slave_1", true, 0, 0, 0); for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) { char addr[32]; sprintf(addr, DEV_IPV4, i + 10); netlink_add_addr4(sock, devices[i].name, addr); if (!devices[i].noipv6) { sprintf(addr, DEV_IPV6, i + 10); netlink_add_addr6(sock, devices[i].name, addr); } uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40); netlink_device_change(sock, devices[i].name, true, 0, &macaddr, devices[i].macsize); } close(sock); } static void initialize_netdevices_init(void) { int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); struct { const char* type; int macsize; bool noipv6; bool noup; } devtypes[] = { {"nr", 7, true}, {"rose", 5, true, true}, }; unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) { char dev[32], addr[32]; sprintf(dev, "%s%d", devtypes[i].type, (int)procid); sprintf(addr, "172.30.%d.%d", i, (int)procid + 1); netlink_add_addr4(sock, dev, addr); if (!devtypes[i].noipv6) { sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1); netlink_add_addr6(sock, dev, addr); } int macsize = devtypes[i].macsize; uint64_t macaddr = 0xbbbbbb + ((unsigned long long)i << (8 * (macsize - 2))) + (procid << (8 * (macsize - 1))); netlink_device_change(sock, dev, !devtypes[i].noup, 0, &macaddr, macsize); } close(sock); } static int read_tun(char* data, int size) { if (tunfd < 0) return -1; int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN) return -1; if (errno == EBADFD) return -1; exit(1); } return rv; } static void flush_tun() { char data[SYZ_TUN_MAX_PACKET_SIZE]; while (read_tun(&data[0], sizeof(data)) != -1) { } } static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2) { if (a0 == 0xc || a0 == 0xb) { char buf[128]; sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1, (uint8_t)a2); return open(buf, O_RDWR, 0); } else { char buf[1024]; char* hash; NONFAILING(strncpy(buf, (char*)a0, sizeof(buf) - 1)); buf[sizeof(buf) - 1] = 0; while ((hash = strchr(buf, '#'))) { *hash = '0' + (char)(a1 % 10); a1 /= 10; } return open(buf, a2, 0); } } #define XT_TABLE_SIZE 1536 #define XT_MAX_ENTRIES 10 struct xt_counters { uint64_t pcnt, bcnt; }; struct ipt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_entries; unsigned int size; }; struct ipt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct ipt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct ipt_table_desc { const char* name; struct ipt_getinfo info; struct ipt_replace replace; }; static struct ipt_table_desc ipv4_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; static struct ipt_table_desc ipv6_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) struct arpt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_entries; unsigned int size; }; struct arpt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct arpt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct arpt_table_desc { const char* name; struct arpt_getinfo info; struct arpt_replace replace; }; static struct arpt_table_desc arpt_tables[] = { {.name = "filter"}, }; #define ARPT_BASE_CTL 96 #define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL) #define ARPT_SO_GET_INFO (ARPT_BASE_CTL) #define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1) static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct ipt_get_entries entries; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct xt_counters counters[XT_MAX_ENTRIES]; struct ipt_get_entries entries; struct ipt_getinfo info; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_arptables(void) { struct arpt_get_entries entries; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_arptables() { struct xt_counters counters[XT_MAX_ENTRIES]; struct arpt_get_entries entries; struct arpt_getinfo info; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } else { } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } #define NF_BR_NUMHOOKS 6 #define EBT_TABLE_MAXNAMELEN 32 #define EBT_CHAIN_MAXNAMELEN 32 #define EBT_BASE_CTL 128 #define EBT_SO_SET_ENTRIES (EBT_BASE_CTL) #define EBT_SO_GET_INFO (EBT_BASE_CTL) #define EBT_SO_GET_ENTRIES (EBT_SO_GET_INFO + 1) #define EBT_SO_GET_INIT_INFO (EBT_SO_GET_ENTRIES + 1) #define EBT_SO_GET_INIT_ENTRIES (EBT_SO_GET_INIT_INFO + 1) struct ebt_replace { char name[EBT_TABLE_MAXNAMELEN]; unsigned int valid_hooks; unsigned int nentries; unsigned int entries_size; struct ebt_entries* hook_entry[NF_BR_NUMHOOKS]; unsigned int num_counters; struct ebt_counter* counters; char* entries; }; struct ebt_entries { unsigned int distinguisher; char name[EBT_CHAIN_MAXNAMELEN]; unsigned int counter_offset; int policy; unsigned int nentries; char data[0] __attribute__((aligned(__alignof__(struct ebt_replace)))); }; struct ebt_table_desc { const char* name; struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; }; static struct ebt_table_desc ebt_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "broute"}, }; static void checkpoint_ebtables(void) { socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; strcpy(table->replace.name, table->name); optlen = sizeof(table->replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->replace.entries_size > sizeof(table->entrytable)) exit(1); table->replace.num_counters = 0; table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace, &optlen)) exit(1); } close(fd); } static void reset_ebtables() { struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; socklen_t optlen; unsigned i, j, h; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; if (table->replace.valid_hooks == 0) continue; memset(&replace, 0, sizeof(replace)); strcpy(replace.name, table->name); optlen = sizeof(replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen)) exit(1); replace.num_counters = 0; table->replace.entries = 0; for (h = 0; h < NF_BR_NUMHOOKS; h++) table->replace.hook_entry[h] = 0; if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) { memset(&entrytable, 0, sizeof(entrytable)); replace.entries = entrytable; optlen = sizeof(replace) + replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen)) exit(1); if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0) continue; } for (j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) { if (table->replace.valid_hooks & (1 << h)) { table->replace.hook_entry[h] = (struct ebt_entries*)table->entrytable + j; j++; } } table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_net_namespace(void) { checkpoint_ebtables(); checkpoint_arptables(); checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void reset_net_namespace(void) { reset_ebtables(); reset_arptables(); reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void setup_cgroups() { if (mkdir("/syzcgroup", 0777)) { } if (mkdir("/syzcgroup/unified", 0777)) { } if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) { } if (chmod("/syzcgroup/unified", 0777)) { } write_file("/syzcgroup/unified/cgroup.subtree_control", "+cpu +memory +io +pids +rdma"); if (mkdir("/syzcgroup/cpu", 0777)) { } if (mount("none", "/syzcgroup/cpu", "cgroup", 0, "cpuset,cpuacct,perf_event,hugetlb")) { } write_file("/syzcgroup/cpu/cgroup.clone_children", "1"); if (chmod("/syzcgroup/cpu", 0777)) { } if (mkdir("/syzcgroup/net", 0777)) { } if (mount("none", "/syzcgroup/net", "cgroup", 0, "net_cls,net_prio,devices,freezer")) { } if (chmod("/syzcgroup/net", 0777)) { } } static void setup_cgroups_loop() { int pid = getpid(); char file[128]; char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/pids.max", cgroupdir); write_file(file, "32"); snprintf(file, sizeof(file), "%s/memory.low", cgroupdir); write_file(file, "%d", 298 << 20); snprintf(file, sizeof(file), "%s/memory.high", cgroupdir); write_file(file, "%d", 299 << 20); snprintf(file, sizeof(file), "%s/memory.max", cgroupdir); write_file(file, "%d", 300 << 20); snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); } static void setup_cgroups_test() { char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (symlink(cgroupdir, "./cgroup")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.cpu")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.net")) { } } static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } setup_cgroups(); } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = (200 << 20); setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = rlim.rlim_max = 256; setrlimit(RLIMIT_NOFILE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } typedef struct { const char* name; const char* value; } sysctl_t; static const sysctl_t sysctls[] = { {"/proc/sys/kernel/shmmax", "16777216"}, {"/proc/sys/kernel/shmall", "536870912"}, {"/proc/sys/kernel/shmmni", "1024"}, {"/proc/sys/kernel/msgmax", "8192"}, {"/proc/sys/kernel/msgmni", "1024"}, {"/proc/sys/kernel/msgmnb", "1024"}, {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, }; unsigned i; for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++) write_file(sysctls[i].name, sysctls[i].value); } int wait_for_loop(int pid) { if (pid < 0) exit(1); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_common(); sandbox_common(); initialize_netdevices_init(); if (unshare(CLONE_NEWNET)) { } initialize_tun(); initialize_netdevices(); loop(); exit(1); } #define FS_IOC_SETFLAGS _IOW('f', 2, long) static void remove_dir(const char* dir) { DIR* dp; struct dirent* ep; int iter = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exit(1); } exit(1); } while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); while (umount2(filename, MNT_DETACH) == 0) { } struct stat st; if (lstat(filename, &st)) exit(1); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EPERM) { int fd = open(filename, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) close(fd); continue; } } if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exit(1); if (umount2(filename, MNT_DETACH)) exit(1); } } closedir(dp); int i; for (i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EPERM) { int fd = open(dir, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) close(fd); continue; } } if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exit(1); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exit(1); } } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); int i; for (i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_loop() { setup_cgroups_loop(); checkpoint_net_namespace(); } static void reset_loop() { reset_net_namespace(); } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setup_cgroups_test(); write_file("/proc/self/oom_score_adj", "1000"); flush_tun(); } static void close_fds() { int fd; for (fd = 3; fd < 30; fd++) close(fd); } static void setup_binfmt_misc() { if (mount(0, "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, 0)) { } write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:\x01::./file0:"); write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:\x02::./file0:POC"); } struct thread_t { int created, call; event_t ready, done; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { event_wait(&th->ready); event_reset(&th->ready); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); event_set(&th->done); } return 0; } static void execute_one(void) { int i, call, thread; int collide = 0; again: for (call = 0; call < 7; call++) { for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; event_init(&th->ready); event_init(&th->done); event_set(&th->done); thread_start(thr, th); } if (!event_isset(&th->done)) continue; event_reset(&th->done); th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); event_set(&th->ready); if (collide && (call % 2) == 0) break; event_timedwait(&th->done, 45); break; } } for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++) sleep_ms(1); close_fds(); if (!collide) { collide = 1; goto again; } } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { setup_loop(); int iter; for (iter = 0;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) exit(1); reset_loop(); int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { if (chdir(cwdbuf)) exit(1); setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5 * 1000) continue; kill_and_wait(pid, &status); break; } remove_dir(cwdbuf); } } uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff}; void execute_call(int call) { intptr_t res; switch (call) { case 0: NONFAILING(memcpy((void*)0x200000c0, "/dev/vhost-net\000", 15)); res = syscall(__NR_openat, 0xffffffffffffff9c, 0x200000c0, 2, 0); if (res != -1) r[0] = res; break; case 1: res = syz_open_dev(0, 4, 0x14000); if (res != -1) r[1] = res; break; case 2: syscall(__NR_getsockopt, 0xffffff9c, 0x84, 0x72, 0, 0); break; case 3: syscall(__NR_getsockopt, r[1], 0x84, 0x6f, 0, 0); break; case 4: NONFAILING(memcpy((void*)0x20000180, "/dev/net/tun\000", 13)); syscall(__NR_openat, 0xffffffffffffff9c, 0x20000180, 0, 0); break; case 5: syscall(__NR_ioctl, r[0], 0xaf01, 0); break; case 6: NONFAILING(*(uint32_t*)0x200023c0 = 0); NONFAILING(*(uint32_t*)0x200023c4 = 0); NONFAILING(*(uint64_t*)0x200023c8 = 0); NONFAILING(*(uint64_t*)0x200023d0 = 0); NONFAILING(*(uint64_t*)0x200023d8 = 0); NONFAILING(*(uint64_t*)0x200023e0 = 0); syscall(__NR_ioctl, r[0], 0x4028af11, 0x200023c0); break; } } int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); setup_binfmt_misc(); install_segv_handler(); use_temporary_dir(); do_sandbox_none(); return 0; }
the_stack_data/125140985.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 long input[1] , unsigned long output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void RandomFunc(unsigned long input[1] , unsigned long output[1] ) { unsigned long state[1] ; unsigned long local1 ; { state[0UL] = input[0UL] + 0xffffffffff660b45UL; local1 = 0UL; while (local1 < input[1UL]) { state[local1] += state[local1]; local1 += 2UL; } output[0UL] = state[0UL] - 0xffffffffda4ab609UL; } } void megaInit(void) { { } } int main(int argc , char *argv[] ) { unsigned long input[1] ; unsigned long output[1] ; int randomFuns_i5 ; unsigned long randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 4242424242UL) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%lu\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } }
the_stack_data/17559.c
/* * File: grcm.c * ============= * Do the general reverse Cuthill-Mckee ordering * * Originally written by: David R. Mackay * * Modified by: * Jun Peng ([email protected]) * Prof. Kincho H. Law * Stanford University * -------------------- */ #include <assert.h> /* fmk - adding prototypes */ void zeroi(int, int *); int rcm(int root, int **padj, int *mask, int *perm, int *deg, int *work); int fnroot(int root, int **padj, int *mask, int *nlvl, int *xls, int *ls); int ndegree(int root, int **padj, int *mask, int *deg, int *ls, int *work); void revrse(int n, int *v); /************************************************************************* ***********************genrcm . . . general reverse cuthill mckee ******** ************************************************************************** purpose - genrcm finds the reverse cuthill-mckee ordering for a general graph. for each connected component in the graph genrcm obtains the ordering by calling the subroutine rcm. input parameters - neqns - number of equations padj - the adjacency structure output parameter - perm - vector that contains the rcm ordering working parameters mask - is used to mark variables that have been numbered during the ordering process. it is initialized to 0 and set to -1 as each nod is numbered. xls - the index bector for a vevel structure. the level structre is sotred in the currently unused spaces in the permutation vectore perm. work - a working vector program routines - fnroot, rcm *************************************************************************/ void genrcm(int neqns, int **padj, int *perm, int *mask, int *xls, int *work) { int num, i, root, nlvl, ccsize; zeroi(neqns, work); zeroi(neqns, mask); num = 0; for (i=0;i<neqns ; i++) { /* --------------------------------------------------- for each masked connected component -------------------------------------------------*/ if (mask[i] < 0) continue ; root = i ; /* ------------------------------------------------------------ first find a pseudo-peripheral node root. note that the level structure found by fnroot is stored starting at perm[num]. then rcm is called to order the component using root as the starting node. ----------------------------------------------------------*/ root = fnroot(root, padj, mask, &nlvl, xls, perm + num) ; ccsize = rcm(root, padj, mask, perm+num,xls, work) ; num += ccsize ; if (num > neqns) return ; } return; } /************************************************************************* *****************subrcm . . . substructure reverse cuthill mckee ******** ************************************************************************* purpose - subrcm finds the reverse cuthill-mckee ordering for a subgraph. for each connected component in the graph subrcm obtains the ordering by calling the subroutine rcm. input parameters - neqns - number of equations padj - the adjacency structure root - first trial root ( any node that lies int the subgraph) output parameter - perm - vector that contains the rcm ordering working parameters mask - is used to mark variables that have been numbered during the ordering process. it is initialized to 0 and set to -1 as each node is numbered. xls - the index bector for a vevel structure. the level structre is sotred in the currently unused spaces in the permutation vectore perm. work - a working vector program routines - fnroot, rcm *************************************************************************/ void subrcm (int neqns, int root, int **padj, int *perm, int *mask, int *xls, int *work) { int num, nlvl, ccsize ; zeroi(neqns, work) ; num = 0 ; if (mask[root] <0) return ; /* ------------------------------------------------------------ first find a pseudo-peripheral node root. note that the level structure found by fnroot is stored starting at perm[num]. then rcm is called to order the component using root as the starting node. ----------------------------------------------------------*/ root = fnroot(root, padj, mask, &nlvl, xls, perm + num) ; ccsize = rcm(root, padj, mask, perm+num,xls, work) ; num += ccsize ; if (num > neqns) return ; return ; } /*********************************************************************** ******************** rcm . . . reverse cuthill mckee ****************** ************************************************************************ purpose - rcm numbers a connected component spedified by mask and root, using the rcm algorithm. the numbering is to be started at the node root. input parameters - root - is the node that defines the connected component and it is used as the starting node for the rcm ordering. padj - the adjacency structure updated parameters - mask - only those nodes wiht nonnegarive inpu mask values are considered by the routine. the nodes numbered by rcm will have their mask values set to zero. output parameters - perm - will contain the rcm ordering. ccsize - is the size of the connected component that ahas been numbered by rcm. working parameter - work - must be set to zero's before calling!!!!!!!!! deg - is a temporary vector used to hold the degree of the nodes in the section graph specified by mask and root. program routines degree *************************************************************************/ int rcm(int root, int **padj, int *mask, int *perm, int *deg, int *work) { int ccsize ; int i, lbegin, lvlend, lnbr, nbr, node, fnbr, k, l, lperm ; int *ptr ; /* --------------------------------------- find the degrees of the nodes in the component specified by mask and root. --------------------------------------*/ ccsize = ndegree(root, padj, mask, deg, perm, work) ; mask[root] |= -1 ; if (ccsize <= 1) return(ccsize) ; lvlend &= 0 ; lnbr = 1 ; /* ----------------------------------------------------- lbegin and lvlend point to the begiinning adn the end of the current level respectively. -----------------------------------------------------*/ do { lbegin = lvlend ; lvlend = lnbr ; for (i = lbegin ; i < lvlend ; i++) { /* ------------------------------------------ for each node in current level . . . ----------------------------------------*/ node = perm[i] ; /* ----------------------------------------------------- find the unnumbered neighbors of node. fnbr and lnbr point to the first and last unnumbered neighbors respectively of the current node in perm. -----------------------------------------------------*/ fnbr = lnbr ; for (ptr = padj[node] ; ptr < padj[node + 1] ; ptr++) { if (mask[*ptr] < 0 ) continue ; mask[*ptr] |= -1 ; perm[lnbr] = *ptr ; lnbr++ ; } if (fnbr < lnbr-1) { /* --------------------------------------------------- sort the neighbors of node in increasing order by degree. linear insertion i sused. --------------------------------------------------*/ k = fnbr ; do { l = k ; k++ ; nbr = perm[k] ; while( l >= fnbr ) { lperm = perm[l] ; if (deg[lperm] <= deg[nbr]) break ; perm[l+1] = lperm ; l-- ; } perm[l+1] = nbr ; } while(k < lnbr-1) ; } /* endif */ } /* end for i = */ } while(lnbr > lvlend ) ; /* end do */ /* ---------------------------------------------------------- we now haave the cuthill mckee ordering now reverse it --------------------------------------------------------*/ revrse(ccsize, perm) ; return(ccsize) ; } /************************************************************************** ******************** ndegree . . . degree in masked component ************** *************************************************************************** purpose - This routine computes the degrees of the nodes in the connected component speciified by mask and root. nodes for which mask is -1 are ignored. input parameter - root - is the input node that defines the component padj - the adjacency structure mask - specifies a section subgraph work - must be initialized to zero before degree is called !!!! output parameters deg - array containing the degrees of the nodes in the component. ccsize - size of the component specified by mask and root working parameter - ls - a temporary vector used to store the nodes of the component level by level. ************************************************************************/ int ndegree(int root, int **padj, int *mask, int *deg, int *ls, int *work) { int ccsize ; int i, lbegin, lvlend, node, ideg, lvsize ; int *ptr ; int minone = -1 ; /* ------------------------------------------ initialization . . .. the array work is used to mark which nodes have been considered so far. -----------------------------------------*/ ls[0] = root ; work[root] |= minone ; lvlend &= 0 ; ccsize = 1 ; /* ------------------------------------------------------------- lbegin is the pointer to the beginning of the current level, and lvlend points to the end of this level. ------------------------------------------------------------*/ do { lbegin = lvlend ; lvlend = ccsize ; /* --------------------------------------------------------- find the degrees of nodes in the current level, and at the same time, generate the next level. --------------------------------------------------------*/ for (i=lbegin ; i < lvlend ; i++) { node = ls[i] ; ideg = 0 ; for (ptr = padj[node] ; ptr < padj[node+1] ; ptr++) { if (mask[*ptr] < 0) continue ; ideg++ ; if (work[*ptr] < 0) continue ; work[*ptr] |= minone ; ls[ccsize] = *ptr ; ccsize++ ; } deg[node] = ideg ; } /* ----------------------------------------------------- compute the current level width. if it is nonnegative. generate another level. ---------------------------------------------------*/ lvsize = ccsize - lvlend ; } while (lvsize > 0) ; /* ------------------------------------------------------ reset work to 0 -----------------------------------------------------*/ for (i=0;i<ccsize ; i++) { node = ls[i] ; work[node] &= 0 ; } return(ccsize) ; }
the_stack_data/34511664.c
// KMSAN: uninit-value in fib_create_info // https://syzkaller.appspot.com/bug?id=9fe6bd32d4ac5295a0c88f101083e39f393a8984 // status:fixed // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <stdint.h> #include <string.h> #include <sys/syscall.h> #include <unistd.h> uint64_t r[1] = {0xffffffffffffffff}; void loop() { long res = 0; res = syscall(__NR_socket, 0x10, 3, 0); if (res != -1) r[0] = res; *(uint64_t*)0x2000bfc8 = 0x20000080; *(uint16_t*)0x20000080 = 0x10; *(uint16_t*)0x20000082 = 0; *(uint32_t*)0x20000084 = 0; *(uint32_t*)0x20000088 = 0; *(uint32_t*)0x2000bfd0 = 0x80; *(uint64_t*)0x2000bfd8 = 0x20002000; *(uint64_t*)0x20002000 = 0x20b4efab; memcpy((void*)0x20b4efab, "\x55\x00\x00\x00\x18\x00\x7f\xaf\xb7\xa4\x1c\xb2\x2d\xa2\x80\x00\x02" "\x06\x00\x00\x00\xa8\x43\x09\x6c\x37\x23\x69\x39\x00\x09\x00\x21\x00" "\x03\x00\x4b\x00\xca\x8a\x98\x48\xa3\x09\x00\x00\x00\x6b\x7b\x31\xaf" "\xdc\x13\x38\xd5\x44\x00\x00\x9b\x84\x13\x6e\xf7\x5a\xfb\x83\xde\x44" "\x11\x00\x68\x27\xc4\x3a\xb8\x22\x00\x00\xbf\x0c\xec\x6b\xab\x91\xd4", 85); *(uint64_t*)0x20002008 = 0x55; *(uint64_t*)0x2000bfe0 = 1; *(uint64_t*)0x2000bfe8 = 0x20004000; *(uint64_t*)0x2000bff0 = 0; *(uint32_t*)0x2000bff8 = 0; syscall(__NR_sendmsg, r[0], 0x2000bfc8, 0); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); loop(); return 0; }
the_stack_data/247019328.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 #define UNDEF -1 /** * @brief * * @param s1 * @param s2 * @return int */ char *sort(char *target) { int length = strlen(target); int swapped = 0; int temporaryVale = 0; do { swapped = 0; for (int i = 0; i < (length - 1); i++) { if (target[i] > target[i + 1]) { temporaryVale = target[i]; target[i] = target[i + 1]; target[i + 1] = temporaryVale; swapped = 1; } } } while (swapped != 0); return target; } int isPermutationOf(const char *s1, const char *s2) { char *ps1; //=malloc(sizeof(s1[0]*strlen(s1))) char *ps2; if (strlen(s1) == 0 || strlen(s2) == 0) { return FALSE; } if (strlen(s1) != strlen(s2)) { return FALSE; } ps1 = malloc(sizeof(s1[0]) * (strlen(s1) + 1)); ps2 = malloc(sizeof(s2[0]) * (strlen(s2) + 1)); if (ps1 == NULL || ps2 == NULL) { return UNDEF; } strcpy(ps1, s1); strcpy(ps2, s2); sort(ps1); sort(ps2); if (strcmp(ps1, ps2) == 0) { free(ps1); free(ps2); return TRUE; } free(ps1); free(ps2); return FALSE; } void test(int expected, int actual, const char *testName) { if (expected == actual) { printf("\nPASSED %s ", testName); } else { printf("\nFAILED %s FAILED", testName); printf("\n expected: %d actual: %d", expected, actual); } } int main(int argc, char const *argv[]) { test(TRUE, isPermutationOf("a", "a"), "a"); test(TRUE, isPermutationOf("abc", "abc"), "abc"); test(TRUE, isPermutationOf("cab", "bac"), "cab=>bac"); test(FALSE, isPermutationOf("c", "b"), "c=>b"); test(TRUE, isPermutationOf("abcdefg", "gfedcba"), "abcdefg"); test(FALSE, isPermutationOf("", "abc"), "1 is empty"); test(FALSE, isPermutationOf("abc", ""), "2 is empty"); test(FALSE, isPermutationOf("", ""), "1 and 2 is empty"); test(FALSE, isPermutationOf("abc", "ab"), "abc>=ab"); test(TRUE, isPermutationOf("123456789", "987654321"), "123456789"); return 0; }
the_stack_data/47911.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> struct _page_hits { char *page; int hits; }; int _page_hits_cmp(const void *a, const void *b) { if (((struct _page_hits*)a)->hits < ((struct _page_hits*)b)->hits) return 1; if (((struct _page_hits*)a)->hits > ((struct _page_hits*)b)->hits) return -1; return 0; } int min(int a, int b) { return a<b ? a : b; } int main(int argc, char *argv[]) { char line[2048]; char page[1024]; char lang[16]; int hits; int i, line_len; struct _page_hits page_hits[1024]; int idx=0; clock_t t0, t1; int fd_in = open(argv[1], O_RDONLY); char *addr, *p1, *p2; struct stat file_stat; int j; t0 = clock(); stat(argv[1], &file_stat); addr = (char*)mmap(0, (size_t)file_stat.st_size, PROT_READ, MAP_PRIVATE, fd_in, 0); for (p1 = addr; p1-addr < (int)file_stat.st_size; p1 = p2 + 1) { p2 = strchr(p1, '\n'); if (p2 > addr + (int)file_stat.st_size) { p2 = addr + (int)file_stat.st_size; } strncpy(line, p1, p2-p1); line[p2-p1] = '\0'; sscanf(line, "%s %s %d %*s", lang, page, &hits); if (strcmp(lang, "en")) { continue; } if (hits > 500) { page_hits[idx].page = strdup(page); page_hits[idx].hits = hits; ++idx; } } close(fd_in); qsort(page_hits, idx, sizeof(struct _page_hits), _page_hits_cmp); t1 = clock(); printf("Query took %.2f seconds\n", (t1-t0)/(double)CLOCKS_PER_SEC); for (i=0; i < min(10, idx); ++i) { printf("%s (%d)\n", page_hits[i].page, page_hits[i].hits); } return 0; }
the_stack_data/81899.c
#define swapmove(a, b, n, m, t) \ t = _mm_srli_epi32(b,n); \ t = _mm_xor_si128(t,a); \ t = _mm_and_si128(t,m); \ a = _mm_xor_si128(a,t); \ t = _mm_slli_epi32(t,n); \ b = _mm_xor_si128(b,t); #define bitslice(x0, x1, x2, x3, x4, x5, x6, x7) \ { \ __m128i t0, t1; \ t0 = _mm_set1_epi32(0x55555555); \ swapmove(x7, x6, 1, t0, t1); \ swapmove(x5, x4, 1, t0, t1); \ swapmove(x3, x2, 1, t0, t1); \ swapmove(x1, x0, 1, t0, t1); \ \ t0 = _mm_set1_epi32(0x33333333); \ swapmove(x7, x5, 2, t0, t1); \ swapmove(x6, x4, 2, t0, t1); \ swapmove(x3, x1, 2, t0, t1); \ swapmove(x2, x0, 2, t0, t1); \ \ t0 = _mm_set1_epi32(0x0f0f0f0f); \ swapmove(x7, x3, 4, t0, t1); \ swapmove(x6, x2, 4, t0, t1); \ swapmove(x5, x1, 4, t0, t1); \ swapmove(x4, x0, 4, t0, t1); \ }
the_stack_data/232956284.c
#include <arpa/inet.h> #include <ctype.h> #include <limits.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <unistd.h> #include <time.h> #include <errno.h> struct PseudoHdr { unsigned long saddr; unsigned long daddr; char reserved; unsigned char protocol; unsigned short length; }; #define PSEUDO sizeof(struct pseudohdr) #define TCPHDR sizeof(struct tcphdr) #define Z_NL 4294967295 unsigned short c_sum(unsigned short* data, int nbytes) { unsigned long sum = 0; for (; nbytes > 1; nbytes -= 2) { sum += *data++; } if (nbytes == 1) { sum += *(unsigned char*) data; } sum = (sum >> 16) + (sum & 0xffff); sum += (sum >> 16); return ~sum; } //unsigned char* buildTCPDatagram(struct sockaddr_in* src_sin, struct sockaddr_in* dst_sin, const unsigned char* msg, unsigned int msgSize); unsigned int buildPseudoHdrBuffer(unsigned int src_addr, unsigned int dst_addr, unsigned int protocol, const unsigned char* hdrData, unsigned int hdrBytes, const char* msgData, unsigned int msgBytes, unsigned short** buffer); int main(int argc, char** argv) { const char* dest_ip = (argc > 1 ? argv[1] : "127.0.0.1"); // destination IP const unsigned short dest_port = (argc > 2 ? atoi(argv[1]) : 80); // destination port unsigned short i; // root-privileges needed for the following operation int s = socket(PF_INET, SOCK_RAW, IPPROTO_TCP); if (s <= 0) { perror("[open_sockraw] socket()"); return 1; } int enable = 1; if (setsockopt(s, IPPROTO_IP, IP_HDRINCL, &enable, sizeof(enable)) < 0) { printf("Error: setsockopt() - Cannot set HDRINCL:\n"); return 1; } // We no longer need root privileges setuid(getuid()); // build up out source and destination sock addresses struct sockaddr_in src_sin; struct sockaddr_in dst_sin; src_sin.sin_family = PF_INET; src_sin.sin_addr.s_addr = inet_addr("127.0.0.1"); dst_sin.sin_family = PF_INET; dst_sin.sin_addr.s_addr = inet_addr(dest_ip); const char* msg = "Hello World"; const unsigned int msgSize = strlen(msg); const unsigned int datagramSize = sizeof(struct ip) + sizeof(struct tcphdr) + strlen(msg); unsigned char* datagram = calloc(1, datagramSize); const unsigned int hdrBytes = sizeof(struct tcphdr); // setup useful pointers to locations within the datagram struct ip* iph = (struct ip*) datagram; struct tcphdr* tcph = (struct tcphdr*)(datagram + sizeof(struct ip)); unsigned char* data = datagram + sizeof(struct ip) + sizeof(struct tcphdr); // build IP header iph->ip_hl = hdrBytes >> 2; iph->ip_v = 4; iph->ip_tos = 0; iph->ip_len = htons(datagramSize); iph->ip_off = 0; iph->ip_ttl = 64; iph->ip_p = IPPROTO_TCP; iph->ip_sum = 0; iph->ip_src.s_addr = src_sin.sin_addr.s_addr; iph->ip_dst.s_addr = dst_sin.sin_addr.s_addr; // now we compute the checksum for the IP header (albeit this is optional) // iph->ip_sum = c_sum((unsigned short*) iph, sizeof(struct ip)); // build TCP header tcph->ack_seq = htonl(0); tcph->res1 = 0; tcph->doff = hdrBytes >> 2; tcph->fin = 0; tcph->syn = 1; tcph->rst = 0; tcph->psh = 0; tcph->ack = 0; tcph->urg = 0; tcph->res2 = 0; tcph->window = htons(512); tcph->check = 0; tcph->urg_ptr = htons(0); struct PseudoHdr pseudoHdr; pseudoHdr.saddr = src_sin.sin_addr.s_addr; pseudoHdr.daddr = dst_sin.sin_addr.s_addr; pseudoHdr.reserved = 0; pseudoHdr.protocol = IPPROTO_TCP; pseudoHdr.length = htons(hdrBytes + msgSize); unsigned int bufSize = sizeof(struct PseudoHdr) + hdrBytes + msgSize; for (i = 1025; i < 11025; i++) { src_sin.sin_port = htons(i); dst_sin.sin_port = htons(dest_port); tcph->source = src_sin.sin_port; tcph->dest = dst_sin.sin_port; iph->ip_id = htons(i); tcph->seq = htonl(i); tcph->check = 0; unsigned char* buf = calloc(1, bufSize); int offset = 0; memcpy(buf + offset, &pseudoHdr, sizeof(struct PseudoHdr)); offset += sizeof(struct PseudoHdr); memcpy(buf + offset, tcph, hdrBytes); offset += hdrBytes; memcpy(buf + offset, msg, msgSize); // unsigned short* buffer = 0; // unsigned int bufferSize = buildPseudoHdrBuffer(src_sin.sin_addr.s_addr, dst_sin.sin_addr.s_addr, IPPROTO_TCP, // (const unsigned char*) tcph, sizeof(struct tcphdr), msg, msgSize, &buffer); tcph->check = c_sum((unsigned short*)buf, bufSize); free(buf); if (msgSize > 0) { memcpy(data, msg, msgSize); } if (sendto(s, datagram, datagramSize, 0, (struct sockaddr*) &dst_sin, sizeof(dst_sin)) < 0) { printf("Error with sendto() -- %s (%d)\n", strerror(errno), errno); break; } } free(datagram); return 0; } unsigned int buildPseudoHdrBuffer(unsigned int src_addr, unsigned int dst_addr, unsigned int protocol, const unsigned char* hdrData, unsigned int hdrBytes, const char* msgData, unsigned int msgBytes, unsigned short** buffer) { struct PseudoHdr pseudoHdr; pseudoHdr.saddr = src_addr; pseudoHdr.daddr = dst_addr; pseudoHdr.reserved = 0; pseudoHdr.protocol = protocol; pseudoHdr.length = htons(hdrBytes + msgBytes); unsigned int bufSize = sizeof(struct PseudoHdr) + hdrBytes + msgBytes; unsigned char* buf = calloc(1, bufSize); int offset = 0; memcpy(buf + offset, &pseudoHdr, sizeof(struct PseudoHdr)); offset += sizeof(struct PseudoHdr); memcpy(buf + offset, hdrData, hdrBytes); offset += hdrBytes; memcpy(buf + offset, msgData, msgBytes); *buffer = (uint16_t*) buf; return bufSize; }
the_stack_data/92325680.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> int retorno = 0; int main() { int p, status; char usr[80]; char passwd[80]; while (!retorno) { printf("User: "); scanf("%s", usr); printf("Password: "); scanf("%s", passwd); if (1) // Si el usuario y contraseña son correctos { p = fork(); if (p == 0) { execlp("./sh", "./sh", NULL); } else { waitpid(p, &status, WUNTRACED); if (WIFEXITED(status)) { printf("exited, status=%d\n", WEXITSTATUS(status)); if (WEXITSTATUS(status) == 1) { kill(getppid(), SIGUSR2); } } } } else { fprintf(stderr, "Wrong user/password\n"); } } return retorno; }
the_stack_data/234517535.c
// RUN: %clang_cc1 -analyze -analyzer-checker=core,osx.cocoa.RetainCount -analyzer-store=region -analyzer-constraints=basic -verify %s // RUN: %clang_cc1 -analyze -analyzer-checker=core,osx.cocoa.RetainCount -analyzer-store=region -analyzer-constraints=range -verify %s typedef struct CGColorSpace *CGColorSpaceRef; extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void); extern CGColorSpaceRef CGColorSpaceRetain(CGColorSpaceRef space); extern void CGColorSpaceRelease(CGColorSpaceRef space); void f() { CGColorSpaceRef X = CGColorSpaceCreateDeviceRGB(); // expected-warning{{leak}} CGColorSpaceRetain(X); } void fb() { CGColorSpaceRef X = CGColorSpaceCreateDeviceRGB(); CGColorSpaceRetain(X); CGColorSpaceRelease(X); CGColorSpaceRelease(X); // no-warning }
the_stack_data/249383.c
int add(int a, int b) { return a + b; }
the_stack_data/145452447.c
/* * In EiC, string literals are shared. */ #include <assert.h> #include <string.h> char *a[] = { "hello", "world",}; char *b[] = { "hello", "world",}; char *c[] = { "hello", "world",}; char *d[] = { "hello", "world",}; char *e[] = { "hello", "world",}; void T1() { assert(a != b); assert(a != c); assert(a != d); assert(a != e); assert(a[0] == b[0]); assert(a[0] == c[0]); assert(a[0] == d[0]); assert(a[0] == e[0]); assert(a[1] == b[1]); assert(a[1] == c[1]); assert(a[1] == d[1]); assert(a[1] == e[1]); } void T2() { assert(strcmp("hello",a[0]) == 0); assert(strcmp("hello",b[0]) == 0); assert(strcmp("hello",c[0]) == 0); assert(strcmp("hello",d[0]) == 0); assert(strcmp("hello",e[0]) == 0); assert(strcmp("world",a[1]) == 0); assert(strcmp("world",b[1]) == 0); assert(strcmp("world",c[1]) == 0); assert(strcmp("world",d[1]) == 0); assert(strcmp("world",e[1]) == 0); } int main() { T1(); T2(); return 0; } #ifdef EiCTeStS main(); #endif
the_stack_data/190769136.c
#include <stdio.h> #include <stdlib.h> /** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ char** fizzBuzz(int n, int* returnSize) { char** ret = (char **)malloc(sizeof(char *) * n); for(int i = 0; i < n; i++) { ret[i] = (char *)malloc(sizeof(char) * 10); } for(int i = 0; i < n; i++) { if((i+1) % 15 == 0) { *(ret+i) = "FizzBuzz"; } else if((i+1) % 3 == 0) { *(ret+i) = "Fizz"; } else if((i+1) % 5 == 0) { *(ret+i) = "Buzz"; } else { sprintf(*(ret+i), "%d", i+1); } } *returnSize = n; return ret; } void main() { int input = 15; int* size = (int *)malloc(sizeof(int)); char** ret = fizzBuzz(input, size); printf("Return: \n[\n"); for(int i = 0; i < *size; i++) { printf(" \"%s\"\n", *(ret+i)); } printf("]\n"); printf("the output array size is: %d\n", *size); }
the_stack_data/92324508.c
/* ************************************************************************* * Ralink Tech Inc. * 5F., No.36, Taiyuan St., Jhubei City, * Hsinchu County 302, * Taiwan, R.O.C. * * (c) Copyright 2002-2010, Ralink Technology, Inc. * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * *************************************************************************/ #ifdef RT33xx #ifndef RTMP_RF_RW_SUPPORT #error "You Should Enable compile flag RTMP_RF_RW_SUPPORT for this chip" #endif /* RTMP_RF_RW_SUPPORT */ #include "rt_config.h" /* RF register initialization set*/ #ifdef RT3370 REG_PAIR RT3370_RFRegTable[] = { {RF_R00, 0xA0}, {RF_R01, 0xF1}, {RF_R02, 0xF1}, {RF_R03, 0x32}, {RF_R04, 0x41}, {RF_R05, 0x8F}, {RF_R06, 0x4A}, {RF_R07, 0xE0}, {RF_R08, 0x4B}, /* Read only*/ {RF_R09, 0x81}, {RF_R10, 0x71}, /* Default value changed from 0x41 to 0x71*/ {RF_R11, 0x11}, {RF_R12, 0x28}, {RF_R13, 0xE0}, {RF_R14, 0x90}, {RF_R15, 0x73}, {RF_R16, 0x44}, {RF_R17, 0x93}, {RF_R18, 0x5C}, {RF_R19, 0x84}, /* Default value changed from 0x82 to 0x84*/ {RF_R20, 0xB2}, {RF_R21, 0xE7}, {RF_R22, 0x04}, {RF_R23, 0x26}, {RF_R24, BW20RFR24}, {RF_R25, 0x23}, {RF_R26, 0x85}, {RF_R27, 0x02}, {RF_R28, 0x60}, {RF_R29, 0x90}, {RF_R30, 0x29}, {RF_R31, BW20RFR31}, }; UCHAR RT3370_NUM_RF_REG_PARMS = (sizeof(RT3370_RFRegTable) / sizeof(REG_PAIR)); #endif /* RT3370 */ #ifdef RTMP_INTERNAL_TX_ALC /* The Tx power tuning entry */ TX_POWER_TUNING_ENTRY_STRUCT RT33xx_TxPowerTuningTable[] = { /* idxTxPowerTable Tx power control over RF Tx power control over MAC */ /* (zero-based array) { RF R12[4:0]: Tx0 ALC}, {MAC 0x1314~0x1324} */ /* 0 */ {0x00, -15}, /* 1 */ {0x01, -15}, /* 2 */ {0x00, -14}, /* 3 */ {0x01, -14}, /* 4 */ {0x00, -13}, /* 5 */ {0x01, -13}, /* 6 */ {0x00, -12}, /* 7 */ {0x01, -12}, /* 8 */ {0x00, -11}, /* 9 */ {0x01, -11}, /* 10 */ {0x00, -10}, /* 11 */ {0x01, -10}, /* 12 */ {0x00, -9}, /* 13 */ {0x01, -9}, /* 14 */ {0x00, -8}, /* 15 */ {0x01, -8}, /* 16 */ {0x00, -7}, /* 17 */ {0x01, -7}, /* 18 */ {0x00, -6}, /* 19 */ {0x01, -6}, /* 20 */ {0x00, -5}, /* 21 */ {0x01, -5}, /* 22 */ {0x00, -4}, /* 23 */ {0x01, -4}, /* 24 */ {0x00, -3}, /* 25 */ {0x01, -3}, /* 26 */ {0x00, -2}, /* 27 */ {0x01, -2}, /* 28 */ {0x00, -1}, /* 29 */ {0x01, -1}, /* 30 */ {0x00, 0}, /* 31 */ {0x01, 0}, /* 32 */ {0x02, 0}, /* 33 */ {0x03, 0}, /* 34 */ {0x04, 0}, /* 35 */ {0x05, 0}, /* 36 */ {0x06, 0}, /* 37 */ {0x07, 0}, /* 38 */ {0x08, 0}, /* 39 */ {0x09, 0}, /* 40 */ {0x0A, 0}, /* 41 */ {0x0B, 0}, /* 42 */ {0x0C, 0}, /* 43 */ {0x0D, 0}, /* 44 */ {0x0E, 0}, /* 45 */ {0x0F, 0}, /* 46 */ {0x0F-1, 1}, /* 47 */ {0x0F, 1}, /* 48 */ {0x0F-1, 2}, /* 49 */ {0x0F, 2}, /* 50 */ {0x0F-1, 3}, /* 51 */ {0x0F, 3}, /* 52 */ {0x0F-1, 4}, /* 53 */ {0x0F, 4}, /* 54 */ {0x0F-1, 5}, /* 55 */ {0x0F, 5}, /* 56 */ {0x0F-1, 6}, /* 57 */ {0x0F, 6}, /* 58 */ {0x0F-1, 7}, /* 59 */ {0x0F, 7}, /* 60 */ {0x0F-1, 8}, /* 61 */ {0x0F, 8}, /* 62 */ {0x0F-1, 9}, /* 63 */ {0x0F, 9}, /* 64 */ {0x0F-1, 10}, /* 65 */ {0x0F, 10}, /* 66 */ {0x0F-1, 11}, /* 67 */ {0x0F, 11}, /* 68 */ {0x0F-1, 12}, /* 69 */ {0x0F, 12}, /* 70 */ {0x0F-1, 13}, /* 71 */ {0x0F, 13}, /* 72 */ {0x0F-1, 14}, /* 73 */ {0x0F, 14}, /* 74 */ {0x0F-1, 15}, /* 75 */ {0x0F, 15}, }; /* The desired TSSI over CCK */ CHAR desiredTSSIOverCCK[4] = {0}; /* The desired TSSI over OFDM */ CHAR desiredTSSIOverOFDM[8] = {0}; /* The desired TSSI over HT */ CHAR desiredTSSIOverHT[8] = {0}; /* The desired TSSI over HT using STBC */ CHAR desiredTSSIOverHTUsingSTBC[8] = {0}; #endif /* RTMP_INTERNAL_TX_ALC */ /* ======================================================================== Routine Description: Initialize RT35xx. Arguments: pAd - WLAN control block pointer Return Value: None Note: ======================================================================== */ VOID RT33xx_Init( IN PRTMP_ADAPTER pAd) { RTMP_CHIP_OP *pChipOps = &pAd->chipOps; RTMP_CHIP_CAP *pChipCap = &pAd->chipCap; /* init capability */ /* WARNING: Currently following table are shared by all RT30xx based IC, change it carefully when you add a new IC here. */ pChipCap->pRFRegTable = RT3020_RFRegTable; pChipCap->MaxNumOfBbpId = 185; /* init operator */ #ifdef RT3370 if (pAd->infType == RTMP_DEV_INF_USB) { pChipCap->pRFRegTable = RT3370_RFRegTable; pChipCap->pBBPRegTable = RT3370_BBPRegTable; pChipCap->bbpRegTbSize = RT3370_NUM_BBP_REG_PARMS; pChipOps->AsicRfInit = NICInitRT3370RFRegisters; } #endif /* RT3370 */ pChipOps->AsicHaltAction = RT33xxHaltAction; pChipOps->AsicRfTurnOff = RT33xxLoadRFSleepModeSetup; pChipOps->AsicReverseRfFromSleepMode = RT33xxReverseRFSleepModeSetup; pChipOps->ChipSwitchChannel = RT33xx_ChipSwitchChannel; pChipOps->AsicAdjustTxPower = AsicAdjustTxPower; pChipOps->ChipBBPAdjust = RT30xx_ChipBBPAdjust; pChipOps->ChipAGCInit = RT30xx_ChipAGCInit; /* 1T1R only */ pChipOps->SetRxAnt = RT33xxSetRxAnt; pAd->Mlme.bEnableAutoAntennaCheck = FALSE; pChipCap->FlgIsHwAntennaDiversitySup = FALSE; pChipOps->AsicGetTxPowerOffset = AsicGetTxPowerOffset; /*pChipOps->ChipResumeMsduTransmission = NULL; */ /*pChipOps->VdrTuning1 = NULL; */ pChipOps->RxSensitivityTuning = NULL; pChipCap->MaxNumOfBbpId = 185; pChipCap->TXWISize = 16; pChipCap->RXWISize = 16; #ifdef RTMP_INTERNAL_TX_ALC pChipCap->TxAlcTxPowerUpperBound_2G = 45; pChipCap->TxPowerTuningTable_2G = RT33xx_TxPowerTuningTable; pChipOps->InitDesiredTSSITable = RT33xx_InitDesiredTSSITable; pChipOps->AsicTxAlcGetAutoAgcOffset = RT33xx_AsicTxAlcGetAutoAgcOffset; #endif /* RTMP_INTERNAL_TX_ALC */ #ifdef RTMP_FREQ_CALIBRATION_SUPPORT #ifdef CONFIG_STA_SUPPORT pChipCap->FreqCalibrationSupport = TRUE; pChipCap->FreqCalInitMode = FREQ_CAL_INIT_MODE0; pChipCap->FreqCalMode = FREQ_CAL_MODE0; pChipCap->RxWIFrqOffset = RXWI_FRQ_OFFSET_FIELD1; #endif /* CONFIG_STA_SUPPORT */ #endif /* RTMP_FREQ_CALIBRATION_SUPPORT */ } /* Antenna divesity use GPIO3 and EESK pin for control*/ /* Antenna and EEPROM access are both using EESK pin,*/ /* Therefor we should avoid accessing EESK at the same time*/ /* Then restore antenna after EEPROM access*/ /* The original name of this function is AsicSetRxAnt(), now change to */ /*VOID AsicSetRxAnt(*/ VOID RT33xxSetRxAnt( IN PRTMP_ADAPTER pAd, IN UCHAR Ant) { UINT32 Value; UINT32 x; if (/*(!pAd->NicConfig2.field.AntDiversity) ||*/ (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF)) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))) { return; } /* the antenna selection is through firmware and MAC register(GPIO3)*/ if (IS_RT3390(pAd) && pAd->RfIcType == RFIC_3320) { if (Ant == 0) { /* Main antenna*/ /* E2PROM_CSR only in PCI bus Reg., USB Bus need MCU commad to control the EESK pin.*/ #ifdef RTMP_MAC_USB AsicSendCommandToMcu(pAd, 0x73, 0xff, 0x1, 0x0, FALSE); #endif /* RTMP_MAC_USB */ RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &Value); Value &= ~(0x0808); RTMP_IO_WRITE32(pAd, GPIO_CTRL_CFG, Value); DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicSetRxAnt, switch to main antenna\n")); } else { /* Aux antenna*/ /* E2PROM_CSR only in PCI bus Reg., USB Bus need MCU commad to control the EESK pin.*/ #ifdef RTMP_MAC_USB AsicSendCommandToMcu(pAd, 0x73, 0xff, 0x0, 0x0, FALSE); #endif /* RTMP_MAC_USB */ RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &Value); Value &= ~(0x0808); Value |= 0x08; RTMP_IO_WRITE32(pAd, GPIO_CTRL_CFG, Value); DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicSetRxAnt, switch to aux antenna\n")); } } } /* add by johnli, RF power sequence setup*/ /* ========================================================================== Description: Load RF normal operation-mode setup ========================================================================== */ VOID RT33xxLoadRFNormalModeSetup( IN PRTMP_ADAPTER pAd) { UCHAR RFValue = 0, bbpreg = 0 ; /* improve power consumption */ RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R138, &bbpreg); if (pAd->Antenna.field.TxPath == 1) { /* turn off tx DAC_1*/ bbpreg = (bbpreg | 0x20); } if (pAd->Antenna.field.RxPath == 1) { /* turn off tx ADC_1*/ bbpreg &= (~0x2); } RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R138, bbpreg); /* RX0_PD & TX0_PD, RF R1 register Bit 2 & Bit 3 to 0 and RF_BLOCK_en,RX1_PD & TX1_PD, Bit0, Bit 4 & Bit5 to 1*/ RT30xxReadRFRegister(pAd, RF_R01, &RFValue); RFValue = (RFValue & (~0x0C)) | 0x31; RT30xxWriteRFRegister(pAd, RF_R01, RFValue); /* TX_LO2_en, RF R15 register Bit 3 to 0*/ RT30xxReadRFRegister(pAd, RF_R15, &RFValue); RFValue &= (~0x08); RT30xxWriteRFRegister(pAd, RF_R15, RFValue); /* TX_LO1_en, RF R17 register Bit 3 to 0*/ RT30xxReadRFRegister(pAd, RF_R17, &RFValue); RFValue &= (~0x08); /* to fix rx long range issue*/ if (((pAd->MACVersion & 0xffff) >= 0x0211) && (pAd->NicConfig2.field.ExternalLNAForG == 0)) { RFValue |= 0x20; } /* set RF_R17_bit[2:0] equal to EEPROM setting at 0x48h*/ if (pAd->TxMixerGain24G >= 2) { RFValue &= (~0x7); /* clean bit [2:0]*/ RFValue |= pAd->TxMixerGain24G; } RT30xxWriteRFRegister(pAd, RF_R17, RFValue); /* RX_LO1_en, RF R20 register Bit 3 to 0*/ RT30xxReadRFRegister(pAd, RF_R20, &RFValue); RFValue &= (~0x08); RT30xxWriteRFRegister(pAd, RF_R20, RFValue); /* RX_LO2_en, RF R21 register Bit 3 to 0*/ RT30xxReadRFRegister(pAd, RF_R21, &RFValue); RFValue &= (~0x08); RT30xxWriteRFRegister(pAd, RF_R21, RFValue); } /* ========================================================================== Description: Load RF sleep-mode setup ========================================================================== */ VOID RT33xxLoadRFSleepModeSetup( IN PRTMP_ADAPTER pAd) { UCHAR RFValue; UINT32 MACValue; /* RF_BLOCK_en. RF R1 register Bit 0 to 0*/ RT30xxReadRFRegister(pAd, RF_R01, &RFValue); RFValue &= (~0x01); RT30xxWriteRFRegister(pAd, RF_R01, RFValue); /* VCO_IC, RF R7 register Bit 4 & Bit 5 to 0*/ RT30xxReadRFRegister(pAd, RF_R07, &RFValue); RFValue &= (~0x30); RT30xxWriteRFRegister(pAd, RF_R07, RFValue); /* RX_CTB_en, RF R21 register Bit 7 to 0*/ RT30xxReadRFRegister(pAd, RF_R21, &RFValue); RFValue &= (~0x80); RT30xxWriteRFRegister(pAd, RF_R21, RFValue); } /* ========================================================================== Description: Reverse RF sleep-mode setup ========================================================================== */ VOID RT33xxReverseRFSleepModeSetup( IN PRTMP_ADAPTER pAd, IN BOOLEAN FlgIsInitState) { UCHAR RFValue; UINT32 MACValue; /* RF_BLOCK_en, RF R1 register Bit 0 to 1*/ RT30xxReadRFRegister(pAd, RF_R01, &RFValue); RFValue |= 0x01; RT30xxWriteRFRegister(pAd, RF_R01, RFValue); /* VCO_IC, RF R7 register Bit 4 & Bit 5 to 1*/ RT30xxReadRFRegister(pAd, RF_R07, &RFValue); /* According to HK's comment for Max Input power issue. RF 07 must set to 0x60. */ RFValue |= 0x20; /* 0x30. */ RT30xxWriteRFRegister(pAd, RF_R07, RFValue); /* RX_CTB_en, RF R21 register Bit 7 to 1*/ RT30xxReadRFRegister(pAd, RF_R21, &RFValue); RFValue |= 0x80; RT30xxWriteRFRegister(pAd, RF_R21, RFValue); } /* end johnli*/ VOID RT33xxHaltAction( IN PRTMP_ADAPTER pAd) { UINT32 TxPinCfg = 0x00050F0F; /* Turn off LNA_PE or TRSW_POL*/ /* Fixed suspend leakage current*/ /* According to MAC 0x0580 bit [31], set MAC 0x1328 bit[18] during suspend mode.*/ /* If SEL_EFUSE=0, set TRSW_POL=0 in suspend mode.*/ /* If SEL_EFUSE=1, set TRSW_POL=1 in suspend mode.*/ if (IS_RT3390(pAd) #ifdef RTMP_EFUSE_SUPPORT && (pAd->bUseEfuse) #endif /* RTMP_EFUSE_SUPPORT */ ) { TxPinCfg &= 0xFFFBF0F0; /* bit18 off*/ } else { TxPinCfg &= 0xFFFFF0F0; } RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg); } VOID RT33xx_ChipSwitchChannel( IN PRTMP_ADAPTER pAd, IN UCHAR Channel, IN BOOLEAN bScan) { CHAR TxPwer = 0, TxPwer2 = DEFAULT_RF_TX_POWER; /*Bbp94 = BBPR94_DEFAULT, TxPwer2 = DEFAULT_RF_TX_POWER;*/ UCHAR index; UINT32 Value = 0; /*BbpReg, Value;*/ UCHAR RFValue; #ifdef DOT11N_SS3_SUPPORT CHAR TxPwer3 = 0; #endif /* DOT11N_SS3_SUPPORT */ #ifdef RT30xx UCHAR Tx0FinePowerCtrl = 0, Tx1FinePowerCtrl = 0; BBP_R109_STRUC BbpR109 = {{0}}; #endif /* RT30xx */ RFValue = 0; /* Search Tx power value*/ /* We can't use ChannelList to search channel, since some central channl's txpowr doesn't list in ChannelList, so use TxPower array instead. */ for (index = 0; index < MAX_NUM_OF_CHANNELS; index++) { if (Channel == pAd->TxPower[index].Channel) { TxPwer = pAd->TxPower[index].Power; TxPwer2 = pAd->TxPower[index].Power2; #ifdef RT30xx /*RT33xx*/ if (IS_RT3090A(pAd) || IS_RT3390(pAd)) /*(pAd->infType == RTMP_DEV_INF_PCI || pAd->infType == RTMP_DEV_INF_PCIE))*/ { Tx0FinePowerCtrl = pAd->TxPower[index].Tx0FinePowerCtrl; Tx1FinePowerCtrl = pAd->TxPower[index].Tx1FinePowerCtrl; } #endif /* RT30xx */ break; } } if (index == MAX_NUM_OF_CHANNELS) { DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: Can't find the Channel#%d \n", Channel)); } #ifdef RT30xx /* The RF programming sequence is difference between 3xxx and 2xxx*/ if ((IS_RT30xx(pAd)) && ((pAd->RfIcType == RFIC_3020) || (pAd->RfIcType == RFIC_2020) || (pAd->RfIcType == RFIC_3021) || (pAd->RfIcType == RFIC_3022) || (pAd->RfIcType == RFIC_3320))) { /* modify by WY for Read RF Reg. error */ UCHAR calRFValue; for (index = 0; index < NUM_OF_3020_CHNL; index++) { if (Channel == FreqItems3020[index].Channel) { /* Programming channel parameters*/ RT30xxWriteRFRegister(pAd, RF_R02, FreqItems3020[index].N); /* RT3370/RT3390 RF version is 0x3320 RF_R3 [7:4] is not reserved bits RF_R3[6:4] (pa1_bc_cck) : PA1 Bias CCK RF_R3[7] (pa2_cc_cck) : PA2 Cascode Bias CCK */ RT30xxReadRFRegister(pAd, RF_R03, (PUCHAR)(&RFValue)); RFValue = (RFValue & 0xF0) | (FreqItems3020[index].K & ~0xF0); /* <bit 3:0>:K<bit 3:0>*/ RT30xxWriteRFRegister(pAd, RF_R03, RFValue); RT30xxReadRFRegister(pAd, RF_R06, &RFValue); RFValue = (RFValue & 0xFC) | FreqItems3020[index].R; RT30xxWriteRFRegister(pAd, RF_R06, RFValue); /* Set Tx0 Power*/ RT30xxReadRFRegister(pAd, RF_R12, &RFValue); RFValue = (RFValue & 0xE0) | TxPwer; RT30xxWriteRFRegister(pAd, RF_R12, RFValue); /* Set Tx1 Power*/ RT30xxReadRFRegister(pAd, RF_R13, &RFValue); RFValue = (RFValue & 0xE0) | TxPwer2; RT30xxWriteRFRegister(pAd, RF_R13, RFValue); #ifdef RT33xx #endif /* RT33xx */ /* Tx/Rx Stream setting*/ RT30xxReadRFRegister(pAd, RF_R01, &RFValue); /*if (IS_RT3090(pAd))*/ /* RFValue |= 0x01; Enable RF block.*/ RFValue &= 0xC3; /*clear bit[7~2]*/ if (pAd->Antenna.field.TxPath == 1) RFValue |= 0x20; else if (pAd->Antenna.field.TxPath == 2) ; if (pAd->Antenna.field.RxPath == 1) RFValue |= 0x10; else if (pAd->Antenna.field.RxPath == 2) ; RT30xxWriteRFRegister(pAd, RF_R01, RFValue); /* Set RF offset*/ RT30xxReadRFRegister(pAd, RF_R23, &RFValue); RFValue = (RFValue & 0x80) | pAd->RfFreqOffset; RT30xxWriteRFRegister(pAd, RF_R23, RFValue); /* Set BW*/ if (!bScan && (pAd->CommonCfg.BBPCurrentBW == BW_40)) { calRFValue = pAd->Mlme.CaliBW40RfR24; /*DISABLE_11N_CHECK(pAd);*/ } else { calRFValue = pAd->Mlme.CaliBW20RfR24; } /* RT3370/RT3390 RF version is 0x3320 RF_R24 [7:6] is not reserved bits RF_R24[6] (BB_Rx1_out_en) : enable baseband output and ADC input RF_R24[7] (BB_Tx1_out_en) : enable DAC output or baseband input */ RT30xxReadRFRegister(pAd, RF_R24, (PUCHAR)(&RFValue)); calRFValue = (RFValue & 0xC0) | (calRFValue & ~0xC0); /* <bit 5>:tx_h20M<bit 5> and <bit 4:0>:tx_agc_fc<bit 4:0>*/ RT30xxWriteRFRegister(pAd, RF_R24, calRFValue); /* RT3370/RT3390 RF version is 0x3320 RF_R31 [7:6] is not reserved bits RF_R31[4:0] (rx_agc_fc) : capacitor control in baseband filter RF_R31[5] (rx_ h20M) : rx_ h20M: 0=10 MHz and 1=20MHz RF_R31[7:6] (drv_bc_cck) : Driver Bias CCK */ /* Set BW*/ if (IS_RT3390(pAd)) /* RT3390 has different AGC for Tx and Rx*/ { if (!bScan && (pAd->CommonCfg.BBPCurrentBW == BW_40)) { calRFValue = pAd->Mlme.CaliBW40RfR31; } else { calRFValue = pAd->Mlme.CaliBW20RfR31; } } RT30xxReadRFRegister(pAd, RF_R31, (PUCHAR)(&RFValue)); calRFValue = (RFValue & 0xC0) | (calRFValue & ~0xC0); /* <bit 5>:rx_h20M<bit 5> and <bit 4:0>:rx_agc_fc<bit 4:0> */ RT30xxWriteRFRegister(pAd, RF_R31, calRFValue); /* Enable RF tuning*/ RT30xxReadRFRegister(pAd, RF_R07, &RFValue); RFValue = RFValue | 0x1; RT30xxWriteRFRegister(pAd, RF_R07, RFValue); /* latch channel for future usage.*/ pAd->LatchRfRegs.Channel = Channel; DBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%d, Pwr1=%d, %dT), N=0x%02X, K=0x%02X, R=0x%02X\n", Channel, pAd->RfIcType, TxPwer, TxPwer2, pAd->Antenna.field.TxPath, FreqItems3020[index].N, FreqItems3020[index].K, FreqItems3020[index].R)); break; } } } #endif /* RT30xx */ /* Change BBP setting during siwtch from a->g, g->a*/ if (Channel <= 14) { ULONG TxPinCfg = 0x00050F0A;/*Gary 2007/08/09 0x050A0A*/ RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd))); RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd))); RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd))); RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0);/*(0x44 - GET_LNA_GAIN(pAd))); According the Rory's suggestion to solve the middle range issue.*/ /* Rx High power VGA offset for LNA select*/ if (pAd->NicConfig2.field.ExternalLNAForG) { RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62); RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x46); } else { RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x84); RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x50); } /* Turn off unused PA or LNA when only 1T or 1R*/ if (pAd->Antenna.field.TxPath == 1) { TxPinCfg &= 0xFFFFFFF3; } if (pAd->Antenna.field.RxPath == 1) { TxPinCfg &= 0xFFFFF3FF; } RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg); RtmpUpdateFilterCoefficientControl(pAd, Channel); } else { ULONG TxPinCfg = 0x00050F05;/*Gary 2007/8/9 0x050505*/ UINT8 bbpValue; RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd))); RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd))); RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd))); RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0);/*(0x44 - GET_LNA_GAIN(pAd))); According the Rory's suggestion to solve the middle range issue. */ /* Set the BBP_R82 value here */ bbpValue = 0xF2; RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, bbpValue); /* Rx High power VGA offset for LNA select*/ if (pAd->NicConfig2.field.ExternalLNAForA) { RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x46); } else { RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x50); } /* 5G band selection PIN, bit1 and bit2 are complement*/ RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value); Value &= (~0x6); Value |= (0x02); RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value); /* Turn off unused PA or LNA when only 1T or 1R*/ /* Turn off unused PA or LNA when only 1T or 1R*/ if (pAd->Antenna.field.TxPath == 1) { TxPinCfg &= 0xFFFFFFF3; } if (pAd->Antenna.field.RxPath == 1) { TxPinCfg &= 0xFFFFF3FF; } RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg); } /* GPIO control*/ /* R66 should be set according to Channel and use 20MHz when scanning*/ /*AsicBBPWriteWithRxChain(pAd, BBP_R66, (0x2E + GET_LNA_GAIN(pAd)), RX_CHAIN_ALL); */ if (bScan) RTMPSetAGCInitValue(pAd, BW_20); else RTMPSetAGCInitValue(pAd, pAd->CommonCfg.BBPCurrentBW); /* On 11A, We should delay and wait RF/BBP to be stable*/ /* and the appropriate time should be 1000 micro seconds */ /* 2005/06/05 - On 11G, We also need this delay time. Otherwise it's difficult to pass the WHQL.*/ RTMPusecDelay(1000); } #ifdef RTMP_INTERNAL_TX_ALC VOID RT33xx_InitDesiredTSSITable( IN PRTMP_ADAPTER pAd) { UCHAR TSSIBase = 0; /* The TSSI over OFDM 54Mbps */ USHORT TSSIStepOver2dot4G = 0; /* The TSSI value/step (0.5 dB/unit) */ UCHAR RFValue = 0; BBP_R49_STRUC BbpR49; ULONG i = 0; USHORT TxPower = 0, TxPowerOFDM54 = 0, temp = 0; BbpR49.byte = 0; if (pAd->TxPowerCtrl.bInternalTxALC == FALSE) { return; } DBGPRINT(RT_DEBUG_TRACE, ("---> %s\n", __FUNCTION__)); RT28xx_EEPROM_READ16(pAd, EEPROM_TSSI_OVER_OFDM_54, temp); TSSIBase = (temp & 0x001F); RT28xx_EEPROM_READ16(pAd, (EEPROM_TSSI_STEP_OVER_2DOT4G - 1), TSSIStepOver2dot4G); TSSIStepOver2dot4G = (0x000F & (TSSIStepOver2dot4G >> 8)); RT28xx_EEPROM_READ16(pAd, (EEPROM_OFDM_MCS6_MCS7 - 1), TxPowerOFDM54); TxPowerOFDM54 = (0x000F & (TxPowerOFDM54 >> 8)); DBGPRINT(RT_DEBUG_TRACE, ("%s: TSSIBase = %d, TSSIStepOver2dot4G = %d, TxPowerOFDM54 = %d\n", __FUNCTION__, TSSIBase, TSSIStepOver2dot4G, TxPowerOFDM54)); /* The desired TSSI over CCK */ RT28xx_EEPROM_READ16(pAd, EEPROM_CCK_MCS0_MCS1, TxPower); TxPower = (TxPower & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xDE = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverCCK[MCS_0] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2)) + 6); desiredTSSIOverCCK[MCS_1] = desiredTSSIOverCCK[MCS_0]; RT28xx_EEPROM_READ16(pAd, (EEPROM_CCK_MCS2_MCS3 - 1), TxPower); TxPower = ((TxPower >> 8) & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xDF = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverCCK[MCS_2] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2)) + 6); desiredTSSIOverCCK[MCS_3] = desiredTSSIOverCCK[MCS_2]; /* Boundary verification: the desired TSSI value */ for (i = 0; i < 4; i++) /* CCK: MCS 0 ~ MCS 3 */ { if (desiredTSSIOverCCK[i] < 0x00) { desiredTSSIOverCCK[i] = 0x00; } else if (desiredTSSIOverCCK[i] > 0x1F) { desiredTSSIOverCCK[i] = 0x1F; } } DBGPRINT(RT_DEBUG_TRACE, ("%s: desiredTSSIOverCCK[0] = %d, desiredTSSIOverCCK[1] = %d, desiredTSSIOverCCK[2] = %d, desiredTSSIOverCCK[3] = %d\n", __FUNCTION__, desiredTSSIOverCCK[0], desiredTSSIOverCCK[1], desiredTSSIOverCCK[2], desiredTSSIOverCCK[3])); /* The desired TSSI over OFDM */ RT28xx_EEPROM_READ16(pAd, EEPROM_OFDM_MCS0_MCS1, TxPower); TxPower = (TxPower & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xE0 = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverOFDM[MCS_0] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverOFDM[MCS_1] = desiredTSSIOverOFDM[MCS_0]; RT28xx_EEPROM_READ16(pAd, (EEPROM_OFDM_MCS2_MCS3 - 1), TxPower); TxPower = ((TxPower >> 8) & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xE1 = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverOFDM[MCS_2] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverOFDM[MCS_3] = desiredTSSIOverOFDM[MCS_2]; RT28xx_EEPROM_READ16(pAd, EEPROM_OFDM_MCS4_MCS5, TxPower); TxPower = (TxPower & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xE2 = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverOFDM[MCS_4] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverOFDM[MCS_5] = desiredTSSIOverOFDM[MCS_4]; desiredTSSIOverOFDM[MCS_6] = TSSIBase; desiredTSSIOverOFDM[MCS_7] = TSSIBase; /* Boundary verification: the desired TSSI value */ for (i = 0; i < 8; i++) /* OFDM: MCS 0 ~ MCS 7 */ { if (desiredTSSIOverOFDM[i] < 0x00) { desiredTSSIOverOFDM[i] = 0x00; } else if (desiredTSSIOverOFDM[i] > 0x1F) { desiredTSSIOverOFDM[i] = 0x1F; } } DBGPRINT(RT_DEBUG_TRACE, ("%s: desiredTSSIOverOFDM[0] = %d, desiredTSSIOverOFDM[1] = %d, desiredTSSIOverOFDM[2] = %d, desiredTSSIOverOFDM[3] = %d\n", __FUNCTION__, desiredTSSIOverOFDM[0], desiredTSSIOverOFDM[1], desiredTSSIOverOFDM[2], desiredTSSIOverOFDM[3])); DBGPRINT(RT_DEBUG_TRACE, ("%s: desiredTSSIOverOFDM[4] = %d, desiredTSSIOverOFDM[5] = %d, desiredTSSIOverOFDM[6] = %d, desiredTSSIOverOFDM[7] = %d\n", __FUNCTION__, desiredTSSIOverOFDM[4], desiredTSSIOverOFDM[5], desiredTSSIOverOFDM[6], desiredTSSIOverOFDM[7])); /* The desired TSSI over HT */ RT28xx_EEPROM_READ16(pAd, EEPROM_HT_MCS0_MCS1, TxPower); TxPower = (TxPower & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xE4 = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverHT[MCS_0] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverHT[MCS_1] = desiredTSSIOverHT[MCS_0]; RT28xx_EEPROM_READ16(pAd, (EEPROM_HT_MCS2_MCS3 - 1), TxPower); TxPower = ((TxPower >> 8) & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xE5 = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverHT[MCS_2] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverHT[MCS_3] = desiredTSSIOverHT[MCS_2]; RT28xx_EEPROM_READ16(pAd, EEPROM_HT_MCS4_MCS5, TxPower); TxPower = (TxPower & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xE6 = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverHT[MCS_4] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverHT[MCS_5] = desiredTSSIOverHT[MCS_4]; RT28xx_EEPROM_READ16(pAd, (EEPROM_HT_MCS6_MCS7 - 1), TxPower); TxPower = ((TxPower >> 8) & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xE7 = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverHT[MCS_6] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverHT[MCS_7] = desiredTSSIOverHT[MCS_6]; /* Boundary verification: the desired TSSI value */ for (i = 0; i < 8; i++) /* HT: MCS 0 ~ MCS 7 */ { if (desiredTSSIOverHT[i] < 0x00) { desiredTSSIOverHT[i] = 0x00; } else if (desiredTSSIOverHT[i] > 0x1F) { desiredTSSIOverHT[i] = 0x1F; } } DBGPRINT(RT_DEBUG_TRACE, ("%s: desiredTSSIOverHT[0] = %d, desiredTSSIOverHT[1] = %d, desiredTSSIOverHT[2] = %d, desiredTSSIOverHT[3] = %d\n", __FUNCTION__, desiredTSSIOverHT[0], desiredTSSIOverHT[1], desiredTSSIOverHT[2], desiredTSSIOverHT[3])); DBGPRINT(RT_DEBUG_TRACE, ("%s: desiredTSSIOverHT[4] = %d, desiredTSSIOverHT[5] = %d, desiredTSSIOverHT[6] = %d, desiredTSSIOverHT[7] = %d\n", __FUNCTION__, desiredTSSIOverHT[4], desiredTSSIOverHT[5], desiredTSSIOverHT[6], desiredTSSIOverHT[7])); /* The desired TSSI over HT using STBC */ RT28xx_EEPROM_READ16(pAd, EEPROM_HT_USING_STBC_MCS0_MCS1, TxPower); TxPower = (TxPower & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xEC = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverHTUsingSTBC[MCS_0] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverHTUsingSTBC[MCS_1] = desiredTSSIOverHTUsingSTBC[MCS_0]; RT28xx_EEPROM_READ16(pAd, (EEPROM_HT_USING_STBC_MCS2_MCS3 - 1), TxPower); TxPower = ((TxPower >> 8) & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xED = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverHTUsingSTBC[MCS_2] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverHTUsingSTBC[MCS_3] = desiredTSSIOverHTUsingSTBC[MCS_2]; RT28xx_EEPROM_READ16(pAd, EEPROM_HT_USING_STBC_MCS4_MCS5, TxPower); TxPower = (TxPower & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xEE = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverHTUsingSTBC[MCS_4] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverHTUsingSTBC[MCS_5] = desiredTSSIOverHTUsingSTBC[MCS_4]; RT28xx_EEPROM_READ16(pAd, (EEPROM_HT_USING_STBC_MCS6_MCS7 - 1), TxPower); TxPower = ((TxPower >> 8) & 0x000F); DBGPRINT(RT_DEBUG_TRACE, ("%s: 0xEF = 0x%X\n", __FUNCTION__, TxPower)); desiredTSSIOverHTUsingSTBC[MCS_6] = (TSSIBase + ((TxPower - TxPowerOFDM54) * (TSSIStepOver2dot4G * 2))); desiredTSSIOverHTUsingSTBC[MCS_7] = desiredTSSIOverHTUsingSTBC[MCS_6]; /* Boundary verification: the desired TSSI value */ for (i = 0; i < 8; i++) /* HT using STBC: MCS 0 ~ MCS 7 */ { if (desiredTSSIOverHTUsingSTBC[i] < 0x00) { desiredTSSIOverHTUsingSTBC[i] = 0x00; } else if (desiredTSSIOverHTUsingSTBC[i] > 0x1F) { desiredTSSIOverHTUsingSTBC[i] = 0x1F; } } DBGPRINT(RT_DEBUG_TRACE, ("%s: desiredTSSIOverHTUsingSTBC[0] = %d, desiredTSSIOverHTUsingSTBC[1] = %d, desiredTSSIOverHTUsingSTBC[2] = %d, desiredTSSIOverHTUsingSTBC[3] = %d\n", __FUNCTION__, desiredTSSIOverHTUsingSTBC[0], desiredTSSIOverHTUsingSTBC[1], desiredTSSIOverHTUsingSTBC[2], desiredTSSIOverHTUsingSTBC[3])); DBGPRINT(RT_DEBUG_TRACE, ("%s: desiredTSSIOverHTUsingSTBC[4] = %d, desiredTSSIOverHTUsingSTBC[5] = %d, desiredTSSIOverHTUsingSTBC[6] = %d, desiredTSSIOverHTUsingSTBC[7] = %d\n", __FUNCTION__, desiredTSSIOverHTUsingSTBC[4], desiredTSSIOverHTUsingSTBC[5], desiredTSSIOverHTUsingSTBC[6], desiredTSSIOverHTUsingSTBC[7])); RT30xxReadRFRegister(pAd, RF_R27, (PUCHAR)(&RFValue)); RFValue = (RFValue | 0x88); /* <7>: IF_Rxout_en, <3>: IF_Txout_en */ RT30xxWriteRFRegister(pAd, RF_R27, RFValue); RT30xxReadRFRegister(pAd, RF_R28, (PUCHAR)(&RFValue)); RFValue = (RFValue & (~0x60)); /* <6:5>: tssi_atten */ RT30xxWriteRFRegister(pAd, RF_R28, RFValue); RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R49, &BbpR49.byte); BbpR49.field.adc5_in_sel = 1; /* Enable the PSI (internal components, new version - RT3390) */ RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R49, BbpR49.byte); DBGPRINT(RT_DEBUG_TRACE, ("<--- %s\n", __FUNCTION__)); } /* ========================================================================== Description: Get the desired TSSI based on the latest packet Arguments: pAd Return Value: The desired TSSI ========================================================================== */ UCHAR RT33xx_GetDesiredTSSI( IN PRTMP_ADAPTER pAd) { PHTTRANSMIT_SETTING pLatestTxHTSetting = (PHTTRANSMIT_SETTING)(&pAd->LastTxRate); UCHAR desiredTSSI = 0; UCHAR MCS = 0; MCS = (UCHAR)(pLatestTxHTSetting->field.MCS); if (pLatestTxHTSetting->field.MODE == MODE_CCK) { if ((MCS < 0) || (MCS > 3)) /* boundary verification */ { DBGPRINT(RT_DEBUG_ERROR, ("%s: incorrect MCS: MCS = %d\n", __FUNCTION__, MCS)); MCS = 0; } desiredTSSI = desiredTSSIOverCCK[MCS]; } else if (pLatestTxHTSetting->field.MODE == MODE_OFDM) { if ((MCS < 0) || (MCS > 7)) /* boundary verification */ { DBGPRINT(RT_DEBUG_ERROR, ("%s: incorrect MCS: MCS = %d\n", __FUNCTION__, MCS)); MCS = 0; } desiredTSSI = desiredTSSIOverOFDM[MCS]; } else if ((pLatestTxHTSetting->field.MODE == MODE_HTMIX) || (pLatestTxHTSetting->field.MODE == MODE_HTGREENFIELD)) { if ((MCS < 0) || (MCS > 7)) /* boundary verification */ { DBGPRINT(RT_DEBUG_ERROR, ("%s: incorrect MCS: MCS = %d\n", __FUNCTION__, MCS)); MCS = 0; } if (pLatestTxHTSetting->field.STBC == 1) { desiredTSSI = desiredTSSIOverHT[MCS]; } else { desiredTSSI = desiredTSSIOverHTUsingSTBC[MCS]; } /* For HT BW40 MCS 7 with/without STBC configuration, the desired TSSI value should subtract one from the formula */ if ((pLatestTxHTSetting->field.BW == BW_40) && (MCS == MCS_7)) { desiredTSSI -= 1; } } DBGPRINT(RT_DEBUG_INFO, ("%s: desiredTSSI = %d, Latest Tx HT setting: MODE = %d, MCS = %d, STBC = %d\n", __FUNCTION__, desiredTSSI, pLatestTxHTSetting->field.MODE, pLatestTxHTSetting->field.MCS, pLatestTxHTSetting->field.STBC)); DBGPRINT(RT_DEBUG_INFO, ("<--- %s\n", __FUNCTION__)); return desiredTSSI; } VOID RT33xx_AsicTxAlcGetAutoAgcOffset( IN PRTMP_ADAPTER pAd, IN PCHAR pDeltaPwr, IN PCHAR pTotalDeltaPwr, IN PCHAR pAgcCompensate, IN PCHAR pDeltaPowerByBbpR1) { const TX_POWER_TUNING_ENTRY_STRUCT *TxPowerTuningTable = pAd->chipCap.TxPowerTuningTable_2G; PTX_POWER_TUNING_ENTRY_STRUCT pTxPowerTuningEntry = NULL; BBP_R49_STRUC BbpR49; UCHAR RFValue = 0; CHAR desiredTssi = 0; CHAR currentTssi = 0; CHAR TotalDeltaPower = 0; CHAR TuningTableIndex = 0; BbpR49.byte = 0; /* Locate the Internal Tx ALC tuning entry */ if ((pAd->TxPowerCtrl.bInternalTxALC == TRUE) && (IS_RT3390(pAd))) { if ((pAd->Mlme.OneSecPeriodicRound % 4 == 0) && (*pDeltaPowerByBbpR1 == 0)) { desiredTssi = RT33xx_GetDesiredTSSI(pAd); RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R49, &BbpR49.byte); currentTssi = BbpR49.field.TSSI; if (desiredTssi > currentTssi) { pAd->TxPowerCtrl.idxTxPowerTable++; } if (desiredTssi < currentTssi) { pAd->TxPowerCtrl.idxTxPowerTable--; } TuningTableIndex = pAd->TxPowerCtrl.idxTxPowerTable #ifdef DOT11_N_SUPPORT + pAd->TxPower[pAd->CommonCfg.CentralChannel-1].Power; #else + pAd->TxPower[pAd->CommonCfg.Channel-1].Power; #endif /* DOT11_N_SUPPORT */ if (TuningTableIndex < LOWERBOUND_TX_POWER_TUNING_ENTRY) { TuningTableIndex = LOWERBOUND_TX_POWER_TUNING_ENTRY; } if (TuningTableIndex > UPPERBOUND_TX_POWER_TUNING_ENTRY(pAd)) { TuningTableIndex = UPPERBOUND_TX_POWER_TUNING_ENTRY(pAd); } /* Valide pAd->TxPowerCtrl.idxTxPowerTable: -30 ~ 45 */ pTxPowerTuningEntry = &TxPowerTuningTable[TuningTableIndex + TX_POWER_TUNING_ENTRY_OFFSET]; pAd->TxPowerCtrl.RF_TX_ALC = pTxPowerTuningEntry->RF_TX_ALC; pAd->TxPowerCtrl.MAC_PowerDelta = pTxPowerTuningEntry->MAC_PowerDelta; /* Tx power adjustment over RF */ RT30xxReadRFRegister(pAd, RF_R12, (PUCHAR)(&RFValue)); RFValue = ((RFValue & 0xE0) | pAd->TxPowerCtrl.RF_TX_ALC); RT30xxWriteRFRegister(pAd, RF_R12, (UCHAR)(RFValue)); /* Tx power adjustment over MAC */ TotalDeltaPower += pAd->TxPowerCtrl.MAC_PowerDelta; DBGPRINT(RT_DEBUG_TRACE, ("%s: desiredTSSI = %d, currentTSSI = %d, idxTxPowerTable = %d, TuningTableIndex = %d, {RF_TX_ALC = %d, MAC_PowerDelta = %d}\n", __FUNCTION__, desiredTssi, currentTssi, pAd->TxPowerCtrl.idxTxPowerTable, TuningTableIndex, pTxPowerTuningEntry->RF_TX_ALC, pTxPowerTuningEntry->MAC_PowerDelta)); } else { /* Tx power adjustment over RF */ RT30xxReadRFRegister(pAd, RF_R12, (PUCHAR)(&RFValue)); RFValue = ((RFValue & 0xE0) | pAd->TxPowerCtrl.RF_TX_ALC); RT30xxWriteRFRegister(pAd, RF_R12, (UCHAR)(RFValue)); /* Tx power adjustment over MAC */ TotalDeltaPower += pAd->TxPowerCtrl.MAC_PowerDelta; } } *pTotalDeltaPwr = TotalDeltaPower; } #endif /* RTMP_INTERNAL_TX_ALC */ #endif /* RT33xx */
the_stack_data/148579235.c
#include <stdio.h> #include <stdlib.h> #include <math.h> /// @brief ATMEGA1284p UART baud rate caluculation tests // Usage: baudrate -f F_CPU -b baud // F_CPU = External CPU clock // Displays actual baud rate and register values int main(int argc, char *argv[]) { int i; long u2x, actual,fosc,baud; int foscf = 0; int baudf = 0; double div; long ubr_regi; char *ptr; for(i=1;i< argc;++i) { ptr = argv[i]; if(*ptr == '-') { ++ptr; if(*ptr == 'f') { ++ptr; if(*ptr || (ptr = argv[++i]) ) fosc = atol(ptr); foscf = 1; } if(*ptr == 'b') { ++ptr; if(*ptr || (ptr = argv[++i]) ) baud = atol(ptr); baudf = 1; } } } if(!foscf || !baudf) { printf("Usage: %s -f F_CPU -b baud\n", argv[0]); printf(" F_CPU = External CPU clock\n"); printf(" Displays actual baud rate and register values\n"); exit(1); } // Calculating Baud Rate // (U2X = 0) // BAUD = Fosc/(16*(UBRn+1)) // UBRn = Fosc/(16*Baud) -1 // (U2X = 1) // BAUD = Fosc/(8*(UBRn+1)) // UBRn = Fosc/(8*Baud) -1 ///@brief Use 8 prescale as a default u2x = 1; div = 8; ubr_regi = round( ((double)fosc/(div*(double)baud)) - 1.0 ); // For lower baud rates use 16 divider if the UBRR register overflows // URBRR register is only a 12 bit register! if(ubr_regi > 4095) { ///@brief Use 16 prescale f we have a low baud rate u2x = 0; div = 16.0; ubr_regi = round( ((double)fosc/(div*(double)baud)) - 1.0 ); } //overflow, baud rate was too low - so we clip to maximum allowed if(ubr_regi > 4095) ubr_regi = 4095; actual = ((double)fosc/(div*((double)(ubr_regi+1)))); printf("fosc = %ld, baud = %ld, actual = %ld, URBRR = %ld, U2X bit = %ld\n", fosc, baud, actual, ubr_regi, u2x); return(0); }
the_stack_data/162642839.c
#include <omp.h> #include <stddef.h> #include <stdlib.h> #define NMAX 10 struct node { int data; int procResult; struct node* next; }; // initialize the list (not shown) struct node* initList(struct node* p){}; // a long computation (not shown) int work(int data) {}; void procWork(struct node* p) { int n = p->data; p->procResult = work(n); } int main() { struct node* p = NULL; struct node* temp = NULL; struct node* head = NULL; struct node* parr; int i; p = initList(p); // save head of the list head = p; int count = 0; while (p != NULL) { p = p->next; count++; } parr = (struct node*)malloc(count * sizeof(struct node)); p = head; for (i = 0; i < count; i++) { parr[i] = *p; p = p->next; } #pragma omp parallel for schedule(static, 1) for (i = 0; i < count; i++) procWork(&parr[i]); }
the_stack_data/124839.c
/* Declarations for math functions. Copyright (C) 1991-1993,1995-1999,2001,2002 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* * ISO C99 Standard: 7.12 Mathematics <math.h> */ /* Copyright (C) 1991-1993,1995-2002, 2003 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* These are defined by the user (or the compiler) to specify the desired environment: __STRICT_ANSI__ ISO Standard C. _ISOC99_SOURCE Extensions to ISO C89 from ISO C99. _POSIX_SOURCE IEEE Std 1003.1. _POSIX_C_SOURCE If ==1, like _POSIX_SOURCE; if >=2 add IEEE Std 1003.2; if >=199309L, add IEEE Std 1003.1b-1993; if >=199506L, add IEEE Std 1003.1c-1995 _XOPEN_SOURCE Includes POSIX and XPG things. Set to 500 if Single Unix conformance is wanted, to 600 for the upcoming sixth revision. _XOPEN_SOURCE_EXTENDED XPG things and X/Open Unix extensions. _LARGEFILE_SOURCE Some more functions for correct standard I/O. _LARGEFILE64_SOURCE Additional functionality from LFS for large files. _FILE_OFFSET_BITS=N Select default filesystem interface. _BSD_SOURCE ISO C, POSIX, and 4.3BSD things. _SVID_SOURCE ISO C, POSIX, and SVID things. _GNU_SOURCE All of the above, plus GNU extensions. _REENTRANT Select additionally reentrant object. _THREAD_SAFE Same as _REENTRANT, often used by other systems. The `-ansi' switch to the GNU C compiler defines __STRICT_ANSI__. If none of these are defined, the default is to have _SVID_SOURCE, _BSD_SOURCE, and _POSIX_SOURCE set to one and _POSIX_C_SOURCE set to 199506L. If more than one of these are defined, they accumulate. For example __STRICT_ANSI__, _POSIX_SOURCE and _POSIX_C_SOURCE together give you ISO C, 1003.1, and 1003.2, but nothing else. These are defined by this file and are used by the header files to decide what to declare or define: __USE_ISOC99 Define ISO C99 things. __USE_POSIX Define IEEE Std 1003.1 things. __USE_POSIX2 Define IEEE Std 1003.2 things. __USE_POSIX199309 Define IEEE Std 1003.1, and .1b things. __USE_POSIX199506 Define IEEE Std 1003.1, .1b, .1c and .1i things. __USE_XOPEN Define XPG things. __USE_XOPEN_EXTENDED Define X/Open Unix things. __USE_UNIX98 Define Single Unix V2 things. __USE_XOPEN2K Define XPG6 things. __USE_LARGEFILE Define correct standard I/O things. __USE_LARGEFILE64 Define LFS things with separate names. __USE_FILE_OFFSET64 Define 64bit interface as default. __USE_BSD Define 4.3BSD things. __USE_SVID Define SVID things. __USE_MISC Define things common to BSD and System V Unix. __USE_GNU Define GNU extensions. __USE_REENTRANT Define reentrant/thread-safe *_r functions. __FAVOR_BSD Favor 4.3BSD things in cases of conflict. The macros `__GNU_LIBRARY__', `__GLIBC__', and `__GLIBC_MINOR__' are defined by this file unconditionally. `__GNU_LIBRARY__' is provided only for compatibility. All new code should use the other symbols to test for features. All macros listed above as possibly being defined by this file are explicitly undefined if they are not explicitly defined. Feature-test macros that are not defined by the user or compiler but are implied by the other feature-test macros defined (or by the lack of any definitions) are defined by the file. */ /* Undefine everything, so we get a clean slate. */ /* Suppress kernel-name space pollution unless user expressedly asks for it. */ /* Always use ISO C things. */ /* If _BSD_SOURCE was defined by the user, favor BSD over POSIX. */ /* If _GNU_SOURCE was defined by the user, turn on all the other features. */ /* If nothing (other than _GNU_SOURCE) is defined, define _BSD_SOURCE and _SVID_SOURCE. */ /* This is to enable the ISO C99 extension. Also recognize the old macro which was used prior to the standard acceptance. This macro will eventually go away and the features enabled by default once the ISO C99 standard is widely adopted. */ /* If none of the ANSI/POSIX macros are defined, use POSIX.1 and POSIX.2 (and IEEE Std 1003.1b-1993 unless _XOPEN_SOURCE is defined). */ /* We do support the IEC 559 math functionality, real and complex. */ /* wchar_t uses ISO 10646-1 (2nd ed., published 2000-09-15) / Unicode 3.1. */ /* This macro indicates that the installed library is the GNU C Library. For historic reasons the value now is 6 and this will stay from now on. The use of this variable is deprecated. Use __GLIBC__ and __GLIBC_MINOR__ now (see below) when you want to test for a specific GNU C library version and use the values in <gnu/lib-names.h> to get the sonames of the shared libraries. */ /* Major and minor version number of the GNU C library package. Use these macros to test for features in specific releases. */ /* Convenience macros to test the versions of glibc and gcc. Use them like this: #if __GNUC_PREREQ (2,8) ... code requiring gcc 2.8 or later ... #endif Note - they won't work for gcc1 or glibc1, since the _MINOR macros were not defined then. */ /* Decide whether a compiler supports the long long datatypes. */ /* This is here only because every header file already includes this one. */ /* Copyright (C) 1992-2001, 2002 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* We are almost always included from features.h. */ /* The GNU libc does not support any K&R compilers or the traditional mode of ISO C compilers anymore. Check for some of the combinations not anymore supported. */ /* Some user header file might have defined this before. */ /* For these things, GCC behaves the ANSI way normally, and the non-ANSI way under -traditional. */ /* This is not a typedef so `const __ptr_t' does the right thing. */ /* C++ needs to know that types and declarations are C, not C++. */ /* The standard library needs the functions from the ISO C90 standard in the std namespace. At the same time we want to be safe for future changes and we include the ISO C99 code in the non-standard namespace __c99. The C++ wrapper header take case of adding the definitions to the global namespace. */ /* For compatibility we do not add the declarations into any namespace. They will end up in the global namespace which is what old code expects. */ /* Support for bounded pointers. */ /* Support for flexible arrays. */ /* Some other non-C99 compiler. Approximate with [1]. */ /* __asm__ ("xyz") is used throughout the headers to rename functions at the assembly language level. This is wrapped by the __REDIRECT macro, in order to support compilers that can do this some other way. When compilers don't support asm-names at all, we have to do preprocessor tricks instead (which don't have exactly the right semantics, but it's the best we can do). Example: int __REDIRECT(setpgrp, (__pid_t pid, __pid_t pgrp), setpgid); */ /* GCC has various useful declarations that can be made with the `__attribute__' syntax. All of the ways we use this do fine if they are omitted for compilers that don't understand it. */ /* At some point during the gcc 2.96 development the `malloc' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ /* At some point during the gcc 2.96 development the `pure' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ /* At some point during the gcc 3.1 development the `used' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ /* gcc allows marking deprecated functions. */ /* At some point during the gcc 2.8 development the `format_arg' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. If several `format_arg' attributes are given for the same function, in gcc-3.0 and older, all but the last one are ignored. In newer gccs, all designated arguments are considered. */ /* At some point during the gcc 2.97 development the `strfmon' format attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ /* It is possible to compile containing GCC extensions even if GCC is run in pedantic mode if the uses are carefully marked using the `__extension__' keyword. But this is not generally available before version 2.8. */ /* __restrict is known in EGCS 1.2 and above. */ /* ISO C99 also allows to declare arrays as non-overlapping. The syntax is array_name[restrict] GCC 3.1 supports this. */ /* Some other non-C99 compiler. */ /* If we don't have __REDIRECT, prototypes will be missing if __USE_FILE_OFFSET64 but not __USE_LARGEFILE[64]. */ /* Decide whether we can define 'extern inline' functions in headers. */ /* This is here only because every header file already includes this one. Get the definitions of all the appropriate `__stub_FUNCTION' symbols. <gnu/stubs.h> contains `#define __stub_FUNCTION' when FUNCTION is a stub that will always return failure (and set errno to ENOSYS). */ /* This file is automatically generated. It defines a symbol `__stub_FUNCTION' for each function in the C library which is a stub, meaning it will fail every time called, usually setting errno to ENOSYS. */ /* Get machine-dependent HUGE_VAL value (returned on overflow). On all IEEE754 machines, this is +Infinity. */ /* `HUGE_VAL' constants for ix86 (where it is infinity). Used by <stdlib.h> and <math.h> functions for overflow. Copyright (C) 1992, 1995, 1996, 1997, 1999, 2000 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* Copyright (C) 1991-1993,1995-2002, 2003 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* IEEE positive infinity (-HUGE_VAL is negative infinity). */ static union { unsigned char __c[8]; double __d; } __huge_val = { { 0, 0, 0, 0, 0, 0, 0xf0, 0x7f } }; /* ISO C99 extensions: (float) HUGE_VALF and (long double) HUGE_VALL. */ /* Get machine-dependent NAN value (returned for some domain errors). */ /* Get general and ISO C99 specific information. */ /* Copyright (C) 1997, 1998, 1999, 2000 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* The file <bits/mathcalls.h> contains the prototypes for all the actual math functions. These macros are used for those prototypes, so we can easily declare each function as both `name' and `__name', and can declare the float versions `namef' and `__namef'. */ /* Prototype declarations for math functions; helper file for <math.h>. Copyright (C) 1996-2002, 2003 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* NOTE: Because of the special way this file is used by <math.h>, this file must NOT be protected from multiple inclusion as header files usually are. This file provides prototype declarations for the math functions. Most functions are declared using the macro: __MATHCALL (NAME,[_r], (ARGS...)); This means there is a function `NAME' returning `double' and a function `NAMEf' returning `float'. Each place `_Mdouble_' appears in the prototype, that is actually `double' in the prototype for `NAME' and `float' in the prototype for `NAMEf'. Reentrant variant functions are called `NAME_r' and `NAMEf_r'. Functions returning other types like `int' are declared using the macro: __MATHDECL (TYPE, NAME,[_r], (ARGS...)); This is just like __MATHCALL but for a function returning `TYPE' instead of `_Mdouble_'. In all of these cases, there is still both a `NAME' and a `NAMEf' that takes `float' arguments. Note that there must be no whitespace before the argument passed for NAME, to make token pasting work with -traditional. */ /* Trigonometric functions. */ /* Arc cosine of X. */ extern double acos (double __x) ; extern double __acos (double __x) ; /* Arc sine of X. */ extern double asin (double __x) ; extern double __asin (double __x) ; /* Arc tangent of X. */ extern double atan (double __x) ; extern double __atan (double __x) ; /* Arc tangent of Y/X. */ extern double atan2 (double __y, double __x) ; extern double __atan2 (double __y, double __x) ; /* Cosine of X. */ extern double cos (double __x) ; extern double __cos (double __x) ; /* Sine of X. */ extern double sin (double __x) ; extern double __sin (double __x) ; /* Tangent of X. */ extern double tan (double __x) ; extern double __tan (double __x) ; /* Hyperbolic functions. */ /* Hyperbolic cosine of X. */ extern double cosh (double __x) ; extern double __cosh (double __x) ; /* Hyperbolic sine of X. */ extern double sinh (double __x) ; extern double __sinh (double __x) ; /* Hyperbolic tangent of X. */ extern double tanh (double __x) ; extern double __tanh (double __x) ; /* Hyperbolic arc cosine of X. */ extern double acosh (double __x) ; extern double __acosh (double __x) ; /* Hyperbolic arc sine of X. */ extern double asinh (double __x) ; extern double __asinh (double __x) ; /* Hyperbolic arc tangent of X. */ extern double atanh (double __x) ; extern double __atanh (double __x) ; /* Exponential and logarithmic functions. */ /* Exponential function of X. */ extern double exp (double __x) ; extern double __exp (double __x) ; /* Break VALUE into a normalized fraction and an integral power of 2. */ extern double frexp (double __x, int *__exponent) ; extern double __frexp (double __x, int *__exponent) ; /* X times (two to the EXP power). */ extern double ldexp (double __x, int __exponent) ; extern double __ldexp (double __x, int __exponent) ; /* Natural logarithm of X. */ extern double log (double __x) ; extern double __log (double __x) ; /* Base-ten logarithm of X. */ extern double log10 (double __x) ; extern double __log10 (double __x) ; /* Break VALUE into integral and fractional parts. */ extern double modf (double __x, double *__iptr) ; extern double __modf (double __x, double *__iptr) ; /* Return exp(X) - 1. */ extern double expm1 (double __x) ; extern double __expm1 (double __x) ; /* Return log(1 + X). */ extern double log1p (double __x) ; extern double __log1p (double __x) ; /* Return the base 2 signed integral exponent of X. */ extern double logb (double __x) ; extern double __logb (double __x) ; /* Power functions. */ /* Return X to the Y power. */ extern double pow (double __x, double __y) ; extern double __pow (double __x, double __y) ; /* Return the square root of X. */ extern double sqrt (double __x) ; extern double __sqrt (double __x) ; /* Return `sqrt(X*X + Y*Y)'. */ extern double hypot (double __x, double __y) ; extern double __hypot (double __x, double __y) ; /* Return the cube root of X. */ extern double cbrt (double __x) ; extern double __cbrt (double __x) ; /* Nearest integer, absolute value, and remainder functions. */ /* Smallest integral value not less than X. */ extern double ceil (double __x) ; extern double __ceil (double __x) ; /* Absolute value of X. */ extern double fabs (double __x) ; extern double __fabs (double __x) ; /* Largest integer not greater than X. */ extern double floor (double __x) ; extern double __floor (double __x) ; /* Floating-point modulo remainder of X/Y. */ extern double fmod (double __x, double __y) ; extern double __fmod (double __x, double __y) ; /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int __isinf (double __value) ; /* Return nonzero if VALUE is finite and not NaN. */ extern int __finite (double __value) ; /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int isinf (double __value) ; /* Return nonzero if VALUE is finite and not NaN. */ extern int finite (double __value) ; /* Return the remainder of X/Y. */ extern double drem (double __x, double __y) ; extern double __drem (double __x, double __y) ; /* Return the fractional part of X after dividing out `ilogb (X)'. */ extern double significand (double __x) ; extern double __significand (double __x) ; /* Return X with its signed changed to Y's. */ extern double copysign (double __x, double __y) ; extern double __copysign (double __x, double __y) ; /* Return nonzero if VALUE is not a number. */ extern int __isnan (double __value) ; /* Return nonzero if VALUE is not a number. */ extern int isnan (double __value) ; /* Bessel functions. */ extern double j0 (double) ; extern double __j0 (double) ; extern double j1 (double) ; extern double __j1 (double) ; extern double jn (int, double) ; extern double __jn (int, double) ; extern double y0 (double) ; extern double __y0 (double) ; extern double y1 (double) ; extern double __y1 (double) ; extern double yn (int, double) ; extern double __yn (int, double) ; /* Error and gamma functions. */ extern double erf (double) ; extern double __erf (double) ; extern double erfc (double) ; extern double __erfc (double) ; extern double lgamma (double) ; extern double __lgamma (double) ; /* Obsolete alias for `lgamma'. */ extern double gamma (double) ; extern double __gamma (double) ; /* Reentrant version of lgamma. This function uses the global variable `signgam'. The reentrant version instead takes a pointer and stores the value through it. */ extern double lgamma_r (double, int *__signgamp) ; extern double __lgamma_r (double, int *__signgamp) ; /* Return the integer nearest X in the direction of the prevailing rounding mode. */ extern double rint (double __x) ; extern double __rint (double __x) ; /* Return X + epsilon if X < Y, X - epsilon if X > Y. */ extern double nextafter (double __x, double __y) ; extern double __nextafter (double __x, double __y) ; /* Return the remainder of integer divison X / Y with infinite precision. */ extern double remainder (double __x, double __y) ; extern double __remainder (double __x, double __y) ; /* Return X times (2 to the Nth power). */ extern double scalbn (double __x, int __n) ; extern double __scalbn (double __x, int __n) ; /* Return the binary exponent of X, which must be nonzero. */ extern int ilogb (double __x) ; extern int __ilogb (double __x) ; /* Include the file of declarations again, this time using `float' instead of `double' and appending f to each function name. */ /* Prototype declarations for math functions; helper file for <math.h>. Copyright (C) 1996-2002, 2003 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* NOTE: Because of the special way this file is used by <math.h>, this file must NOT be protected from multiple inclusion as header files usually are. This file provides prototype declarations for the math functions. Most functions are declared using the macro: __MATHCALL (NAME,[_r], (ARGS...)); This means there is a function `NAME' returning `double' and a function `NAMEf' returning `float'. Each place `_Mdouble_' appears in the prototype, that is actually `double' in the prototype for `NAME' and `float' in the prototype for `NAMEf'. Reentrant variant functions are called `NAME_r' and `NAMEf_r'. Functions returning other types like `int' are declared using the macro: __MATHDECL (TYPE, NAME,[_r], (ARGS...)); This is just like __MATHCALL but for a function returning `TYPE' instead of `_Mdouble_'. In all of these cases, there is still both a `NAME' and a `NAMEf' that takes `float' arguments. Note that there must be no whitespace before the argument passed for NAME, to make token pasting work with -traditional. */ /* Trigonometric functions. */ /* Arc cosine of X. */ extern float acosf (float __x) ; extern float __acosf (float __x) ; /* Arc sine of X. */ extern float asinf (float __x) ; extern float __asinf (float __x) ; /* Arc tangent of X. */ extern float atanf (float __x) ; extern float __atanf (float __x) ; /* Arc tangent of Y/X. */ extern float atan2f (float __y, float __x) ; extern float __atan2f (float __y, float __x) ; /* Cosine of X. */ extern float cosf (float __x) ; extern float __cosf (float __x) ; /* Sine of X. */ extern float sinf (float __x) ; extern float __sinf (float __x) ; /* Tangent of X. */ extern float tanf (float __x) ; extern float __tanf (float __x) ; /* Hyperbolic functions. */ /* Hyperbolic cosine of X. */ extern float coshf (float __x) ; extern float __coshf (float __x) ; /* Hyperbolic sine of X. */ extern float sinhf (float __x) ; extern float __sinhf (float __x) ; /* Hyperbolic tangent of X. */ extern float tanhf (float __x) ; extern float __tanhf (float __x) ; /* Hyperbolic arc cosine of X. */ extern float acoshf (float __x) ; extern float __acoshf (float __x) ; /* Hyperbolic arc sine of X. */ extern float asinhf (float __x) ; extern float __asinhf (float __x) ; /* Hyperbolic arc tangent of X. */ extern float atanhf (float __x) ; extern float __atanhf (float __x) ; /* Exponential and logarithmic functions. */ /* Exponential function of X. */ extern float expf (float __x) ; extern float __expf (float __x) ; /* Break VALUE into a normalized fraction and an integral power of 2. */ extern float frexpf (float __x, int *__exponent) ; extern float __frexpf (float __x, int *__exponent) ; /* X times (two to the EXP power). */ extern float ldexpf (float __x, int __exponent) ; extern float __ldexpf (float __x, int __exponent) ; /* Natural logarithm of X. */ extern float logf (float __x) ; extern float __logf (float __x) ; /* Base-ten logarithm of X. */ extern float log10f (float __x) ; extern float __log10f (float __x) ; /* Break VALUE into integral and fractional parts. */ extern float modff (float __x, float *__iptr) ; extern float __modff (float __x, float *__iptr) ; /* Return exp(X) - 1. */ extern float expm1f (float __x) ; extern float __expm1f (float __x) ; /* Return log(1 + X). */ extern float log1pf (float __x) ; extern float __log1pf (float __x) ; /* Return the base 2 signed integral exponent of X. */ extern float logbf (float __x) ; extern float __logbf (float __x) ; /* Power functions. */ /* Return X to the Y power. */ extern float powf (float __x, float __y) ; extern float __powf (float __x, float __y) ; /* Return the square root of X. */ extern float sqrtf (float __x) ; extern float __sqrtf (float __x) ; /* Return `sqrt(X*X + Y*Y)'. */ extern float hypotf (float __x, float __y) ; extern float __hypotf (float __x, float __y) ; /* Return the cube root of X. */ extern float cbrtf (float __x) ; extern float __cbrtf (float __x) ; /* Nearest integer, absolute value, and remainder functions. */ /* Smallest integral value not less than X. */ extern float ceilf (float __x) ; extern float __ceilf (float __x) ; /* Absolute value of X. */ extern float fabsf (float __x) ; extern float __fabsf (float __x) ; /* Largest integer not greater than X. */ extern float floorf (float __x) ; extern float __floorf (float __x) ; /* Floating-point modulo remainder of X/Y. */ extern float fmodf (float __x, float __y) ; extern float __fmodf (float __x, float __y) ; /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int __isinff (float __value) ; /* Return nonzero if VALUE is finite and not NaN. */ extern int __finitef (float __value) ; /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int isinff (float __value) ; /* Return nonzero if VALUE is finite and not NaN. */ extern int finitef (float __value) ; /* Return the remainder of X/Y. */ extern float dremf (float __x, float __y) ; extern float __dremf (float __x, float __y) ; /* Return the fractional part of X after dividing out `ilogb (X)'. */ extern float significandf (float __x) ; extern float __significandf (float __x) ; /* Return X with its signed changed to Y's. */ extern float copysignf (float __x, float __y) ; extern float __copysignf (float __x, float __y) ; /* Return nonzero if VALUE is not a number. */ extern int __isnanf (float __value) ; /* Return nonzero if VALUE is not a number. */ extern int isnanf (float __value) ; /* Bessel functions. */ extern float j0f (float) ; extern float __j0f (float) ; extern float j1f (float) ; extern float __j1f (float) ; extern float jnf (int, float) ; extern float __jnf (int, float) ; extern float y0f (float) ; extern float __y0f (float) ; extern float y1f (float) ; extern float __y1f (float) ; extern float ynf (int, float) ; extern float __ynf (int, float) ; /* Error and gamma functions. */ extern float erff (float) ; extern float __erff (float) ; extern float erfcf (float) ; extern float __erfcf (float) ; extern float lgammaf (float) ; extern float __lgammaf (float) ; /* Obsolete alias for `lgamma'. */ extern float gammaf (float) ; extern float __gammaf (float) ; /* Reentrant version of lgamma. This function uses the global variable `signgam'. The reentrant version instead takes a pointer and stores the value through it. */ extern float lgammaf_r (float, int *__signgamp) ; extern float __lgammaf_r (float, int *__signgamp) ; /* Return the integer nearest X in the direction of the prevailing rounding mode. */ extern float rintf (float __x) ; extern float __rintf (float __x) ; /* Return X + epsilon if X < Y, X - epsilon if X > Y. */ extern float nextafterf (float __x, float __y) ; extern float __nextafterf (float __x, float __y) ; /* Return the remainder of integer divison X / Y with infinite precision. */ extern float remainderf (float __x, float __y) ; extern float __remainderf (float __x, float __y) ; /* Return X times (2 to the Nth power). */ extern float scalbnf (float __x, int __n) ; extern float __scalbnf (float __x, int __n) ; /* Return the binary exponent of X, which must be nonzero. */ extern int ilogbf (float __x) ; extern int __ilogbf (float __x) ; /* Include the file of declarations again, this time using `long double' instead of `double' and appending l to each function name. */ /* Prototype declarations for math functions; helper file for <math.h>. Copyright (C) 1996-2002, 2003 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* NOTE: Because of the special way this file is used by <math.h>, this file must NOT be protected from multiple inclusion as header files usually are. This file provides prototype declarations for the math functions. Most functions are declared using the macro: __MATHCALL (NAME,[_r], (ARGS...)); This means there is a function `NAME' returning `double' and a function `NAMEf' returning `float'. Each place `_Mdouble_' appears in the prototype, that is actually `double' in the prototype for `NAME' and `float' in the prototype for `NAMEf'. Reentrant variant functions are called `NAME_r' and `NAMEf_r'. Functions returning other types like `int' are declared using the macro: __MATHDECL (TYPE, NAME,[_r], (ARGS...)); This is just like __MATHCALL but for a function returning `TYPE' instead of `_Mdouble_'. In all of these cases, there is still both a `NAME' and a `NAMEf' that takes `float' arguments. Note that there must be no whitespace before the argument passed for NAME, to make token pasting work with -traditional. */ /* Trigonometric functions. */ /* Arc cosine of X. */ extern long double acosl (long double __x) ; extern long double __acosl (long double __x) ; /* Arc sine of X. */ extern long double asinl (long double __x) ; extern long double __asinl (long double __x) ; /* Arc tangent of X. */ extern long double atanl (long double __x) ; extern long double __atanl (long double __x) ; /* Arc tangent of Y/X. */ extern long double atan2l (long double __y, long double __x) ; extern long double __atan2l (long double __y, long double __x) ; /* Cosine of X. */ extern long double cosl (long double __x) ; extern long double __cosl (long double __x) ; /* Sine of X. */ extern long double sinl (long double __x) ; extern long double __sinl (long double __x) ; /* Tangent of X. */ extern long double tanl (long double __x) ; extern long double __tanl (long double __x) ; /* Hyperbolic functions. */ /* Hyperbolic cosine of X. */ extern long double coshl (long double __x) ; extern long double __coshl (long double __x) ; /* Hyperbolic sine of X. */ extern long double sinhl (long double __x) ; extern long double __sinhl (long double __x) ; /* Hyperbolic tangent of X. */ extern long double tanhl (long double __x) ; extern long double __tanhl (long double __x) ; /* Hyperbolic arc cosine of X. */ extern long double acoshl (long double __x) ; extern long double __acoshl (long double __x) ; /* Hyperbolic arc sine of X. */ extern long double asinhl (long double __x) ; extern long double __asinhl (long double __x) ; /* Hyperbolic arc tangent of X. */ extern long double atanhl (long double __x) ; extern long double __atanhl (long double __x) ; /* Exponential and logarithmic functions. */ /* Exponential function of X. */ extern long double expl (long double __x) ; extern long double __expl (long double __x) ; /* Break VALUE into a normalized fraction and an integral power of 2. */ extern long double frexpl (long double __x, int *__exponent) ; extern long double __frexpl (long double __x, int *__exponent) ; /* X times (two to the EXP power). */ extern long double ldexpl (long double __x, int __exponent) ; extern long double __ldexpl (long double __x, int __exponent) ; /* Natural logarithm of X. */ extern long double logl (long double __x) ; extern long double __logl (long double __x) ; /* Base-ten logarithm of X. */ extern long double log10l (long double __x) ; extern long double __log10l (long double __x) ; /* Break VALUE into integral and fractional parts. */ extern long double modfl (long double __x, long double *__iptr) ; extern long double __modfl (long double __x, long double *__iptr) ; /* Return exp(X) - 1. */ extern long double expm1l (long double __x) ; extern long double __expm1l (long double __x) ; /* Return log(1 + X). */ extern long double log1pl (long double __x) ; extern long double __log1pl (long double __x) ; /* Return the base 2 signed integral exponent of X. */ extern long double logbl (long double __x) ; extern long double __logbl (long double __x) ; /* Power functions. */ /* Return X to the Y power. */ extern long double powl (long double __x, long double __y) ; extern long double __powl (long double __x, long double __y) ; /* Return the square root of X. */ extern long double sqrtl (long double __x) ; extern long double __sqrtl (long double __x) ; /* Return `sqrt(X*X + Y*Y)'. */ extern long double hypotl (long double __x, long double __y) ; extern long double __hypotl (long double __x, long double __y) ; /* Return the cube root of X. */ extern long double cbrtl (long double __x) ; extern long double __cbrtl (long double __x) ; /* Nearest integer, absolute value, and remainder functions. */ /* Smallest integral value not less than X. */ extern long double ceill (long double __x) ; extern long double __ceill (long double __x) ; /* Absolute value of X. */ extern long double fabsl (long double __x) ; extern long double __fabsl (long double __x) ; /* Largest integer not greater than X. */ extern long double floorl (long double __x) ; extern long double __floorl (long double __x) ; /* Floating-point modulo remainder of X/Y. */ extern long double fmodl (long double __x, long double __y) ; extern long double __fmodl (long double __x, long double __y) ; /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int __isinfl (long double __value) ; /* Return nonzero if VALUE is finite and not NaN. */ extern int __finitel (long double __value) ; /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int isinfl (long double __value) ; /* Return nonzero if VALUE is finite and not NaN. */ extern int finitel (long double __value) ; /* Return the remainder of X/Y. */ extern long double dreml (long double __x, long double __y) ; extern long double __dreml (long double __x, long double __y) ; /* Return the fractional part of X after dividing out `ilogb (X)'. */ extern long double significandl (long double __x) ; extern long double __significandl (long double __x) ; /* Return X with its signed changed to Y's. */ extern long double copysignl (long double __x, long double __y) ; extern long double __copysignl (long double __x, long double __y) ; /* Return nonzero if VALUE is not a number. */ extern int __isnanl (long double __value) ; /* Return nonzero if VALUE is not a number. */ extern int isnanl (long double __value) ; /* Bessel functions. */ extern long double j0l (long double) ; extern long double __j0l (long double) ; extern long double j1l (long double) ; extern long double __j1l (long double) ; extern long double jnl (int, long double) ; extern long double __jnl (int, long double) ; extern long double y0l (long double) ; extern long double __y0l (long double) ; extern long double y1l (long double) ; extern long double __y1l (long double) ; extern long double ynl (int, long double) ; extern long double __ynl (int, long double) ; /* Error and gamma functions. */ extern long double erfl (long double) ; extern long double __erfl (long double) ; extern long double erfcl (long double) ; extern long double __erfcl (long double) ; extern long double lgammal (long double) ; extern long double __lgammal (long double) ; /* Obsolete alias for `lgamma'. */ extern long double gammal (long double) ; extern long double __gammal (long double) ; /* Reentrant version of lgamma. This function uses the global variable `signgam'. The reentrant version instead takes a pointer and stores the value through it. */ extern long double lgammal_r (long double, int *__signgamp) ; extern long double __lgammal_r (long double, int *__signgamp) ; /* Return the integer nearest X in the direction of the prevailing rounding mode. */ extern long double rintl (long double __x) ; extern long double __rintl (long double __x) ; /* Return X + epsilon if X < Y, X - epsilon if X > Y. */ extern long double nextafterl (long double __x, long double __y) ; extern long double __nextafterl (long double __x, long double __y) ; /* Return the remainder of integer divison X / Y with infinite precision. */ extern long double remainderl (long double __x, long double __y) ; extern long double __remainderl (long double __x, long double __y) ; /* Return X times (2 to the Nth power). */ extern long double scalbnl (long double __x, int __n) ; extern long double __scalbnl (long double __x, int __n) ; /* Return the binary exponent of X, which must be nonzero. */ extern int ilogbl (long double __x) ; extern int __ilogbl (long double __x) ; /* This variable is used by `gamma' and `lgamma'. */ extern int signgam; /* ISO C99 defines some generic macros which work on any data type. */ /* Support for various different standard error handling behaviors. */ typedef enum { _IEEE_ = -1, /* According to IEEE 754/IEEE 854. */ _SVID_, /* According to System V, release 4. */ _XOPEN_, /* Nowadays also Unix98. */ _POSIX_, _ISOC_ /* Actually this is ISO C99. */ } _LIB_VERSION_TYPE; /* This variable can be changed at run-time to any of the values above to affect floating point error handling behavior (it may also be necessary to change the hardware FPU exception settings). */ extern _LIB_VERSION_TYPE _LIB_VERSION; /* In SVID error handling, `matherr' is called with this description of the exceptional condition. We have a problem when using C++ since `exception' is a reserved name in C++. */ struct exception { int type; char *name; double arg1; double arg2; double retval; }; extern int matherr (struct exception *__exc); /* Types of exceptions in the `type' field. */ /* SVID mode specifies returning this large value instead of infinity. */ /* Some useful constants. */ /* The above constants are not adequate for computation using `long double's. Therefore we provide as an extension constants with similar names as a GNU extension. Provide enough digits for the 128-bit IEEE quad. */ /* When compiling in strict ISO C compatible mode we must not use the inline functions since they, among other things, do not set the `errno' variable correctly. */ /* Get machine-dependent inline versions (if there are any). */ float brent(ax,bx,cx,f,tol,xmin) float ax,bx,cx,tol,*xmin; float (*f)(); /* ANSI: float (*f)(float); */ { int iter; float a,b,d,etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm; float e=0.0; void nrerror(); a=((ax < cx) ? ax : cx); b=((ax > cx) ? ax : cx); x=w=v=bx; fw=fv=fx=(*f)(x); for (iter=1;iter<=100;iter++) { xm=0.5*(a+b); tol2=2.0*(tol1=tol*fabs(x)+1.0e-10); if (fabs(x-xm) <= (tol2-0.5*(b-a))) { *xmin=x; return fx; } if (fabs(e) > tol1) { r=(x-w)*(fx-fv); q=(x-v)*(fx-fw); p=(x-v)*q-(x-w)*r; q=2.0*(q-r); if (q > 0.0) p = -p; q=fabs(q); etemp=e; e=d; if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) d=0.3819660*(e=(x >= xm ? a-x : b-x)); else { d=p/q; u=x+d; if (u-a < tol2 || b-u < tol2) d=((xm-x) > 0.0 ? fabs(tol1) : -fabs(tol1)); } } else { d=0.3819660*(e=(x >= xm ? a-x : b-x)); } u=(fabs(d) >= tol1 ? x+d : x+((d) > 0.0 ? fabs(tol1) : -fabs(tol1))); fu=(*f)(u); if (fu <= fx) { if (u >= x) a=x; else b=x; (v)=(w);(w)=(x);(x)=(u); (fv)=(fw);(fw)=(fx);(fx)=(fu); } else { if (u < x) a=u; else b=u; if (fu <= fw || w == x) { v=w; w=u; fv=fw; fw=fu; } else if (fu <= fv || v == x || v == w) { v=u; fv=fu; } } } nrerror("Too many iterations in BRENT"); *xmin=x; return fx; }
the_stack_data/45442.c
#include <sys/time.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define N 10 int t0, t1; int getusec () { struct timeval tv; gettimeofday (&tv, 0); return tv.tv_sec * 1000000 + tv.tv_usec; } int main (int argc, char **argv) { int msec, i; if (argc != 2) { fprintf (stderr, "Usage:\n"); fprintf (stderr, " timerbench msec\n"); exit (1); } msec = strtol (argv[1], 0, 0); t0 = getusec (); for (i=0; i<N; i++) usleep (msec * 1000); t1 = getusec (); printf ("Measured interval is %.2f msec.\n", (t1 - t0) / 1000.0 / N); return 0; }
the_stack_data/73575919.c
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* builds a histogram of maximal runs */ void build(char* str, int* hist) { char ch = -1; while(*str) { /* capitalize just in case... */ if(toupper(*str) != ch) { ch = toupper(*str); hist[ch-'A']++; } ++str; } } /* comparison function for qsort */ int cmp(const void* a, const void* b) { return strcmp((char*)a, (char*)b); } int main() { int T, D, q, i, j, k, g, bad; int hist[1000+100][26]; char buf[1000][31], chk[100][101], print[1024*64], *temp; freopen("zombie.in","r",stdin); //open the input file; scanf("%d", &T); g = 0; while(T--) { memset(chk, 0, sizeof(chk)); memset(buf, 0, sizeof(buf)); memset(print, 0, sizeof(print)); memset(hist, 0, sizeof(hist)); temp = NULL; D = q = i = j = k = bad = 0; scanf("%d", &D); /* read & capitalize the dictionary */ for(i = 0; i < D; ++i) { scanf("%s", buf[i]); for(j = 0; j < strlen(buf[i]); ++j) { buf[i][j] = toupper(buf[i][j]); } } /* sort the words alphabetically */ qsort(buf, D, 31, cmp); /* construct a histogram for each word in the dictionary */ for(i = 0; i < D; ++i) { build(buf[i], hist[i]); } scanf("%d", &q); /* read & construct a histogram for each zombie word */ for(i = 0; i < q; ++i) { scanf("%s", chk[i]); build(chk[i], hist[i + 1000]); } printf("Scenario #%d:\n", ++g); /* for each zombie word attempt to match it with a dictionary word */ for(i = 0; i < q; ++i) { memset(print, 0, sizeof(print)); temp = print; for(j = 0; j < D; ++j) { bad = 0; for(k = 0; k < 26; ++k) { /* a word only matches if it has the same number of maximal runs */ if(hist[j][k] != hist[i+1000][k]) { bad = 1; } } if(!bad) { /* this is a possible match */ temp += sprintf(temp, "%s?\n", buf[j]); } } /* if the buffer ptr has changed then a match has been found */ if(print != temp) { printf("Did you mean:\n%s\n", print); } else { printf("No matches found.\n\n"); } } } }
the_stack_data/62304.c
// recursive sum of digits(int initial, int sum) //mod by 10 to get the last digit, divide by 10 to shift the number. //1234 % 10 = 4 //1234 / 10 = 123 #include<stdio.h> int SumDigitsRec(int n, int sum) ; int main(void) { int num = 123, sum = 0 ; SumDigitsRec(num,sum); printf("This is the sum %d \n", sum) ; return ; } int SumDigitsRec(int n, int sum) { if(n == 0) { return sum; } sum += n % 10; return SumDigitsRec((n/10),sum); }
the_stack_data/223492.c
/* small demonstration machine - simulator */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <stdint.h> char *memory; int memoryImage = 0; int16_t lIByte = 0; int16_t rIByte = 1; union { int16_t word; char bytesInWord[2]; } instruction; char temp; char acc; int16_t arg; int running = 1; int jumped = 0; FILE *simlog; char out(int16_t arg); void in(int16_t arg, char acc); int main(int argc, char **argv){ memoryImage = open(argv[1], 0); if (memoryImage == -1){ perror(argv[1]); exit(1); } simlog = fopen("sim.log", "w"); memory = calloc(1, 4096); read(memoryImage, memory, 4096); while (running){ instruction.bytesInWord[1] = memory[lIByte]; instruction.bytesInWord[0] = memory[rIByte]; temp = instruction.bytesInWord[1] & 0xF0; arg = instruction.word & 0x0FFF; fprintf(simlog, "acc: %i ip: %x instruction: ", acc, lIByte); switch (temp){ case '\x00': fprintf(simlog, "nop\n"); break; case '\x10': fprintf(simlog, "adda 0x%x\n", arg); acc = acc + memory[arg]; break; case '\x20': fprintf(simlog, "addm 0x%x\n", arg); memory[arg] = acc + memory[arg]; break; case '\x30': fprintf(simlog, "suba 0x%x\n", arg); acc = acc - memory[arg]; break; case '\x40': fprintf(simlog, "subm 0x%x\n", arg); memory[arg] = memory[arg] - acc; break; case '\x50': fprintf(simlog, "cla\n"); acc = 0; break; case '\x60': fprintf(simlog, "clm 0x%x\n", arg); memory[arg] = 0; break; case '\x70': fprintf(simlog, "jmp 0x%x\n", arg); lIByte = arg; rIByte = arg + 1; jumped = 1; break; case '\x80': fprintf(simlog, "jin 0x%x\n", arg); if (acc < 0){ lIByte = arg; rIByte = arg + 1; jumped = 1; } break; case '\x90': fprintf(simlog, "out 0x%x\n", arg); acc = out(arg); break; case '\xA0': fprintf(simlog, "in 0x%x\n", arg); in(arg, acc); break; case '\xB0': fprintf(simlog, "mova 0x%x\n", arg); acc = memory[arg]; break; case '\xC0': fprintf(simlog, "movm 0x%x\n", arg); memory[arg] = acc; break; case '\xD0': fprintf(simlog, "stoa 0x%x\n", arg); acc = (char)arg; break; case '\xE0': fprintf(simlog, "eq 0x%x\n", arg); if (acc == memory[arg]){ acc = -128; } else { acc = 0; } break; case '\xF0': fprintf(simlog, "hlt\n"); running = 0; break; default: fprintf(stderr, "%s: fatal: invalid instruction (this should not happen)\n", argv[0]); break; } if (!jumped){ rIByte++; rIByte++; lIByte++; lIByte++; } jumped = 0; } free(memory); return 0; } char out(int16_t arg){ if (arg == 0x0){ return getchar(); } return 0; } void in(int16_t arg, char acc){ if (arg == 0x0){ putchar(acc); } }
the_stack_data/154832058.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py // REQUIRES: powerpc-registered-target // RUN: %clang_cc1 -triple powerpc64-unknown-unknown \ // RUN: -emit-llvm %s -o - -target-cpu pwr8 | FileCheck %s // RUN: %clang_cc1 -triple powerpc64le-unknown-unknown \ // RUN: -emit-llvm %s -o - -target-cpu pwr8 | FileCheck %s // CHECK-LABEL: @test_builtin_ppc_compare_and_swap( // CHECK-NEXT: entry: // CHECK-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[B_ADDR:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[C_ADDR:%.*]] = alloca i32, align 4 // CHECK-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // CHECK-NEXT: store i32 [[B:%.*]], i32* [[B_ADDR]], align 4 // CHECK-NEXT: store i32 [[C:%.*]], i32* [[C_ADDR]], align 4 // CHECK-NEXT: [[TMP0:%.*]] = load i32, i32* [[C_ADDR]], align 4 // CHECK-NEXT: [[TMP1:%.*]] = load i32, i32* [[B_ADDR]], align 4 // CHECK-NEXT: [[TMP2:%.*]] = cmpxchg weak volatile i32* [[A_ADDR]], i32 [[TMP1]], i32 [[TMP0]] monotonic monotonic, align 4 // CHECK-NEXT: [[TMP3:%.*]] = extractvalue { i32, i1 } [[TMP2]], 0 // CHECK-NEXT: [[TMP4:%.*]] = extractvalue { i32, i1 } [[TMP2]], 1 // CHECK-NEXT: store i32 [[TMP3]], i32* [[B_ADDR]], align 4 // CHECK-NEXT: ret void // void test_builtin_ppc_compare_and_swap(int a, int b, int c) { __compare_and_swap(&a, &b, c); } // CHECK-LABEL: @test_builtin_ppc_compare_and_swaplp( // CHECK-NEXT: entry: // CHECK-NEXT: [[A_ADDR:%.*]] = alloca i64, align 8 // CHECK-NEXT: [[B_ADDR:%.*]] = alloca i64, align 8 // CHECK-NEXT: [[C_ADDR:%.*]] = alloca i64, align 8 // CHECK-NEXT: store i64 [[A:%.*]], i64* [[A_ADDR]], align 8 // CHECK-NEXT: store i64 [[B:%.*]], i64* [[B_ADDR]], align 8 // CHECK-NEXT: store i64 [[C:%.*]], i64* [[C_ADDR]], align 8 // CHECK-NEXT: [[TMP0:%.*]] = load i64, i64* [[C_ADDR]], align 8 // CHECK-NEXT: [[TMP1:%.*]] = load i64, i64* [[B_ADDR]], align 8 // CHECK-NEXT: [[TMP2:%.*]] = cmpxchg weak volatile i64* [[A_ADDR]], i64 [[TMP1]], i64 [[TMP0]] monotonic monotonic, align 8 // CHECK-NEXT: [[TMP3:%.*]] = extractvalue { i64, i1 } [[TMP2]], 0 // CHECK-NEXT: [[TMP4:%.*]] = extractvalue { i64, i1 } [[TMP2]], 1 // CHECK-NEXT: store i64 [[TMP3]], i64* [[B_ADDR]], align 8 // CHECK-NEXT: ret void // void test_builtin_ppc_compare_and_swaplp(long a, long b, long c) { __compare_and_swaplp(&a, &b, c); }
the_stack_data/82642.c
#include <regex.h> /* * Various messages and responses */ static const char CLIENT_ERR[] = "Client Error: "; static const int CLIENT_ERR_LEN = sizeof(CLIENT_ERR) - 1; static const char CMD_NOT_SUP[] = "Command not supported"; static const int CMD_NOT_SUP_LEN = sizeof(CMD_NOT_SUP) - 1; static const char BAD_ARGS[] = "Bad arguments"; static const int BAD_ARGS_LEN= sizeof(BAD_ARGS) - 1; static const char UNEXPECTED_ARGS[] = "Unexpected arguments"; static const int UNEXPECTED_ARGS_LEN = sizeof(UNEXPECTED_ARGS) - 1; static const char FILT_KEY_NEEDED[] = "Must provide filter name and key"; static const int FILT_KEY_NEEDED_LEN = sizeof(FILT_KEY_NEEDED) - 1; static const char FILT_NEEDED[] = "Must provide filter name"; static const int FILT_NEEDED_LEN = sizeof(FILT_NEEDED) - 1; static const char BAD_FILT_NAME[] = "Bad filter name"; static const int BAD_FILT_NAME_LEN = sizeof(BAD_FILT_NAME) - 1; static const char INTERNAL_ERR[] = "Internal Error\n"; static const int INTERNAL_ERR_LEN = sizeof(INTERNAL_ERR) - 1; static const char FILT_NOT_EXIST[] = "Filter does not exist\n"; static const int FILT_NOT_EXIST_LEN = sizeof(FILT_NOT_EXIST) - 1; static const char FILT_NOT_PROXIED[] = "Filter is not proxied. Close it first.\n"; static const int FILT_NOT_PROXIED_LEN = sizeof(FILT_NOT_PROXIED) - 1; static const char DELETE_IN_PROGRESS[] = "Delete in progress\n"; static const int DELETE_IN_PROGRESS_LEN = sizeof(DELETE_IN_PROGRESS) - 1; static const char DONE_RESP[] = "Done\n"; static const int DONE_RESP_LEN = sizeof(DONE_RESP) - 1; static const char EXISTS_RESP[] = "Exists\n"; static const int EXISTS_RESP_LEN = sizeof(EXISTS_RESP) - 1; static const char YES_SPACE[] = "Yes "; static const int YES_SPACE_LEN = sizeof(YES_SPACE) - 1; static const char NO_SPACE[] = "No "; static const int NO_SPACE_LEN = sizeof(NO_SPACE) - 1; static const char YES_RESP[] = "Yes\n"; static const int YES_RESP_LEN = sizeof(YES_RESP) - 1; static const char NO_RESP[] = "No\n"; static const int NO_RESP_LEN = sizeof(NO_RESP) - 1; static const char NEW_LINE[] = "\n"; static const int NEW_LINE_LEN = sizeof(NEW_LINE) - 1; static const char START_RESP[] = "START\n"; static const int START_RESP_LEN = sizeof(START_RESP) - 1; static const char END_RESP[] = "END\n"; static const int END_RESP_LEN = sizeof(END_RESP) - 1; typedef enum { UNKNOWN = 0, // Unrecognized command CHECK, // Check a single key CHECK_MULTI, // Check multiple space-seperated keys SET, // Set a single key SET_MULTI, // Set multiple space-seperated keys LIST, // List filters INFO, // Info about a fileter CREATE, // Creates a filter DROP, // Drop a filter CLOSE, // Close a filter CLEAR, // Clears a filter from the internals FLUSH, // Force flush a filter } conn_cmd_type; /* Static regexes */ static regex_t VALID_FILTER_NAMES_RE; static const char *VALID_FILTER_NAMES_PATTERN = "^[^ \t\n\r]{1,200}$";
the_stack_data/122016640.c
#include <unistd.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { printf("hello world (pid:%d)\n", (int) getpid()); int rc = fork(); if(rc < 0) { printf("fork failed\n"); } else if(rc == 0) { printf("hello, I am child (pid:%d)\n", (int) getpid()); } else { int wc = wait(NULL); printf("hello, I am parent of %d (wc:%d) (pid:%d)\n", rc, wc, (int) getpid()); } return 0; }
the_stack_data/115765262.c
/* SoLoud audio engine Copyright (c) 2013-2018 Jari Komppa This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #if defined(WITH_SDL2) #include <stdlib.h> #if defined(_MSC_VER) #define WINDOWS_VERSION #include <SDL.h> #else #include <SDL2/SDL.h> #endif #include <math.h> typedef Uint32 (*SDL2_WasInit_t)(Uint32 flags); typedef int (*SDL2_InitSubSystem_t)(Uint32 flags); typedef SDL_AudioDeviceID (*SDL2_OpenAudioDevice_t)(const char* device, int iscapture, const SDL_AudioSpec* desired, SDL_AudioSpec* obtained, int allowed_changes); typedef void (*SDL2_CloseAudioDevice_t)(SDL_AudioDeviceID dev); typedef void (*SDL2_PauseAudioDevice_t)(SDL_AudioDeviceID dev, int pause_on); static SDL2_WasInit_t SDL2_WasInit = NULL; static SDL2_InitSubSystem_t SDL2_InitSubSystem = NULL; static SDL2_OpenAudioDevice_t SDL2_OpenAudioDevice = NULL; static SDL2_CloseAudioDevice_t SDL2_CloseAudioDevice = NULL; static SDL2_PauseAudioDevice_t SDL2_PauseAudioDevice = NULL; #ifdef WINDOWS_VERSION #include <windows.h> static HMODULE sdl2_openDll() { HMODULE res = LoadLibraryA("SDL2.dll"); return res; } static void* sdl2_getDllProc(HMODULE aDllHandle, const char *aProcName) { return (void*)GetProcAddress(aDllHandle, (LPCSTR)aProcName); } #else #include <dlfcn.h> // dll functions static void * sdl2_openDll() { void * res; res = dlopen("/Library/Frameworks/SDL2.framework/SDL2", RTLD_LAZY); if (!res) res = dlopen("SDL2.so", RTLD_LAZY); if (!res) res = dlopen("libSDL2.so", RTLD_LAZY); return res; } static void* sdl2_getDllProc(void * aLibrary, const char *aProcName) { return dlsym(aLibrary, aProcName); } #endif static int sdl2_load_dll() { #ifdef WINDOWS_VERSION HMODULE dll = NULL; #else void * dll = NULL; #endif if (SDL2_OpenAudioDevice != NULL) { return 1; } dll = sdl2_openDll(); if (dll) { SDL2_WasInit = (SDL2_WasInit_t)sdl2_getDllProc(dll, "SDL_WasInit"); SDL2_InitSubSystem = (SDL2_InitSubSystem_t)sdl2_getDllProc(dll, "SDL_InitSubSystem"); SDL2_OpenAudioDevice = (SDL2_OpenAudioDevice_t)sdl2_getDllProc(dll, "SDL_OpenAudioDevice"); SDL2_CloseAudioDevice = (SDL2_CloseAudioDevice_t)sdl2_getDllProc(dll, "SDL_CloseAudioDevice"); SDL2_PauseAudioDevice = (SDL2_PauseAudioDevice_t)sdl2_getDllProc(dll, "SDL_PauseAudioDevice"); if (SDL2_WasInit && SDL2_InitSubSystem && SDL2_OpenAudioDevice && SDL2_CloseAudioDevice && SDL2_PauseAudioDevice) { return 1; } } SDL2_OpenAudioDevice = NULL; return 0; } int dll_SDL2_found() { return sdl2_load_dll(); } Uint32 dll_SDL2_WasInit(Uint32 flags) { if (SDL2_WasInit) return SDL2_WasInit(flags); return 0; } int dll_SDL2_InitSubSystem(Uint32 flags) { if (SDL2_InitSubSystem) return SDL2_InitSubSystem(flags); return -1; } SDL_AudioDeviceID dll_SDL2_OpenAudioDevice(const char* device, int iscapture, const SDL_AudioSpec* desired, SDL_AudioSpec* obtained, int allowed_changes) { if (SDL2_OpenAudioDevice) return SDL2_OpenAudioDevice(device, iscapture, desired, obtained, allowed_changes); return 0; } void dll_SDL2_CloseAudioDevice(SDL_AudioDeviceID dev) { if (SDL2_CloseAudioDevice) SDL2_CloseAudioDevice(dev); } void dll_SDL2_PauseAudioDevice(SDL_AudioDeviceID dev, int pause_on) { if (SDL2_PauseAudioDevice) SDL2_PauseAudioDevice(dev, pause_on); } #endif
the_stack_data/2409.c
#include <stdio.h> #include <math.h> #include <stdlib.h> int main(void) { long long ans = 0; long long num; for (int n = 1; n <= 1000; n++) { num = n; for (int m = 1; m < n; m++) { num = (num * n) % 10000000000; } ans += num; ans %= 10000000000; } printf("%010lld\n", ans); }
the_stack_data/192331855.c
/* Università di Bologna Corso di laurea in Informatica 11925 - Architettura degli elaboratori Stefano Volpe #969766 10/11/2020 0.c Scrivere un programma che prende da linea di comando il nome di 2 file di testo e copia il primo sul secondo (il secondo viene creato se non esiste) */ #include <stdio.h> int main(int argc, char **argv) { const int argc_min = 3; if (argc < argc_min) { fprintf(stderr, "Numero di parametri non sufficiente.\n"); return 1; } FILE *f1 = fopen(argv[1], "r"); if (!f1) { fprintf(stderr, "File '%s' non trovato.\n", argv[1]); return 2; } FILE *f2 = fopen(argv[2], "w"); if (!f2) { fprintf(stderr, "File '%s' non aperto.\n", argv[2]); return 3; } while(!feof(f1)) putc(fgetc(f1), f2); fclose(f1); fclose(f2); printf("'%s' copiato in '%s'.\n", argv[1], argv[2]); }
the_stack_data/70450021.c
#ifdef FLA_ENABLE_XBLAS /* ../netlib/sgerfsx.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "FLA_f2c.h" /* Table of constant values */ static integer c_n1 = -1; static integer c__0 = 0; static integer c__1 = 1; /* > \brief \b SGERFSX */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download SGERFSX + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/sgerfsx .f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/sgerfsx .f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/sgerfsx .f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE SGERFSX( TRANS, EQUED, N, NRHS, A, LDA, AF, LDAF, IPIV, */ /* R, C, B, LDB, X, LDX, RCOND, BERR, N_ERR_BNDS, */ /* ERR_BNDS_NORM, ERR_BNDS_COMP, NPARAMS, PARAMS, */ /* WORK, IWORK, INFO ) */ /* .. Scalar Arguments .. */ /* CHARACTER TRANS, EQUED */ /* INTEGER INFO, LDA, LDAF, LDB, LDX, N, NRHS, NPARAMS, */ /* $ N_ERR_BNDS */ /* REAL RCOND */ /* .. */ /* .. Array Arguments .. */ /* INTEGER IPIV( * ), IWORK( * ) */ /* REAL A( LDA, * ), AF( LDAF, * ), B( LDB, * ), */ /* $ X( LDX , * ), WORK( * ) */ /* REAL R( * ), C( * ), PARAMS( * ), BERR( * ), */ /* $ ERR_BNDS_NORM( NRHS, * ), */ /* $ ERR_BNDS_COMP( NRHS, * ) */ /* .. */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > SGERFSX improves the computed solution to a system of linear */ /* > equations and provides error bounds and backward error estimates */ /* > for the solution. In addition to normwise error bound, the code */ /* > provides maximum componentwise error bound if possible. See */ /* > comments for ERR_BNDS_NORM and ERR_BNDS_COMP for details of the */ /* > error bounds. */ /* > */ /* > The original system of linear equations may have been equilibrated */ /* > before calling this routine, as described by arguments EQUED, R */ /* > and C below. In this case, the solution and error bounds returned */ /* > are for the original unequilibrated system. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \verbatim */ /* > Some optional parameters are bundled in the PARAMS array. These */ /* > settings determine how refinement is performed, but often the */ /* > defaults are acceptable. If the defaults are acceptable, users */ /* > can pass NPARAMS = 0 which prevents the source code from accessing */ /* > the PARAMS argument. */ /* > \endverbatim */ /* > */ /* > \param[in] TRANS */ /* > \verbatim */ /* > TRANS is CHARACTER*1 */ /* > Specifies the form of the system of equations: */ /* > = 'N': A * X = B (No transpose) */ /* > = 'T': A**T * X = B (Transpose) */ /* > = 'C': A**H * X = B (Conjugate transpose = Transpose) */ /* > \endverbatim */ /* > */ /* > \param[in] EQUED */ /* > \verbatim */ /* > EQUED is CHARACTER*1 */ /* > Specifies the form of equilibration that was done to A */ /* > before calling this routine. This is needed to compute */ /* > the solution and error bounds correctly. */ /* > = 'N': No equilibration */ /* > = 'R': Row equilibration, i.e., A has been premultiplied by */ /* > diag(R). */ /* > = 'C': Column equilibration, i.e., A has been postmultiplied */ /* > by diag(C). */ /* > = 'B': Both row and column equilibration, i.e., A has been */ /* > replaced by diag(R) * A * diag(C). */ /* > The right hand side B has been changed accordingly. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] NRHS */ /* > \verbatim */ /* > NRHS is INTEGER */ /* > The number of right hand sides, i.e., the number of columns */ /* > of the matrices B and X. NRHS >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] A */ /* > \verbatim */ /* > A is REAL array, dimension (LDA,N) */ /* > The original N-by-N matrix A. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. LDA >= max(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in] AF */ /* > \verbatim */ /* > AF is REAL array, dimension (LDAF,N) */ /* > The factors L and U from the factorization A = P*L*U */ /* > as computed by SGETRF. */ /* > \endverbatim */ /* > */ /* > \param[in] LDAF */ /* > \verbatim */ /* > LDAF is INTEGER */ /* > The leading dimension of the array AF. LDAF >= max(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in] IPIV */ /* > \verbatim */ /* > IPIV is INTEGER array, dimension (N) */ /* > The pivot indices from SGETRF; for 1<=i<=N, row i of the */ /* > matrix was interchanged with row IPIV(i). */ /* > \endverbatim */ /* > */ /* > \param[in] R */ /* > \verbatim */ /* > R is REAL array, dimension (N) */ /* > The row scale factors for A. If EQUED = 'R' or 'B', A is */ /* > multiplied on the left by diag(R); if EQUED = 'N' or 'C', R */ /* > is not accessed. */ /* > If R is accessed, each element of R should be a power of the radix */ /* > to ensure a reliable solution and error estimates. Scaling by */ /* > powers of the radix does not cause rounding errors unless the */ /* > result underflows or overflows. Rounding errors during scaling */ /* > lead to refining with a matrix that is not equivalent to the */ /* > input matrix, producing error estimates that may not be */ /* > reliable. */ /* > \endverbatim */ /* > */ /* > \param[in] C */ /* > \verbatim */ /* > C is REAL array, dimension (N) */ /* > The column scale factors for A. If EQUED = 'C' or 'B', A is */ /* > multiplied on the right by diag(C); if EQUED = 'N' or 'R', C */ /* > is not accessed. */ /* > If C is accessed, each element of C should be a power of the radix */ /* > to ensure a reliable solution and error estimates. Scaling by */ /* > powers of the radix does not cause rounding errors unless the */ /* > result underflows or overflows. Rounding errors during scaling */ /* > lead to refining with a matrix that is not equivalent to the */ /* > input matrix, producing error estimates that may not be */ /* > reliable. */ /* > \endverbatim */ /* > */ /* > \param[in] B */ /* > \verbatim */ /* > B is REAL array, dimension (LDB,NRHS) */ /* > The right hand side matrix B. */ /* > \endverbatim */ /* > */ /* > \param[in] LDB */ /* > \verbatim */ /* > LDB is INTEGER */ /* > The leading dimension of the array B. LDB >= max(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in,out] X */ /* > \verbatim */ /* > X is REAL array, dimension (LDX,NRHS) */ /* > On entry, the solution matrix X, as computed by SGETRS. */ /* > On exit, the improved solution matrix X. */ /* > \endverbatim */ /* > */ /* > \param[in] LDX */ /* > \verbatim */ /* > LDX is INTEGER */ /* > The leading dimension of the array X. LDX >= max(1,N). */ /* > \endverbatim */ /* > */ /* > \param[out] RCOND */ /* > \verbatim */ /* > RCOND is REAL */ /* > Reciprocal scaled condition number. This is an estimate of the */ /* > reciprocal Skeel condition number of the matrix A after */ /* > equilibration (if done). If this is less than the machine */ /* > precision (in particular, if it is zero), the matrix is singular */ /* > to working precision. Note that the error may still be small even */ /* > if this number is very small and the matrix appears ill- */ /* > conditioned. */ /* > \endverbatim */ /* > */ /* > \param[out] BERR */ /* > \verbatim */ /* > BERR is REAL array, dimension (NRHS) */ /* > Componentwise relative backward error. This is the */ /* > componentwise relative backward error of each solution vector X(j) */ /* > (i.e., the smallest relative change in any element of A or B that */ /* > makes X(j) an exact solution). */ /* > \endverbatim */ /* > */ /* > \param[in] N_ERR_BNDS */ /* > \verbatim */ /* > N_ERR_BNDS is INTEGER */ /* > Number of error bounds to return for each right hand side */ /* > and each type (normwise or componentwise). See ERR_BNDS_NORM and */ /* > ERR_BNDS_COMP below. */ /* > \endverbatim */ /* > */ /* > \param[out] ERR_BNDS_NORM */ /* > \verbatim */ /* > ERR_BNDS_NORM is REAL array, dimension (NRHS, N_ERR_BNDS) */ /* > For each right-hand side, this array contains information about */ /* > various error bounds and condition numbers corresponding to the */ /* > normwise relative error, which is defined as follows: */ /* > */ /* > Normwise relative error in the ith solution vector: */ /* > max_j (f2c_abs(XTRUE(j,i) - X(j,i))) */ /* > ------------------------------ */ /* > max_j f2c_abs(X(j,i)) */ /* > */ /* > The array is indexed by the type of error information as described */ /* > below. There currently are up to three pieces of information */ /* > returned. */ /* > */ /* > The first index in ERR_BNDS_NORM(i,:) corresponds to the ith */ /* > right-hand side. */ /* > */ /* > The second index in ERR_BNDS_NORM(:,err) contains the following */ /* > three fields: */ /* > err = 1 "Trust/don't trust" boolean. Trust the answer if the */ /* > reciprocal condition number is less than the threshold */ /* > sqrt(n) * slamch('Epsilon'). */ /* > */ /* > err = 2 "Guaranteed" error bound: The estimated forward error, */ /* > almost certainly within a factor of 10 of the true error */ /* > so long as the next entry is greater than the threshold */ /* > sqrt(n) * slamch('Epsilon'). This error bound should only */ /* > be trusted if the previous boolean is true. */ /* > */ /* > err = 3 Reciprocal condition number: Estimated normwise */ /* > reciprocal condition number. Compared with the threshold */ /* > sqrt(n) * slamch('Epsilon') to determine if the error */ /* > estimate is "guaranteed". These reciprocal condition */ /* > numbers are 1 / (norm(Z^{ -1} ,inf) * norm(Z,inf)) for some */ /* > appropriately scaled matrix Z. */ /* > Let Z = S*A, where S scales each row by a power of the */ /* > radix so all absolute row sums of Z are approximately 1. */ /* > */ /* > See Lapack Working Note 165 for further details and extra */ /* > cautions. */ /* > \endverbatim */ /* > */ /* > \param[out] ERR_BNDS_COMP */ /* > \verbatim */ /* > ERR_BNDS_COMP is REAL array, dimension (NRHS, N_ERR_BNDS) */ /* > For each right-hand side, this array contains information about */ /* > various error bounds and condition numbers corresponding to the */ /* > componentwise relative error, which is defined as follows: */ /* > */ /* > Componentwise relative error in the ith solution vector: */ /* > f2c_abs(XTRUE(j,i) - X(j,i)) */ /* > max_j ---------------------- */ /* > f2c_abs(X(j,i)) */ /* > */ /* > The array is indexed by the right-hand side i (on which the */ /* > componentwise relative error depends), and the type of error */ /* > information as described below. There currently are up to three */ /* > pieces of information returned for each right-hand side. If */ /* > componentwise accuracy is not requested (PARAMS(3) = 0.0), then */ /* > ERR_BNDS_COMP is not accessed. If N_ERR_BNDS .LT. 3, then at most */ /* > the first (:,N_ERR_BNDS) entries are returned. */ /* > */ /* > The first index in ERR_BNDS_COMP(i,:) corresponds to the ith */ /* > right-hand side. */ /* > */ /* > The second index in ERR_BNDS_COMP(:,err) contains the following */ /* > three fields: */ /* > err = 1 "Trust/don't trust" boolean. Trust the answer if the */ /* > reciprocal condition number is less than the threshold */ /* > sqrt(n) * slamch('Epsilon'). */ /* > */ /* > err = 2 "Guaranteed" error bound: The estimated forward error, */ /* > almost certainly within a factor of 10 of the true error */ /* > so long as the next entry is greater than the threshold */ /* > sqrt(n) * slamch('Epsilon'). This error bound should only */ /* > be trusted if the previous boolean is true. */ /* > */ /* > err = 3 Reciprocal condition number: Estimated componentwise */ /* > reciprocal condition number. Compared with the threshold */ /* > sqrt(n) * slamch('Epsilon') to determine if the error */ /* > estimate is "guaranteed". These reciprocal condition */ /* > numbers are 1 / (norm(Z^{ -1} ,inf) * norm(Z,inf)) for some */ /* > appropriately scaled matrix Z. */ /* > Let Z = S*(A*diag(x)), where x is the solution for the */ /* > current right-hand side and S scales each row of */ /* > A*diag(x) by a power of the radix so all absolute row */ /* > sums of Z are approximately 1. */ /* > */ /* > See Lapack Working Note 165 for further details and extra */ /* > cautions. */ /* > \endverbatim */ /* > */ /* > \param[in] NPARAMS */ /* > \verbatim */ /* > NPARAMS is INTEGER */ /* > Specifies the number of parameters set in PARAMS. If .LE. 0, the */ /* > PARAMS array is never referenced and default values are used. */ /* > \endverbatim */ /* > */ /* > \param[in,out] PARAMS */ /* > \verbatim */ /* > PARAMS is REAL array, dimension NPARAMS */ /* > Specifies algorithm parameters. If an entry is .LT. 0.0, then */ /* > that entry will be filled with default value used for that */ /* > parameter. Only positions up to NPARAMS are accessed; defaults */ /* > are used for higher-numbered parameters. */ /* > */ /* > PARAMS(LA_LINRX_ITREF_I = 1) : Whether to perform iterative */ /* > refinement or not. */ /* > Default: 1.0 */ /* > = 0.0 : No refinement is performed, and no error bounds are */ /* > computed. */ /* > = 1.0 : Use the double-precision refinement algorithm, */ /* > possibly with doubled-single computations if the */ /* > compilation environment does not support DOUBLE */ /* > PRECISION. */ /* > (other values are reserved for future use) */ /* > */ /* > PARAMS(LA_LINRX_ITHRESH_I = 2) : Maximum number of residual */ /* > computations allowed for refinement. */ /* > Default: 10 */ /* > Aggressive: Set to 100 to permit convergence using approximate */ /* > factorizations or factorizations other than LU. If */ /* > the factorization uses a technique other than */ /* > Gaussian elimination, the guarantees in */ /* > err_bnds_norm and err_bnds_comp may no longer be */ /* > trustworthy. */ /* > */ /* > PARAMS(LA_LINRX_CWISE_I = 3) : Flag determining if the code */ /* > will attempt to find a solution with small componentwise */ /* > relative error in the double-precision algorithm. Positive */ /* > is true, 0.0 is false. */ /* > Default: 1.0 (attempt componentwise convergence) */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is REAL array, dimension (4*N) */ /* > \endverbatim */ /* > */ /* > \param[out] IWORK */ /* > \verbatim */ /* > IWORK is INTEGER array, dimension (N) */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: Successful exit. The solution to every right-hand side is */ /* > guaranteed. */ /* > < 0: If INFO = -i, the i-th argument had an illegal value */ /* > > 0 and <= N: U(INFO,INFO) is exactly zero. The factorization */ /* > has been completed, but the factor U is exactly singular, so */ /* > the solution and error bounds could not be computed. RCOND = 0 */ /* > is returned. */ /* > = N+J: The solution corresponding to the Jth right-hand side is */ /* > not guaranteed. The solutions corresponding to other right- */ /* > hand sides K with K > J may not be guaranteed as well, but */ /* > only the first such right-hand side is reported. If a small */ /* > componentwise error is not requested (PARAMS(3) = 0.0) then */ /* > the Jth right-hand side is the first with a normwise error */ /* > bound that is not guaranteed (the smallest J such */ /* > that ERR_BNDS_NORM(J,1) = 0.0). By default (PARAMS(3) = 1.0) */ /* > the Jth right-hand side is the first with either a normwise or */ /* > componentwise error bound that is not guaranteed (the smallest */ /* > J such that either ERR_BNDS_NORM(J,1) = 0.0 or */ /* > ERR_BNDS_COMP(J,1) = 0.0). See the definition of */ /* > ERR_BNDS_NORM(:,1) and ERR_BNDS_COMP(:,1). To get information */ /* > about all of the right-hand sides check ERR_BNDS_NORM or */ /* > ERR_BNDS_COMP. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date November 2011 */ /* > \ingroup realGEcomputational */ /* ===================================================================== */ /* Subroutine */ int sgerfsx_(char *trans, char *equed, integer *n, integer * nrhs, real *a, integer *lda, real *af, integer *ldaf, integer *ipiv, real *r__, real *c__, real *b, integer *ldb, real *x, integer *ldx, real *rcond, real *berr, integer *n_err_bnds__, real *err_bnds_norm__, real *err_bnds_comp__, integer *nparams, real *params, real *work, integer *iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, af_dim1, af_offset, b_dim1, b_offset, x_dim1, x_offset, err_bnds_norm_dim1, err_bnds_norm_offset, err_bnds_comp_dim1, err_bnds_comp_offset, i__1; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ real illrcond_thresh__, unstable_thresh__, err_lbnd__; integer ref_type__; extern integer ilatrans_(char *); integer j; real rcond_tmp__; integer prec_type__, trans_type__; extern real sla_gercond_(char *, integer *, real *, integer *, real *, integer *, integer *, integer *, real *, integer *, real *, integer *); real cwise_wrong__; extern /* Subroutine */ int sla_gerfsx_extended_(integer *, integer *, integer *, integer *, real *, integer *, real *, integer *, integer *, logical *, real *, real *, integer *, real *, integer * , real *, integer *, real *, real *, real *, real *, real *, real *, real *, integer *, real *, real *, logical *, integer *); char norm[1]; logical ignore_cwise__; extern logical lsame_(char *, char *); real anorm; extern real slamch_(char *), slange_(char *, integer *, integer *, real *, integer *, real *); extern /* Subroutine */ int xerbla_(char *, integer *), sgecon_( char *, integer *, real *, integer *, real *, real *, real *, integer *, integer *); logical colequ, notran, rowequ; extern integer ilaprec_(char *); integer ithresh, n_norms__; real rthresh; /* -- LAPACK computational routine (version 3.4.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* November 2011 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* ================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Check the input parameters. */ /* Parameter adjustments */ err_bnds_comp_dim1 = *nrhs; err_bnds_comp_offset = 1 + err_bnds_comp_dim1; err_bnds_comp__ -= err_bnds_comp_offset; err_bnds_norm_dim1 = *nrhs; err_bnds_norm_offset = 1 + err_bnds_norm_dim1; err_bnds_norm__ -= err_bnds_norm_offset; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; af_dim1 = *ldaf; af_offset = 1 + af_dim1; af -= af_offset; --ipiv; --r__; --c__; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; --berr; --params; --work; --iwork; /* Function Body */ *info = 0; trans_type__ = ilatrans_(trans); ref_type__ = 1; if (*nparams >= 1) { if (params[1] < 0.f) { params[1] = 1.f; } else { ref_type__ = params[1]; } } /* Set default parameters. */ illrcond_thresh__ = (real) (*n) * slamch_("Epsilon"); ithresh = 10; rthresh = .5f; unstable_thresh__ = .25f; ignore_cwise__ = FALSE_; if (*nparams >= 2) { if (params[2] < 0.f) { params[2] = (real) ithresh; } else { ithresh = (integer) params[2]; } } if (*nparams >= 3) { if (params[3] < 0.f) { if (ignore_cwise__) { params[3] = 0.f; } else { params[3] = 1.f; } } else { ignore_cwise__ = params[3] == 0.f; } } if (ref_type__ == 0 || *n_err_bnds__ == 0) { n_norms__ = 0; } else if (ignore_cwise__) { n_norms__ = 1; } else { n_norms__ = 2; } notran = lsame_(trans, "N"); rowequ = lsame_(equed, "R") || lsame_(equed, "B"); colequ = lsame_(equed, "C") || lsame_(equed, "B"); /* Test input parameters. */ if (trans_type__ == -1) { *info = -1; } else if (! rowequ && ! colequ && ! lsame_(equed, "N")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*nrhs < 0) { *info = -4; } else if (*lda < max(1,*n)) { *info = -6; } else if (*ldaf < max(1,*n)) { *info = -8; } else if (*ldb < max(1,*n)) { *info = -13; } else if (*ldx < max(1,*n)) { *info = -15; } if (*info != 0) { i__1 = -(*info); xerbla_("SGERFSX", &i__1); return 0; } /* Quick return if possible. */ if (*n == 0 || *nrhs == 0) { *rcond = 1.f; i__1 = *nrhs; for (j = 1; j <= i__1; ++j) { berr[j] = 0.f; if (*n_err_bnds__ >= 1) { err_bnds_norm__[j + err_bnds_norm_dim1] = 1.f; err_bnds_comp__[j + err_bnds_comp_dim1] = 1.f; } if (*n_err_bnds__ >= 2) { err_bnds_norm__[j + (err_bnds_norm_dim1 << 1)] = 0.f; err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] = 0.f; } if (*n_err_bnds__ >= 3) { err_bnds_norm__[j + err_bnds_norm_dim1 * 3] = 1.f; err_bnds_comp__[j + err_bnds_comp_dim1 * 3] = 1.f; } } return 0; } /* Default to failure. */ *rcond = 0.f; i__1 = *nrhs; for (j = 1; j <= i__1; ++j) { berr[j] = 1.f; if (*n_err_bnds__ >= 1) { err_bnds_norm__[j + err_bnds_norm_dim1] = 1.f; err_bnds_comp__[j + err_bnds_comp_dim1] = 1.f; } if (*n_err_bnds__ >= 2) { err_bnds_norm__[j + (err_bnds_norm_dim1 << 1)] = 1.f; err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] = 1.f; } if (*n_err_bnds__ >= 3) { err_bnds_norm__[j + err_bnds_norm_dim1 * 3] = 0.f; err_bnds_comp__[j + err_bnds_comp_dim1 * 3] = 0.f; } } /* Compute the norm of A and the reciprocal of the condition */ /* number of A. */ if (notran) { *(unsigned char *)norm = 'I'; } else { *(unsigned char *)norm = '1'; } anorm = slange_(norm, n, n, &a[a_offset], lda, &work[1]); sgecon_(norm, n, &af[af_offset], ldaf, &anorm, rcond, &work[1], &iwork[1], info); /* Perform refinement on each right-hand side */ if (ref_type__ != 0) { prec_type__ = ilaprec_("D"); if (notran) { sla_gerfsx_extended_(&prec_type__, &trans_type__, n, nrhs, &a[ a_offset], lda, &af[af_offset], ldaf, &ipiv[1], &colequ, & c__[1], &b[b_offset], ldb, &x[x_offset], ldx, &berr[1], & n_norms__, &err_bnds_norm__[err_bnds_norm_offset], & err_bnds_comp__[err_bnds_comp_offset], &work[*n + 1], & work[1], &work[(*n << 1) + 1], &work[1], rcond, &ithresh, &rthresh, &unstable_thresh__, &ignore_cwise__, info); } else { sla_gerfsx_extended_(&prec_type__, &trans_type__, n, nrhs, &a[ a_offset], lda, &af[af_offset], ldaf, &ipiv[1], &rowequ, & r__[1], &b[b_offset], ldb, &x[x_offset], ldx, &berr[1], & n_norms__, &err_bnds_norm__[err_bnds_norm_offset], & err_bnds_comp__[err_bnds_comp_offset], &work[*n + 1], & work[1], &work[(*n << 1) + 1], &work[1], rcond, &ithresh, &rthresh, &unstable_thresh__, &ignore_cwise__, info); } } /* Computing MAX */ r__1 = 10.f; r__2 = sqrt((real) (*n)); // , expr subst err_lbnd__ = max(r__1,r__2) * slamch_("Epsilon"); if (*n_err_bnds__ >= 1 && n_norms__ >= 1) { /* Compute scaled normwise condition number cond(A*C). */ if (colequ && notran) { rcond_tmp__ = sla_gercond_(trans, n, &a[a_offset], lda, &af[ af_offset], ldaf, &ipiv[1], &c_n1, &c__[1], info, &work[1] , &iwork[1]); } else if (rowequ && ! notran) { rcond_tmp__ = sla_gercond_(trans, n, &a[a_offset], lda, &af[ af_offset], ldaf, &ipiv[1], &c_n1, &r__[1], info, &work[1] , &iwork[1]); } else { rcond_tmp__ = sla_gercond_(trans, n, &a[a_offset], lda, &af[ af_offset], ldaf, &ipiv[1], &c__0, &r__[1], info, &work[1] , &iwork[1]); } i__1 = *nrhs; for (j = 1; j <= i__1; ++j) { /* Cap the error at 1.0. */ if (*n_err_bnds__ >= 2 && err_bnds_norm__[j + (err_bnds_norm_dim1 << 1)] > 1.f) { err_bnds_norm__[j + (err_bnds_norm_dim1 << 1)] = 1.f; } /* Threshold the error (see LAWN). */ if (rcond_tmp__ < illrcond_thresh__) { err_bnds_norm__[j + (err_bnds_norm_dim1 << 1)] = 1.f; err_bnds_norm__[j + err_bnds_norm_dim1] = 0.f; if (*info <= *n) { *info = *n + j; } } else if (err_bnds_norm__[j + (err_bnds_norm_dim1 << 1)] < err_lbnd__) { err_bnds_norm__[j + (err_bnds_norm_dim1 << 1)] = err_lbnd__; err_bnds_norm__[j + err_bnds_norm_dim1] = 1.f; } /* Save the condition number. */ if (*n_err_bnds__ >= 3) { err_bnds_norm__[j + err_bnds_norm_dim1 * 3] = rcond_tmp__; } } } if (*n_err_bnds__ >= 1 && n_norms__ >= 2) { /* Compute componentwise condition number cond(A*diag(Y(:,J))) for */ /* each right-hand side using the current solution as an estimate of */ /* the true solution. If the componentwise error estimate is too */ /* large, then the solution is a lousy estimate of truth and the */ /* estimated RCOND may be too optimistic. To avoid misleading users, */ /* the inverse condition number is set to 0.0 when the estimated */ /* cwise error is at least CWISE_WRONG. */ cwise_wrong__ = sqrt(slamch_("Epsilon")); i__1 = *nrhs; for (j = 1; j <= i__1; ++j) { if (err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] < cwise_wrong__) { rcond_tmp__ = sla_gercond_(trans, n, &a[a_offset], lda, &af[ af_offset], ldaf, &ipiv[1], &c__1, &x[j * x_dim1 + 1], info, &work[1], &iwork[1]); } else { rcond_tmp__ = 0.f; } /* Cap the error at 1.0. */ if (*n_err_bnds__ >= 2 && err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] > 1.f) { err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] = 1.f; } /* Threshold the error (see LAWN). */ if (rcond_tmp__ < illrcond_thresh__) { err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] = 1.f; err_bnds_comp__[j + err_bnds_comp_dim1] = 0.f; if (params[3] == 1.f && *info < *n + j) { *info = *n + j; } } else if (err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] < err_lbnd__) { err_bnds_comp__[j + (err_bnds_comp_dim1 << 1)] = err_lbnd__; err_bnds_comp__[j + err_bnds_comp_dim1] = 1.f; } /* Save the condition number. */ if (*n_err_bnds__ >= 3) { err_bnds_comp__[j + err_bnds_comp_dim1 * 3] = rcond_tmp__; } } } return 0; /* End of SGERFSX */ } /* sgerfsx_ */ #endif
the_stack_data/969750.c
/* * FreeRTOS V202107.00 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #include <stdint.h> extern uint32_t Image$$ER_IROM_FREERTOS_SYSTEM_CALLS$$Base; extern uint32_t Image$$ER_IROM_FREERTOS_SYSTEM_CALLS$$Limit; /* Memory map needed for MPU setup. Must must match the one defined in * the scatter-loading file (FreeRTOSDemo.sct). */ const uint32_t * __FLASH_segment_start__ = ( uint32_t * ) 0x08000000; const uint32_t * __FLASH_segment_end__ = ( uint32_t * ) 0x08200000; const uint32_t * __SRAM_segment_start__ = ( uint32_t * ) 0x20000000; const uint32_t * __SRAM_segment_end__ = ( uint32_t * ) 0x20020000; const uint32_t * __privileged_functions_start__ = ( uint32_t * ) 0x08000000; const uint32_t * __privileged_functions_end__ = ( uint32_t * ) 0x08008000; const uint32_t * __privileged_data_start__ = ( uint32_t * ) 0x20000000; const uint32_t * __privileged_data_end__ = ( uint32_t * ) 0x20008000; const uint32_t * __syscalls_flash_start__ = ( uint32_t * ) &( Image$$ER_IROM_FREERTOS_SYSTEM_CALLS$$Base ); const uint32_t * __syscalls_flash_end__ = ( uint32_t * ) &( Image$$ER_IROM_FREERTOS_SYSTEM_CALLS$$Limit ); /*-----------------------------------------------------------*/ /** * @brief Mem fault handler. */ void MemManage_Handler( void ) __attribute__ (( naked )); /*-----------------------------------------------------------*/ void MemManage_Handler( void ) { __asm volatile ( " tst lr, #4 \n" " ite eq \n" " mrseq r0, msp \n" " mrsne r0, psp \n" " ldr r1, handler_address_const \n" " bx r1 \n" " \n" " .align 4 \n" " handler_address_const: .word vHandleMemoryFault \n" ); } /*-----------------------------------------------------------*/
the_stack_data/57950526.c
#include <unistd.h> volatile int release_flag = 0; int main(int argc, char const *argv[]) { while (! release_flag) // Wait for debugger to attach sleep(3); return 0; }
the_stack_data/792649.c
#include <stdlib.h> #include <stdio.h> void clear_stdin(void); int main(void) { int n; char c; printf("%s","Donnez un nombre entier et un caractere : "); scanf("%d %c", &n, &c); clear_stdin(); printf("n = %d\n", n); printf("c = %c\n", c); return EXIT_SUCCESS; } void clear_stdin(void) { int c; do { c = getchar(); } while (c != '\n' && c != EOF); }
the_stack_data/153337.c
#include <stdio.h> #include <math.h> #include <sys/types.h> #define OUR_PI 3.14159265 int main() { FILE * infile; char line[256]; unsigned long numTargets; unsigned long i; double targetDistance; double angle; /* Open the input file */ infile = fopen("tower.in", "r"); /* Get the number of targets */ fgets(line, sizeof(line), infile); sscanf(line, "%ld", &numTargets); /* Loop through each target */ for (i=0; i < numTargets; i++) { /* Get this target distance */ fgets(line, sizeof(line), infile); sscanf(line, "%lf", &targetDistance); /* Compute the angle needed for this distance. Note that we * are basically creating a triangle with the base being this * targetDistance and the hypotenuse being 56 meters. Taking * the arc-cosine of this distance over the hypotenuse gives * us our answer, but in radians */ angle = acos(targetDistance / 56.0); /* Output the answer angle, but in degrees */ printf("Target #%ld: %.1f degrees\n", i+1, angle * 180.0 / OUR_PI); } /* Close the input file */ fclose(infile); }
the_stack_data/334623.c
/* Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ /* The purpose of this file is to provide implementation of file IO routines on Windows that can be thought as drop-in replacement for corresponding C runtime functionality. Compared to Windows CRT, this one - does not have the same file descriptor limitation (default is 16384 and can be increased further, whereas CRT poses a hard limit of 2048 file descriptors) - the file operations are not serialized - positional IO pread/pwrite is ported here. - no text mode for files, all IO is "binary" Naming convention: All routines are prefixed with my_win_, e.g Posix open() is implemented with my_win_open() Implemented are - POSIX routines(e.g open, read, lseek ...) - Some ANSI C stream routines (fopen, fdopen, fileno, fclose) - Windows CRT equvalients (my_get_osfhandle, open_osfhandle) Worth to note: - File descriptors used here are located in a range that is not compatible with CRT on purpose. Attempt to use a file descriptor from Windows CRT library range in my_win_* function will be punished with DBUG_ASSERT() - File streams (FILE *) are actually from the C runtime. The routines provided here are useful only in scernarios that use low-level IO with my_win_fileno() */ #ifdef _WIN32 #include "mysys_priv.h" #include "my_sys.h" #include "my_thread_local.h" #include <share.h> #include <sys/stat.h> /* Associates a file descriptor with an existing operating-system file handle.*/ File my_open_osfhandle(HANDLE handle, int oflag) { int offset= -1; uint i; DBUG_ENTER("my_open_osfhandle"); mysql_mutex_lock(&THR_LOCK_open); for(i= MY_FILE_MIN; i < my_file_limit;i++) { if(my_file_info[i].fhandle == 0) { struct st_my_file_info *finfo= &(my_file_info[i]); finfo->type= FILE_BY_OPEN; finfo->fhandle= handle; finfo->oflag= oflag; offset= i; break; } } mysql_mutex_unlock(&THR_LOCK_open); if(offset == -1) errno= EMFILE; /* to many file handles open */ DBUG_RETURN(offset); } static void invalidate_fd(File fd) { DBUG_ENTER("invalidate_fd"); DBUG_ASSERT(fd >= MY_FILE_MIN && fd < (int)my_file_limit); my_file_info[fd].fhandle= 0; DBUG_VOID_RETURN; } /* Get Windows handle for a file descriptor */ HANDLE my_get_osfhandle(File fd) { DBUG_ENTER("my_get_osfhandle"); DBUG_ASSERT(fd >= MY_FILE_MIN && fd < (int)my_file_limit); DBUG_RETURN(my_file_info[fd].fhandle); } static int my_get_open_flags(File fd) { DBUG_ENTER("my_get_open_flags"); DBUG_ASSERT(fd >= MY_FILE_MIN && fd < (int)my_file_limit); DBUG_RETURN(my_file_info[fd].oflag); } /* Open a file with sharing. Similar to _sopen() from libc, but allows managing share delete on win32 SYNOPSIS my_win_sopen() path file name oflag operation flags shflag share flag pmode permission flags RETURN VALUE File descriptor of opened file if success -1 and sets errno if fails. */ File my_win_sopen(const char *path, int oflag, int shflag, int pmode) { int fh; /* handle of opened file */ int mask; HANDLE osfh; /* OS handle of opened file */ DWORD fileaccess; /* OS file access (requested) */ DWORD fileshare; /* OS file sharing mode */ DWORD filecreate; /* OS method of opening/creating */ DWORD fileattrib; /* OS file attribute flags */ SECURITY_ATTRIBUTES SecurityAttributes; DBUG_ENTER("my_win_sopen"); if (check_if_legal_filename(path)) { errno= EACCES; DBUG_RETURN(-1); } SecurityAttributes.nLength= sizeof(SecurityAttributes); SecurityAttributes.lpSecurityDescriptor= NULL; SecurityAttributes.bInheritHandle= !(oflag & _O_NOINHERIT); /* decode the access flags */ switch (oflag & (_O_RDONLY | _O_WRONLY | _O_RDWR)) { case _O_RDONLY: /* read access */ fileaccess= GENERIC_READ; break; case _O_WRONLY: /* write access */ fileaccess= GENERIC_WRITE; break; case _O_RDWR: /* read and write access */ fileaccess= GENERIC_READ | GENERIC_WRITE; break; default: /* error, bad oflag */ errno= EINVAL; DBUG_RETURN(-1); } /* decode sharing flags */ switch (shflag) { case _SH_DENYRW: /* exclusive access except delete */ fileshare= FILE_SHARE_DELETE; break; case _SH_DENYWR: /* share read and delete access */ fileshare= FILE_SHARE_READ | FILE_SHARE_DELETE; break; case _SH_DENYRD: /* share write and delete access */ fileshare= FILE_SHARE_WRITE | FILE_SHARE_DELETE; break; case _SH_DENYNO: /* share read, write and delete access */ fileshare= FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; break; case _SH_DENYRWD: /* exclusive access */ fileshare= 0L; break; case _SH_DENYWRD: /* share read access */ fileshare= FILE_SHARE_READ; break; case _SH_DENYRDD: /* share write access */ fileshare= FILE_SHARE_WRITE; break; case _SH_DENYDEL: /* share read and write access */ fileshare= FILE_SHARE_READ | FILE_SHARE_WRITE; break; default: /* error, bad shflag */ errno= EINVAL; DBUG_RETURN(-1); } /* decode open/create method flags */ switch (oflag & (_O_CREAT | _O_EXCL | _O_TRUNC)) { case 0: case _O_EXCL: /* ignore EXCL w/o CREAT */ filecreate= OPEN_EXISTING; break; case _O_CREAT: filecreate= OPEN_ALWAYS; break; case _O_CREAT | _O_EXCL: case _O_CREAT | _O_TRUNC | _O_EXCL: filecreate= CREATE_NEW; break; case _O_TRUNC: case _O_TRUNC | _O_EXCL: /* ignore EXCL w/o CREAT */ filecreate= TRUNCATE_EXISTING; break; case _O_CREAT | _O_TRUNC: filecreate= CREATE_ALWAYS; break; default: /* this can't happen ... all cases are covered */ errno= EINVAL; DBUG_RETURN(-1); } /* decode file attribute flags if _O_CREAT was specified */ fileattrib= FILE_ATTRIBUTE_NORMAL; /* default */ if (oflag & _O_CREAT) { _umask((mask= _umask(0))); if (!((pmode & ~mask) & _S_IWRITE)) fileattrib= FILE_ATTRIBUTE_READONLY; } /* Set temporary file (delete-on-close) attribute if requested. */ if (oflag & _O_TEMPORARY) { fileattrib|= FILE_FLAG_DELETE_ON_CLOSE; fileaccess|= DELETE; } /* Set temporary file (delay-flush-to-disk) attribute if requested.*/ if (oflag & _O_SHORT_LIVED) fileattrib|= FILE_ATTRIBUTE_TEMPORARY; /* Set sequential or random access attribute if requested. */ if (oflag & _O_SEQUENTIAL) fileattrib|= FILE_FLAG_SEQUENTIAL_SCAN; else if (oflag & _O_RANDOM) fileattrib|= FILE_FLAG_RANDOM_ACCESS; /* try to open/create the file */ if ((osfh= CreateFile(path, fileaccess, fileshare, &SecurityAttributes, filecreate, fileattrib, NULL)) == INVALID_HANDLE_VALUE) { /* OS call to open/create file failed! map the error, release the lock, and return -1. note that it's not necessary to call _free_osfhnd (it hasn't been used yet). */ my_osmaperr(GetLastError()); /* map error */ DBUG_RETURN(-1); /* return error to caller */ } if ((fh= my_open_osfhandle(osfh, oflag & (_O_APPEND | _O_RDONLY | _O_TEXT))) == -1) { CloseHandle(osfh); } DBUG_RETURN(fh); /* return handle */ } File my_win_open(const char *path, int flags) { DBUG_ENTER("my_win_open"); DBUG_RETURN(my_win_sopen((char *) path, flags | _O_BINARY, _SH_DENYNO, _S_IREAD | S_IWRITE)); } int my_win_close(File fd) { DBUG_ENTER("my_win_close"); if(CloseHandle(my_get_osfhandle(fd))) { invalidate_fd(fd); DBUG_RETURN(0); } my_osmaperr(GetLastError()); DBUG_RETURN(-1); } size_t my_win_pread(File Filedes, uchar *Buffer, size_t Count, my_off_t offset) { DWORD nBytesRead; HANDLE hFile; OVERLAPPED ov= {0}; LARGE_INTEGER li; DBUG_ENTER("my_win_pread"); if(!Count) DBUG_RETURN(0); #ifdef _WIN64 if(Count > UINT_MAX) Count= UINT_MAX; #endif hFile= (HANDLE)my_get_osfhandle(Filedes); li.QuadPart= offset; ov.Offset= li.LowPart; ov.OffsetHigh= li.HighPart; if(!ReadFile(hFile, Buffer, (DWORD)Count, &nBytesRead, &ov)) { DWORD lastError= GetLastError(); /* ERROR_BROKEN_PIPE is returned when no more data coming through e.g. a command pipe in windows : see MSDN on ReadFile. */ if(lastError == ERROR_HANDLE_EOF || lastError == ERROR_BROKEN_PIPE) DBUG_RETURN(0); /*return 0 at EOF*/ my_osmaperr(lastError); DBUG_RETURN((size_t)-1); } DBUG_RETURN(nBytesRead); } size_t my_win_read(File Filedes, uchar *Buffer, size_t Count) { DWORD nBytesRead; HANDLE hFile; DBUG_ENTER("my_win_read"); if(!Count) DBUG_RETURN(0); #ifdef _WIN64 if(Count > UINT_MAX) Count= UINT_MAX; #endif hFile= (HANDLE)my_get_osfhandle(Filedes); if(!ReadFile(hFile, Buffer, (DWORD)Count, &nBytesRead, NULL)) { DWORD lastError= GetLastError(); /* ERROR_BROKEN_PIPE is returned when no more data coming through e.g. a command pipe in windows : see MSDN on ReadFile. */ if(lastError == ERROR_HANDLE_EOF || lastError == ERROR_BROKEN_PIPE) DBUG_RETURN(0); /*return 0 at EOF*/ my_osmaperr(lastError); DBUG_RETURN((size_t)-1); } DBUG_RETURN(nBytesRead); } size_t my_win_pwrite(File Filedes, const uchar *Buffer, size_t Count, my_off_t offset) { DWORD nBytesWritten; HANDLE hFile; OVERLAPPED ov= {0}; LARGE_INTEGER li; DBUG_ENTER("my_win_pwrite"); DBUG_PRINT("my",("Filedes: %d, Buffer: %p, Count: %llu, offset: %llu", Filedes, Buffer, (ulonglong)Count, (ulonglong)offset)); if(!Count) DBUG_RETURN(0); #ifdef _WIN64 if(Count > UINT_MAX) Count= UINT_MAX; #endif hFile= (HANDLE)my_get_osfhandle(Filedes); li.QuadPart= offset; ov.Offset= li.LowPart; ov.OffsetHigh= li.HighPart; if(!WriteFile(hFile, Buffer, (DWORD)Count, &nBytesWritten, &ov)) { my_osmaperr(GetLastError()); DBUG_RETURN((size_t)-1); } else DBUG_RETURN(nBytesWritten); } my_off_t my_win_lseek(File fd, my_off_t pos, int whence) { LARGE_INTEGER offset; LARGE_INTEGER newpos; DBUG_ENTER("my_win_lseek"); /* Check compatibility of Windows and Posix seek constants */ compile_time_assert(FILE_BEGIN == SEEK_SET && FILE_CURRENT == SEEK_CUR && FILE_END == SEEK_END); offset.QuadPart= pos; if(!SetFilePointerEx(my_get_osfhandle(fd), offset, &newpos, whence)) { my_osmaperr(GetLastError()); newpos.QuadPart= -1; } DBUG_RETURN(newpos.QuadPart); } #ifndef FILE_WRITE_TO_END_OF_FILE #define FILE_WRITE_TO_END_OF_FILE 0xffffffff #endif size_t my_win_write(File fd, const uchar *Buffer, size_t Count) { DWORD nWritten; OVERLAPPED ov; OVERLAPPED *pov= NULL; HANDLE hFile; DBUG_ENTER("my_win_write"); DBUG_PRINT("my",("Filedes: %d, Buffer: %p, Count %llu", fd, Buffer, (ulonglong)Count)); if(!Count) DBUG_RETURN(0); #ifdef _WIN64 if(Count > UINT_MAX) Count= UINT_MAX; #endif if(my_get_open_flags(fd) & _O_APPEND) { /* Atomic append to the end of file is is done by special initialization of the OVERLAPPED structure. See MSDN WriteFile documentation for more info. */ memset(&ov, 0, sizeof(ov)); ov.Offset= FILE_WRITE_TO_END_OF_FILE; ov.OffsetHigh= -1; pov= &ov; } hFile= my_get_osfhandle(fd); if(!WriteFile(hFile, Buffer, (DWORD)Count, &nWritten, pov)) { my_osmaperr(GetLastError()); DBUG_RETURN((size_t)-1); } DBUG_RETURN(nWritten); } int my_win_chsize(File fd, my_off_t newlength) { HANDLE hFile; LARGE_INTEGER length; DBUG_ENTER("my_win_chsize"); hFile= (HANDLE) my_get_osfhandle(fd); length.QuadPart= newlength; if (!SetFilePointerEx(hFile, length , NULL , FILE_BEGIN)) goto err; if (!SetEndOfFile(hFile)) goto err; DBUG_RETURN(0); err: my_osmaperr(GetLastError()); set_my_errno(errno); DBUG_RETURN(-1); } /* Get the file descriptor for stdin,stdout or stderr */ static File my_get_stdfile_descriptor(FILE *stream) { HANDLE hFile; DWORD nStdHandle; DBUG_ENTER("my_get_stdfile_descriptor"); if(stream == stdin) nStdHandle= STD_INPUT_HANDLE; else if(stream == stdout) nStdHandle= STD_OUTPUT_HANDLE; else if(stream == stderr) nStdHandle= STD_ERROR_HANDLE; else DBUG_RETURN(-1); hFile= GetStdHandle(nStdHandle); if(hFile != INVALID_HANDLE_VALUE) DBUG_RETURN(my_open_osfhandle(hFile, 0)); DBUG_RETURN(-1); } File my_win_fileno(FILE *file) { HANDLE hFile= (HANDLE)_get_osfhandle(fileno(file)); int retval= -1; uint i; DBUG_ENTER("my_win_fileno"); for(i= MY_FILE_MIN; i < my_file_limit; i++) { if(my_file_info[i].fhandle == hFile) { retval= i; break; } } if(retval == -1) /* try std stream */ DBUG_RETURN(my_get_stdfile_descriptor(file)); DBUG_RETURN(retval); } FILE *my_win_fopen(const char *filename, const char *type) { FILE *file; int flags= 0; DBUG_ENTER("my_win_open"); /* If we are not creating, then we need to use my_access to make sure the file exists since Windows doesn't handle files like "com1.sym" very well */ if (check_if_legal_filename(filename)) { errno= EACCES; DBUG_RETURN(NULL); } file= fopen(filename, type); if(!file) DBUG_RETURN(NULL); if(strchr(type,'a') != NULL) flags= O_APPEND; /* Register file handle in my_table_info. Necessary for my_fileno() */ if(my_open_osfhandle((HANDLE)_get_osfhandle(fileno(file)), flags) < 0) { fclose(file); DBUG_RETURN(NULL); } DBUG_RETURN(file); } FILE * my_win_fdopen(File fd, const char *type) { FILE *file; int crt_fd; int flags= 0; DBUG_ENTER("my_win_fdopen"); if(strchr(type,'a') != NULL) flags= O_APPEND; /* Convert OS file handle to CRT file descriptor and then call fdopen*/ crt_fd= _open_osfhandle((intptr_t)my_get_osfhandle(fd), flags); if(crt_fd < 0) file= NULL; else file= fdopen(crt_fd, type); DBUG_RETURN(file); } int my_win_fclose(FILE *file) { File fd; DBUG_ENTER("my_win_close"); fd= my_fileno(file); if(fd < 0) DBUG_RETURN(-1); if(fclose(file) < 0) DBUG_RETURN(-1); invalidate_fd(fd); DBUG_RETURN(0); } /* Quick and dirty my_fstat() implementation for Windows. Use CRT fstat on temporarily allocated file descriptor. Patch file size, because size that fstat returns is not reliable (may be outdated) */ int my_win_fstat(File fd, struct _stati64 *buf) { int crt_fd; int retval; HANDLE hFile, hDup; DBUG_ENTER("my_win_fstat"); hFile= my_get_osfhandle(fd); if(!DuplicateHandle( GetCurrentProcess(), hFile, GetCurrentProcess(), &hDup ,0,FALSE,DUPLICATE_SAME_ACCESS)) { my_osmaperr(GetLastError()); DBUG_RETURN(-1); } if ((crt_fd= _open_osfhandle((intptr_t)hDup,0)) < 0) DBUG_RETURN(-1); retval= _fstati64(crt_fd, buf); if(retval == 0) { /* File size returned by stat is not accurate (may be outdated), fix it*/ GetFileSizeEx(hDup, (PLARGE_INTEGER) (&(buf->st_size))); } _close(crt_fd); DBUG_RETURN(retval); } int my_win_stat( const char *path, struct _stati64 *buf) { DBUG_ENTER("my_win_stat"); if(_stati64( path, buf) == 0) { /* File size returned by stat is not accurate (may be outdated), fix it*/ WIN32_FILE_ATTRIBUTE_DATA data; if (GetFileAttributesEx(path, GetFileExInfoStandard, &data)) { LARGE_INTEGER li; li.LowPart= data.nFileSizeLow; li.HighPart= data.nFileSizeHigh; buf->st_size= li.QuadPart; } DBUG_RETURN(0); } DBUG_RETURN(-1); } int my_win_fsync(File fd) { DBUG_ENTER("my_win_fsync"); if(FlushFileBuffers(my_get_osfhandle(fd))) DBUG_RETURN(0); my_osmaperr(GetLastError()); DBUG_RETURN(-1); } int my_win_dup(File fd) { HANDLE hDup; DBUG_ENTER("my_win_dup"); if (DuplicateHandle(GetCurrentProcess(), my_get_osfhandle(fd), GetCurrentProcess(), &hDup, 0, FALSE, DUPLICATE_SAME_ACCESS)) { DBUG_RETURN(my_open_osfhandle(hDup, my_get_open_flags(fd))); } my_osmaperr(GetLastError()); DBUG_RETURN(-1); } #endif /*_WIN32*/
the_stack_data/3781.c
// // Created by zhang on 2017/9/8. // #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> #include <stdlib.h> #include <string.h> struct info { char name[10]; char buf[100]; }; //利用多线程接收发来的信息,可以在任何时候接收信息,包括发信息的时候 void *getmssage(void *p) { int *sockfd = (int *) p; struct info from; while (recv(*sockfd, &from, sizeof(from), 0) > 0) { printf("%s说:%s\n", from.name, from.buf); memset(from.name, 0, sizeof(from.name)); memset(from.buf, 0, sizeof(from.buf)); } } int main() { int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) perror("socket"), exit(-1); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(2222); addr.sin_addr.s_addr = inet_addr("172.30.13.70"); int res = connect(sockfd, (struct sockaddr *) &addr, sizeof(addr)); if (res == -1) perror("connect"), exit(-1); struct info in; printf("请输入用户名:"); scanf("%s", in.name); getchar(); //此时必须要用getchar 因为第 43 行用的是gets接收数据, 38行的scanf函数接收数据的时候碰到 \n就结束了,下面的gets 就会把缓存区的 \n 给接收到, 如果下面用 scanf 接收数据的话,此时就不需要用 getchar了, 因为 scanf 在第一个字符碰到 \n的时候会直接把 \n 给忽略掉 pthread_t pid; pthread_create(pid, 0, getmssage, (void *) &sockfd); while (1) { //scanf("%s",in.buf); gets(in.buf); if (!strcmp(in.buf, "bye")) { strcpy(in.buf, "退出登陆"); send(sockfd, &in, sizeof(in), 0); exit(0); } if (send(sockfd, &in, sizeof(in), 0) == -1) perror("send"), exit(-1); memset(in.buf, 0, strlen(in.buf)); } }